blob: e3674281e03ade19113a2079992d65c5c913fc39 [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
Anders Carlssondde0a942008-09-11 09:15:33 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51{
52 return LocalDeclMap[VD];
53}
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56 return CGM.getTypes().ConvertType(T);
57}
58
Chris Lattner41110242008-06-17 18:05:57 +000059bool CodeGenFunction::isObjCPointerType(QualType T) {
60 // All Objective-C types are pointers.
61 return T->isObjCInterfaceType() ||
62 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63}
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner41110242008-06-17 18:05:57 +000066 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000068}
69
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000070void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000071 // Finish emission of indirect switches.
72 EmitIndirectSwitches();
73
Sanjiv Guptaaf994172008-07-04 11:04:26 +000074 // Emit debug descriptor for function end.
Daniel Dunbar5ca20842008-09-09 21:00:17 +000075 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000076 if (EndLoc.isValid()) {
77 DI->setLocation(EndLoc);
Sanjiv Guptaaf994172008-07-04 11:04:26 +000078 }
79 DI->EmitRegionEnd(CurFn, Builder);
80 }
81
Chris Lattner391d77a2008-03-30 23:03:07 +000082 // Emit a return for code that falls off the end. If insert point
83 // is a dummy block with no predecessors then remove the block itself.
84 llvm::BasicBlock *BB = Builder.GetInsertBlock();
Daniel Dunbar5ca20842008-09-09 21:00:17 +000085 if (isDummyBlock(BB)) {
Chris Lattner391d77a2008-03-30 23:03:07 +000086 BB->eraseFromParent();
Daniel Dunbar5ca20842008-09-09 21:00:17 +000087 } else {
88 // Just transfer to return
89 Builder.CreateBr(ReturnBlock);
Devang Pateld9363c32007-09-28 21:49:18 +000090 }
Chris Lattnerda138702007-07-16 21:28:45 +000091 assert(BreakContinueStack.empty() &&
92 "mismatched push/pop in break/continue stack!");
Daniel Dunbar5ca20842008-09-09 21:00:17 +000093
Daniel Dunbar17b708d2008-09-09 23:27:19 +000094 // Emit function epilog (to return).
Daniel Dunbar5ca20842008-09-09 21:00:17 +000095 Builder.SetInsertPoint(ReturnBlock);
Daniel Dunbar17b708d2008-09-09 23:27:19 +000096 EmitFunctionEpilog(FnRetTy, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +000097
Chris Lattner5a2fa142007-12-02 06:32:24 +000098 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
99 AllocaInsertPt->eraseFromParent();
100 AllocaInsertPt = 0;
101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 // Verify that the function is well formed.
Daniel Dunbarb43f3922008-09-17 21:13:22 +0000103 if (verifyFunction(*CurFn, llvm::PrintMessageAction)) {
104 CurFn->dump();
105 assert(0 && "Function failed verification!");
106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107}
108
Daniel Dunbar7c086512008-09-09 23:14:03 +0000109void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
110 llvm::Function *Fn,
111 const FunctionArgList &Args) {
112 CurFuncDecl = D;
113 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000114 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000115 assert(CurFn->isDeclaration() && "Function already has body?");
116
117 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000118
Chris Lattner41110242008-06-17 18:05:57 +0000119 // Create a marker to make it easy to insert allocas into the entryblock
120 // later. Don't create this with the builder, because we don't want it
121 // folded.
122 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
123 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
124 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000125
126 ReturnBlock = llvm::BasicBlock::Create("return", CurFn);
127 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000128 if (!RetTy->isVoidType())
129 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000130
Chris Lattner41110242008-06-17 18:05:57 +0000131 Builder.SetInsertPoint(EntryBB);
132
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000133 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000134 // FIXME: The cast here is a huge hack.
135 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
136 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
137 CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody());
138 if (body && body->getLBracLoc().isValid()) {
139 DI->setLocation(body->getLBracLoc());
140 }
141 DI->EmitFunctionStart(FD, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000142 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000143 }
144
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000145 EmitFunctionProlog(CurFn, FnRetTy, Args);
Daniel Dunbar7c086512008-09-09 23:14:03 +0000146}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000147
Daniel Dunbar7c086512008-09-09 23:14:03 +0000148void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
149 llvm::Function *Fn) {
150 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000151 if (FD->getNumParams()) {
152 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
153 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000154
155 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
156 Args.push_back(std::make_pair(FD->getParamDecl(i),
157 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000158 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000159
Daniel Dunbar7c086512008-09-09 23:14:03 +0000160 StartFunction(FD, FD->getResultType(), Fn, Args);
161
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000162 EmitStmt(FD->getBody());
163
164 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
165 if (S) {
166 FinishFunction(S->getRBracLoc());
167 } else {
168 FinishFunction();
169 }
Chris Lattner41110242008-06-17 18:05:57 +0000170}
171
Devang Pateld9363c32007-09-28 21:49:18 +0000172/// isDummyBlock - Return true if BB is an empty basic block
173/// with no predecessors.
174bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
Chris Lattner1e9660e2008-07-25 23:40:10 +0000175 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
Devang Pateld9363c32007-09-28 21:49:18 +0000176 return true;
177 return false;
178}
179
Devang Patel51b09f22007-10-04 23:45:31 +0000180/// StartBlock - Start new block named N. If insert block is a dummy block
181/// then reuse it.
182void CodeGenFunction::StartBlock(const char *N) {
183 llvm::BasicBlock *BB = Builder.GetInsertBlock();
184 if (!isDummyBlock(BB))
Gabor Greif984d0b42008-04-06 20:42:52 +0000185 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patel51b09f22007-10-04 23:45:31 +0000186 else
187 BB->setName(N);
188}
189
Devang Patel88a981b2007-11-01 19:11:01 +0000190/// getCGRecordLayout - Return record layout info.
191const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000192 QualType Ty) {
193 const RecordType *RTy = Ty->getAsRecordType();
194 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000195
Chris Lattneraf319132008-02-05 06:55:31 +0000196 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000197}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000198
Daniel Dunbar488e9932008-08-16 00:56:44 +0000199/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000200/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000201void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
202 bool OmitOnError) {
203 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000204}
205
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000206unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
207 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
208 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
209}
210
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000211void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
212{
213 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
214 if (DestPtr->getType() != BP)
215 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
216
217 // Get size and alignment info for this aggregate.
218 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
219
220 // FIXME: Handle variable sized types.
221 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
222
223 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
224 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
225 // TypeInfo.first describes size in bits.
226 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
227 llvm::ConstantInt::get(llvm::Type::Int32Ty,
228 TypeInfo.second/8));
229}
230
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000231void CodeGenFunction::EmitIndirectSwitches() {
232 llvm::BasicBlock *Default;
233
Daniel Dunbar76526a52008-08-04 17:24:44 +0000234 if (IndirectSwitches.empty())
235 return;
236
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000237 if (!LabelIDs.empty()) {
238 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
239 } else {
240 // No possible targets for indirect goto, just emit an infinite
241 // loop.
242 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn);
243 llvm::BranchInst::Create(Default, Default);
244 }
245
246 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
247 e = IndirectSwitches.end(); i != e; ++i) {
248 llvm::SwitchInst *I = *i;
249
250 I->setSuccessor(0, Default);
251 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
252 LE = LabelIDs.end(); LI != LE; ++LI) {
253 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
254 LI->second),
255 getBasicBlockForLabel(LI->first));
256 }
257 }
258}