blob: a934e43e48034b931e9a2dc8fa38852ea84b1601 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/Analysis/Verifier.h"
Devang Pateld9363c32007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000026 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner41110242008-06-17 18:05:57 +000027 CaseRangeBlock(NULL) {
28 LLVMIntTy = ConvertType(getContext().IntTy);
29 LLVMPointerWidth = Target.getPointerWidth(0);
30}
Reid Spencer5f016e22007-07-11 17:01:13 +000031
32ASTContext &CodeGenFunction::getContext() const {
33 return CGM.getContext();
34}
35
36
37llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38 llvm::BasicBlock *&BB = LabelMap[S];
39 if (BB) return BB;
40
41 // Create, but don't insert, the new block.
Gabor Greif984d0b42008-04-06 20:42:52 +000042 return BB = llvm::BasicBlock::Create(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff248a7532008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
51 return CGM.getTypes().ConvertType(T);
52}
53
Chris Lattner41110242008-06-17 18:05:57 +000054bool CodeGenFunction::isObjCPointerType(QualType T) {
55 // All Objective-C types are pointers.
56 return T->isObjCInterfaceType() ||
57 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
58}
59
Reid Spencer5f016e22007-07-11 17:01:13 +000060bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner41110242008-06-17 18:05:57 +000061 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
62 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000063}
64
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000065void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000066 // Finish emission of indirect switches.
67 EmitIndirectSwitches();
68
Sanjiv Guptaaf994172008-07-04 11:04:26 +000069 // Emit debug descriptor for function end.
Daniel Dunbar5ca20842008-09-09 21:00:17 +000070 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000071 if (EndLoc.isValid()) {
72 DI->setLocation(EndLoc);
Sanjiv Guptaaf994172008-07-04 11:04:26 +000073 }
74 DI->EmitRegionEnd(CurFn, Builder);
75 }
76
Chris Lattner391d77a2008-03-30 23:03:07 +000077 // Emit a return for code that falls off the end. If insert point
78 // is a dummy block with no predecessors then remove the block itself.
79 llvm::BasicBlock *BB = Builder.GetInsertBlock();
Daniel Dunbar5ca20842008-09-09 21:00:17 +000080 if (isDummyBlock(BB)) {
Chris Lattner391d77a2008-03-30 23:03:07 +000081 BB->eraseFromParent();
Daniel Dunbar5ca20842008-09-09 21:00:17 +000082 } else {
83 // Just transfer to return
84 Builder.CreateBr(ReturnBlock);
Devang Pateld9363c32007-09-28 21:49:18 +000085 }
Chris Lattnerda138702007-07-16 21:28:45 +000086 assert(BreakContinueStack.empty() &&
87 "mismatched push/pop in break/continue stack!");
Daniel Dunbar5ca20842008-09-09 21:00:17 +000088
89 // Emit code to actually return.
90 Builder.SetInsertPoint(ReturnBlock);
91 if (!ReturnValue) {
92 Builder.CreateRetVoid();
93 } else {
94 if (!hasAggregateLLVMType(FnRetTy)) {
95 Builder.CreateRet(Builder.CreateLoad(ReturnValue));
96 } else if (FnRetTy->isAnyComplexType()) {
97 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, FnRetTy);
98 Builder.CreateRetVoid();
99 } else {
100 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, FnRetTy);
101 Builder.CreateRetVoid();
102 }
103 }
104
Chris Lattner5a2fa142007-12-02 06:32:24 +0000105 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
106 AllocaInsertPt->eraseFromParent();
107 AllocaInsertPt = 0;
108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 // Verify that the function is well formed.
Chris Lattner391d77a2008-03-30 23:03:07 +0000110 assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
112
Daniel Dunbar7c086512008-09-09 23:14:03 +0000113void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
114 llvm::Function *Fn,
115 const FunctionArgList &Args) {
116 CurFuncDecl = D;
117 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000118 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000119 assert(CurFn->isDeclaration() && "Function already has body?");
120
121 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000122
Chris Lattner41110242008-06-17 18:05:57 +0000123 // Create a marker to make it easy to insert allocas into the entryblock
124 // later. Don't create this with the builder, because we don't want it
125 // folded.
126 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
127 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
128 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000129
130 ReturnBlock = llvm::BasicBlock::Create("return", CurFn);
131 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000132 if (!RetTy->isVoidType())
133 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000134
Chris Lattner41110242008-06-17 18:05:57 +0000135 Builder.SetInsertPoint(EntryBB);
136
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000137 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000138 // FIXME: The cast here is a huge hack.
139 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
140 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
141 CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody());
142 if (body && body->getLBracLoc().isValid()) {
143 DI->setLocation(body->getLBracLoc());
144 }
145 DI->EmitFunctionStart(FD, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000146 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000147 }
148
Chris Lattner41110242008-06-17 18:05:57 +0000149 // Emit allocs for param decls. Give the LLVM Argument nodes names.
150 llvm::Function::arg_iterator AI = CurFn->arg_begin();
151
152 // Name the struct return argument.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000153 if (hasAggregateLLVMType(FnRetTy)) {
Chris Lattner41110242008-06-17 18:05:57 +0000154 AI->setName("agg.result");
155 ++AI;
156 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000157
158 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
159 i != e; ++i, ++AI) {
160 const VarDecl *Arg = i->first;
161 QualType T = i->second;
162 assert(AI != CurFn->arg_end() && "Argument mismatch!");
163 llvm::Value* V = AI;
164 if (!getContext().typesAreCompatible(T, Arg->getType())) {
165 // This must be a promotion, for something like
166 // "void a(x) short x; {..."
167 V = EmitScalarConversion(V, T, Arg->getType());
168 }
169 EmitParmDecl(*Arg, V);
170 }
171 assert(AI == CurFn->arg_end() && "Argument mismatch!");
172}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000173
Daniel Dunbar7c086512008-09-09 23:14:03 +0000174void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
175 llvm::Function *Fn) {
176 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000177 if (FD->getNumParams()) {
178 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
179 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000180
181 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
182 Args.push_back(std::make_pair(FD->getParamDecl(i),
183 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000184 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000185
Daniel Dunbar7c086512008-09-09 23:14:03 +0000186 StartFunction(FD, FD->getResultType(), Fn, Args);
187
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000188 EmitStmt(FD->getBody());
189
190 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
191 if (S) {
192 FinishFunction(S->getRBracLoc());
193 } else {
194 FinishFunction();
195 }
Chris Lattner41110242008-06-17 18:05:57 +0000196}
197
Devang Pateld9363c32007-09-28 21:49:18 +0000198/// isDummyBlock - Return true if BB is an empty basic block
199/// with no predecessors.
200bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
Chris Lattner1e9660e2008-07-25 23:40:10 +0000201 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
Devang Pateld9363c32007-09-28 21:49:18 +0000202 return true;
203 return false;
204}
205
Devang Patel51b09f22007-10-04 23:45:31 +0000206/// StartBlock - Start new block named N. If insert block is a dummy block
207/// then reuse it.
208void CodeGenFunction::StartBlock(const char *N) {
209 llvm::BasicBlock *BB = Builder.GetInsertBlock();
210 if (!isDummyBlock(BB))
Gabor Greif984d0b42008-04-06 20:42:52 +0000211 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patel51b09f22007-10-04 23:45:31 +0000212 else
213 BB->setName(N);
214}
215
Devang Patel88a981b2007-11-01 19:11:01 +0000216/// getCGRecordLayout - Return record layout info.
217const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000218 QualType Ty) {
219 const RecordType *RTy = Ty->getAsRecordType();
220 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000221
Chris Lattneraf319132008-02-05 06:55:31 +0000222 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000223}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000224
Daniel Dunbar488e9932008-08-16 00:56:44 +0000225/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000226/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000227void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
228 bool OmitOnError) {
229 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000230}
231
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000232unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
233 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
234 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
235}
236
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000237void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
238{
239 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
240 if (DestPtr->getType() != BP)
241 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
242
243 // Get size and alignment info for this aggregate.
244 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
245
246 // FIXME: Handle variable sized types.
247 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
248
249 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
250 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
251 // TypeInfo.first describes size in bits.
252 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
253 llvm::ConstantInt::get(llvm::Type::Int32Ty,
254 TypeInfo.second/8));
255}
256
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000257void CodeGenFunction::EmitIndirectSwitches() {
258 llvm::BasicBlock *Default;
259
Daniel Dunbar76526a52008-08-04 17:24:44 +0000260 if (IndirectSwitches.empty())
261 return;
262
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000263 if (!LabelIDs.empty()) {
264 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
265 } else {
266 // No possible targets for indirect goto, just emit an infinite
267 // loop.
268 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn);
269 llvm::BranchInst::Create(Default, Default);
270 }
271
272 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
273 e = IndirectSwitches.end(); i != e; ++i) {
274 llvm::SwitchInst *I = *i;
275
276 I->setSuccessor(0, Default);
277 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
278 LE = LabelIDs.end(); LI != LE; ++LI) {
279 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
280 LI->second),
281 getBasicBlockForLabel(LI->first));
282 }
283 }
284}