Files
swift-mirror/lib/IRGen/GenDecl.cpp
John McCall 85fecab3b1 Reorganize the emission of a call site so that it's abstracted over
exactly how the arguments are emitted.  Introduce a new code path
which emits arguments from existing Explosions (possibly of the wrong
resilience level).  Use that code path to implement getter/setter
code for MemberRefExpr l-values.  This is just a checkpoint for the
latter two parts, but the ApplyExpr path is working correctly in the
new framework, which is worth a commit.

Swift SVN r1589
2012-04-24 08:16:51 +00:00

450 lines
15 KiB
C++

//===--- GenDecl.cpp - IR Generation for Declarations ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for local and global
// declarations in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "llvm/Module.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "Linking.h"
#include "LValue.h"
using namespace swift;
using namespace irgen;
static bool isTrivialGlobalInit(llvm::Function *fn) {
// Must be exactly one basic block.
if (next(fn->begin()) != fn->end()) return false;
// Basic block must have exactly one instruction.
llvm::BasicBlock *entry = &fn->getEntryBlock();
if (next(entry->begin()) != entry->end()) return false;
// That instruction is necessarily a 'ret' instruction.
assert(isa<llvm::ReturnInst>(entry->front()));
return true;
}
/// Emit all the top-level code in the translation unit.
void IRGenModule::emitTranslationUnit(TranslationUnit *tunit,
unsigned StartElem) {
Type emptyTuple = TupleType::getEmpty(Context);
FunctionType *unitToUnit = FunctionType::get(emptyTuple, emptyTuple, Context);
Pattern *params[] = {
TuplePattern::create(Context, SourceLoc(),
llvm::ArrayRef<TuplePatternElt>(), SourceLoc())
};
llvm::FunctionType *fnType =
getFunctionType(unitToUnit, ExplosionKind::Minimal, 0, false);
llvm::Function *fn;
if (tunit->IsMainModule) {
// For the main module, just emit main().
fn = llvm::Function::Create(fnType, llvm::GlobalValue::ExternalLinkage,
"main", &Module);
} else {
// Otherwise, create a global initializer.
// FIXME: This is completely, utterly, wrong.
fn = llvm::Function::Create(fnType, llvm::GlobalValue::ExternalLinkage,
tunit->Name.str() + ".init", &Module);
}
IRGenFunction(*this, unitToUnit, params, ExplosionKind::Minimal,
/*uncurry*/ 0, fn)
.emitGlobalTopLevel(tunit, StartElem);
// We don't need global init to call main().
if (tunit->IsMainModule)
return;
// Not all translation units need a global initialization function.
if (isTrivialGlobalInit(fn)) {
fn->eraseFromParent();
return;
}
// Build the initializer for the global variable.
llvm::Constant *initAndPriority[] = {
llvm::ConstantInt::get(Int32Ty, 0),
fn
};
llvm::Constant *allInits[] = {
llvm::ConstantStruct::getAnon(LLVMContext, initAndPriority)
};
llvm::Constant *globalInits =
llvm::ConstantArray::get(llvm::ArrayType::get(allInits[0]->getType(), 1),
allInits);
// Add this as a global initializer.
(void) new llvm::GlobalVariable(Module,
globalInits->getType(),
/*is constant*/ true,
llvm::GlobalValue::AppendingLinkage,
globalInits,
"llvm.global_ctors");
}
void IRGenFunction::emitGlobalTopLevel(TranslationUnit *TU, unsigned StartElem) {
for (unsigned i = StartElem, e = TU->Decls.size(); i != e; ++i) {
assert(Builder.hasValidIP());
emitGlobalDecl(TU->Decls[i]);
}
}
LinkInfo LinkInfo::get(IRGenModule &IGM, const LinkEntity &entity) {
LinkInfo result;
llvm::raw_svector_ostream nameStream(result.Name);
entity.mangle(nameStream);
// TODO, obviously.
result.Linkage = llvm::GlobalValue::ExternalLinkage;
result.Visibility = llvm::GlobalValue::DefaultVisibility;
return result;
}
/// Emit a global declaration.
void IRGenFunction::emitGlobalDecl(Decl *D) {
switch (D->getKind()) {
case DeclKind::Extension:
IGM.emitExtension(cast<ExtensionDecl>(D));
return;
case DeclKind::PatternBinding:
emitPatternBindingDecl(cast<PatternBindingDecl>(D));
return;
case DeclKind::Subscript:
llvm_unreachable("there are no global subscript operations");
// oneof elements can be found at the top level because of struct
// "constructor" injection. Just ignore them here; we'll get them
// as part of the struct.
case DeclKind::OneOfElement:
return;
// Type aliases require IR-gen support if they're really a struct/oneof
// declaration.
case DeclKind::TypeAlias:
return IGM.emitTypeAlias(cast<TypeAliasDecl>(D)->getUnderlyingType());
// These declarations don't require IR-gen support.
case DeclKind::Import:
return;
// We emit these as part of the PatternBindingDecl.
case DeclKind::Var:
return;
case DeclKind::Func:
return IGM.emitGlobalFunction(cast<FuncDecl>(D));
case DeclKind::TopLevelCode: {
auto Body = cast<TopLevelCodeDecl>(D)->getBody();
if (Body.is<Expr*>())
return emitIgnored(Body.get<Expr*>());
return emitStmt(Body.get<Stmt*>());
}
}
llvm_unreachable("bad decl kind!");
}
/// Find the address of a (fragile, constant-size) global variable
/// declaration. The address value is always an llvm::GlobalVariable*.
Address IRGenModule::getAddrOfGlobalVariable(VarDecl *var) {
// Check whether we've cached this.
llvm::GlobalVariable *&entry = GlobalVars[var];
if (entry) {
llvm::GlobalVariable *gv = cast<llvm::GlobalVariable>(entry);
return Address(gv, Alignment(gv->getAlignment()));
}
const TypeInfo &type = getFragileTypeInfo(var->getType());
// Okay, we need to rebuild it.
LinkInfo link = LinkInfo::get(*this, LinkEntity::forNonFunction(var));
llvm::GlobalVariable *addr
= new llvm::GlobalVariable(Module, type.StorageType, /*constant*/ false,
link.getLinkage(), /*initializer*/ nullptr,
link.getName());
addr->setVisibility(link.getVisibility());
Alignment align = type.StorageAlignment;
addr->setAlignment(align.getValue());
entry = addr;
return Address(addr, align);
}
/// Fetch the declaration of the given global function.
llvm::Function *IRGenModule::getAddrOfGlobalFunction(FuncDecl *func,
ExplosionKind kind,
unsigned uncurryLevel) {
LinkEntity entity = LinkEntity::forFunction(func, kind, uncurryLevel);
// Check whether we've cached this.
llvm::Function *&entry = GlobalFuncs[entity];
if (entry) return cast<llvm::Function>(entry);
llvm::FunctionType *fnType =
getFunctionType(func->getType(), kind, uncurryLevel, /*data*/ false);
LinkInfo link = LinkInfo::get(*this, entity);
llvm::Function *addr
= cast<llvm::Function>(Module.getOrInsertFunction(link.getName(), fnType));
addr->setLinkage(link.getLinkage());
addr->setVisibility(link.getVisibility());
entry = addr;
return addr;
}
/// getAddrOfInjectionFunction - Get the address of the function to
/// perform a particular injection into a oneof type.
llvm::Function *
IRGenModule::getAddrOfInjectionFunction(OneOfElementDecl *D) {
LinkEntity entity = LinkEntity::forFunction(D, ExplosionKind::Minimal, 0);
llvm::Function *&entry = GlobalFuncs[entity];
if (entry) return cast<llvm::Function>(entry);
// The formal type of the function is generally the type of the decl,
// but if that's not a function type, it's () -> that.
Type formalType = D->getType();
if (!isa<FunctionType>(formalType)) {
formalType = FunctionType::get(TupleType::getEmpty(Context),
formalType, Context);
}
// FIXME: pick the explosion kind better!
llvm::FunctionType *fnType =
getFunctionType(formalType, ExplosionKind::Minimal, /*uncurry*/ 0,
/*data*/ false);
LinkInfo link = LinkInfo::get(*this, entity);
llvm::Function *addr
= cast<llvm::Function>(Module.getOrInsertFunction(link.getName(), fnType));
addr->setLinkage(link.getLinkage());
addr->setVisibility(link.getVisibility());
entry = addr;
return addr;
}
static Type addOwnerArgument(ASTContext &ctx, Type owner, Type resultType) {
Type argType = owner;
if (!argType->hasReferenceSemantics()) {
argType = LValueType::get(argType, LValueType::Qual::DefaultForGetSet, ctx);
}
return FunctionType::get(argType, resultType, ctx);
}
static Type addOwnerArgument(ASTContext &ctx, ValueDecl *value,
Type resultType) {
DeclContext *DC = value->getDeclContext();
switch (DC->getContextKind()) {
case DeclContextKind::TranslationUnit:
case DeclContextKind::BuiltinModule:
case DeclContextKind::CapturingExpr:
case DeclContextKind::TopLevelCodeDecl:
return resultType;
case DeclContextKind::ExtensionDecl:
return addOwnerArgument(ctx, cast<ExtensionDecl>(DC)->getExtendedType(),
resultType);
case DeclContextKind::OneOfType:
return addOwnerArgument(ctx, cast<OneOfType>(DC), resultType);
case DeclContextKind::ProtocolType:
return addOwnerArgument(ctx, cast<ProtocolType>(DC), resultType);
}
llvm_unreachable("bad decl context");
}
/// getAddrOfGetter - Get the address of the function which performs a
/// get or set.
llvm::Function *IRGenModule::getAddrOfGetter(VarDecl *var,
ExplosionKind explosionLevel) {
LinkEntity entity = LinkEntity::forGetter(var, explosionLevel);
llvm::Function *&entry = GlobalFuncs[entity];
if (entry) return cast<llvm::Function>(entry);
// The formal type of a getter function is one of:
// () -> T (for a nontype member)
// ([byref] A) -> () -> T (for a type member)
Type formalType = var->getType();
formalType = FunctionType::get(TupleType::getEmpty(Context),
formalType, Context);
formalType = addOwnerArgument(Context, var, formalType);
llvm::FunctionType *fnType =
getFunctionType(formalType, explosionLevel, /*uncurry*/ 1,
/*data*/ false);
LinkInfo link = LinkInfo::get(*this, entity);
llvm::Function *addr
= cast<llvm::Function>(Module.getOrInsertFunction(link.getName(), fnType));
addr->setLinkage(link.getLinkage());
addr->setVisibility(link.getVisibility());
entry = addr;
return addr;
}
/// getAddrOfGetter - Get the address of the function which performs a
/// get or set.
llvm::Function *IRGenModule::getAddrOfSetter(VarDecl *var,
ExplosionKind explosionLevel) {
LinkEntity entity = LinkEntity::forSetter(var, explosionLevel);
llvm::Function *&entry = GlobalFuncs[entity];
if (entry) return cast<llvm::Function>(entry);
// The formal type of a setter function is one of:
// T -> () (for a nontype member)
// ([byref] A) -> T -> () (for a type member)
Type formalType = var->getType();
formalType = FunctionType::get(formalType, TupleType::getEmpty(Context),
Context);
formalType = addOwnerArgument(Context, var, formalType);
llvm::FunctionType *fnType =
getFunctionType(formalType, explosionLevel, /*uncurry*/ 1,
/*data*/ false);
LinkInfo link = LinkInfo::get(*this, entity);
llvm::Function *addr
= cast<llvm::Function>(Module.getOrInsertFunction(link.getName(), fnType));
addr->setLinkage(link.getLinkage());
addr->setVisibility(link.getVisibility());
entry = addr;
return addr;
}
LValue IRGenFunction::getGlobal(VarDecl *var) {
OwnedAddress addr(IGM.getAddrOfGlobalVariable(var), IGM.RefCountedNull);
return emitAddressLValue(addr);
}
/// Emit a type extension.
void IRGenModule::emitExtension(ExtensionDecl *ext) {
for (Decl *member : ext->getMembers()) {
switch (member->getKind()) {
case DeclKind::Import:
case DeclKind::OneOfElement:
case DeclKind::PatternBinding:
case DeclKind::TopLevelCode:
llvm_unreachable("decl not allowed in extension!");
case DeclKind::Subscript:
// Getter/setter will be handled separately.
continue;
case DeclKind::Extension:
emitExtension(cast<ExtensionDecl>(member));
continue;
case DeclKind::TypeAlias:
emitTypeAlias(cast<TypeAliasDecl>(member)->getUnderlyingType());
continue;
case DeclKind::Var:
unimplemented(member->getLocStart(), "var decl in extension");
continue;
case DeclKind::Func: {
FuncDecl *func = cast<FuncDecl>(member);
if (func->isStatic()) {
// Eventually this won't always be the right thing.
emitStaticMethod(func);
} else {
emitInstanceMethod(func);
}
continue;
}
}
llvm_unreachable("bad extension member kind");
}
}
void IRGenFunction::emitLocal(Decl *D) {
switch (D->getKind()) {
case DeclKind::Import:
case DeclKind::Subscript:
case DeclKind::TopLevelCode:
llvm_unreachable("declaration cannot appear in local scope");
// Type aliases require IR-gen support if they're really
// struct/oneof declarations.
case DeclKind::TypeAlias:
return IGM.emitTypeAlias(cast<TypeAliasDecl>(D)->getUnderlyingType());
case DeclKind::OneOfElement:
// no IR generation support required.
return;
case DeclKind::Var:
// We handle these in pattern-binding.
return;
case DeclKind::Extension:
unimplemented(D->getLocStart(), "local extension emission");
return;
case DeclKind::Func:
unimplemented(D->getLocStart(), "local function emission");
return;
case DeclKind::PatternBinding:
emitPatternBindingDecl(cast<PatternBindingDecl>(D));
return;
}
llvm_unreachable("bad declaration kind!");
}
OwnedAddress IRGenFunction::getLocal(ValueDecl *D) {
auto I = Locals.find(D);
assert(I != Locals.end() && "no entry in local map!");
return I->second.Var.Addr;
}
void IRGenFunction::setLocal(ValueDecl *D, OwnedAddress addr) {
assert(!Locals.count(D));
std::pair<ValueDecl*, LocalRecord> entry;
entry.first = D;
entry.second.Var.Addr = addr;
Locals.insert(entry);
}
/// Create an allocation on the stack.
Address IRGenFunction::createAlloca(llvm::Type *type,
Alignment alignment,
const llvm::Twine &name) {
llvm::AllocaInst *alloca = new llvm::AllocaInst(type, name, AllocaIP);
alloca->setAlignment(alignment.getValue());
return Address(alloca, alignment);
}