1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "llvm/Support/CFG.h"
21 using namespace clang;
22 using namespace CodeGen;
23 
24 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
25   : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
26     CaseRangeBlock(NULL) {
27     LLVMIntTy = ConvertType(getContext().IntTy);
28     LLVMPointerWidth = Target.getPointerWidth(0);
29 }
30 
31 ASTContext &CodeGenFunction::getContext() const {
32   return CGM.getContext();
33 }
34 
35 
36 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
37   llvm::BasicBlock *&BB = LabelMap[S];
38   if (BB) return BB;
39 
40   // Create, but don't insert, the new block.
41   return BB = createBasicBlock(S->getName());
42 }
43 
44 llvm::Constant *
45 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
46   return cast<llvm::Constant>(LocalDeclMap[BVD]);
47 }
48 
49 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
50 {
51   return LocalDeclMap[VD];
52 }
53 
54 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
55   return CGM.getTypes().ConvertType(T);
56 }
57 
58 bool CodeGenFunction::isObjCPointerType(QualType T) {
59   // All Objective-C types are pointers.
60   return T->isObjCInterfaceType() ||
61     T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
62 }
63 
64 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
65   return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
66     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
67 }
68 
69 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
70   // Finish emission of indirect switches.
71   EmitIndirectSwitches();
72 
73   // Emit debug descriptor for function end.
74   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
75     DI->setLocation(EndLoc);
76     DI->EmitRegionEnd(CurFn, Builder);
77   }
78 
79   assert(BreakContinueStack.empty() &&
80          "mismatched push/pop in break/continue stack!");
81 
82   // Emit function epilog (to return). This has the nice side effect
83   // of also automatically handling code that falls off the end.
84   EmitBlock(ReturnBlock);
85   EmitFunctionEpilog(FnRetTy, ReturnValue);
86 
87   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
88   AllocaInsertPt->eraseFromParent();
89   AllocaInsertPt = 0;
90 }
91 
92 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
93                                     llvm::Function *Fn,
94                                     const FunctionArgList &Args,
95                                     SourceLocation StartLoc) {
96   CurFuncDecl = D;
97   FnRetTy = RetTy;
98   CurFn = Fn;
99   assert(CurFn->isDeclaration() && "Function already has body?");
100 
101   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
102 
103   // Create a marker to make it easy to insert allocas into the entryblock
104   // later.  Don't create this with the builder, because we don't want it
105   // folded.
106   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
107   AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
108                                          EntryBB);
109 
110   ReturnBlock = createBasicBlock("return");
111   ReturnValue = 0;
112   if (!RetTy->isVoidType())
113     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
114 
115   Builder.SetInsertPoint(EntryBB);
116 
117   // Emit subprogram debug descriptor.
118   // FIXME: The cast here is a huge hack.
119   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
120     DI->setLocation(StartLoc);
121     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
122       DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder);
123     } else {
124       // Just use LLVM function name.
125       DI->EmitFunctionStart(Fn->getName().c_str(),
126                             RetTy, CurFn, Builder);
127     }
128   }
129 
130   EmitFunctionProlog(CurFn, FnRetTy, Args);
131 }
132 
133 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
134                                    llvm::Function *Fn) {
135   FunctionArgList Args;
136   if (FD->getNumParams()) {
137     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
138     assert(FProto && "Function def must have prototype!");
139 
140     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
141       Args.push_back(std::make_pair(FD->getParamDecl(i),
142                                     FProto->getArgType(i)));
143   }
144 
145   StartFunction(FD, FD->getResultType(), Fn, Args,
146                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
147 
148   EmitStmt(FD->getBody());
149 
150   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
151   if (S) {
152     FinishFunction(S->getRBracLoc());
153   } else {
154     FinishFunction();
155   }
156 }
157 
158 /// isDummyBlock - Return true if BB is an empty basic block
159 /// with no predecessors.
160 bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
161   if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
162     return true;
163   return false;
164 }
165 
166 /// ContainsLabel - Return true if the statement contains a label in it.  If
167 /// this statement is not executed normally, it not containing a label means
168 /// that we can just remove the code.
169 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
170   // Null statement, not a label!
171   if (S == 0) return false;
172 
173   // If this is a label, we have to emit the code, consider something like:
174   // if (0) {  ...  foo:  bar(); }  goto foo;
175   if (isa<LabelStmt>(S))
176     return true;
177 
178   // If this is a case/default statement, and we haven't seen a switch, we have
179   // to emit the code.
180   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
181     return true;
182 
183   // If this is a switch statement, we want to ignore cases below it.
184   if (isa<SwitchStmt>(S))
185     IgnoreCaseStmts = true;
186 
187   // Scan subexpressions for verboten labels.
188   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
189        I != E; ++I)
190     if (ContainsLabel(*I, IgnoreCaseStmts))
191       return true;
192 
193   return false;
194 }
195 
196 /// getCGRecordLayout - Return record layout info.
197 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
198                                                          QualType Ty) {
199   const RecordType *RTy = Ty->getAsRecordType();
200   assert (RTy && "Unexpected type. RecordType expected here.");
201 
202   return CGT.getCGRecordLayout(RTy->getDecl());
203 }
204 
205 /// ErrorUnsupported - Print out an error that codegen doesn't support the
206 /// specified stmt yet.
207 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
208                                        bool OmitOnError) {
209   CGM.ErrorUnsupported(S, Type, OmitOnError);
210 }
211 
212 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
213   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
214   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
215 }
216 
217 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
218 {
219   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
220   if (DestPtr->getType() != BP)
221     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
222 
223   // Get size and alignment info for this aggregate.
224   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
225 
226   // FIXME: Handle variable sized types.
227   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
228 
229   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
230                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
231                       // TypeInfo.first describes size in bits.
232                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
233                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
234                                              TypeInfo.second/8));
235 }
236 
237 void CodeGenFunction::EmitIndirectSwitches() {
238   llvm::BasicBlock *Default;
239 
240   if (IndirectSwitches.empty())
241     return;
242 
243   if (!LabelIDs.empty()) {
244     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
245   } else {
246     // No possible targets for indirect goto, just emit an infinite
247     // loop.
248     Default = createBasicBlock("indirectgoto.loop", CurFn);
249     llvm::BranchInst::Create(Default, Default);
250   }
251 
252   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
253          e = IndirectSwitches.end(); i != e; ++i) {
254     llvm::SwitchInst *I = *i;
255 
256     I->setSuccessor(0, Default);
257     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
258            LE = LabelIDs.end(); LI != LE; ++LI) {
259       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
260                                         LI->second),
261                  getBasicBlockForLabel(LI->first));
262     }
263   }
264 }
265 
266 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
267 {
268   // FIXME: This entire method is hardcoded for 32-bit X86.
269 
270   const char *TargetPrefix = getContext().Target.getTargetPrefix();
271 
272   if (strcmp(TargetPrefix, "x86") != 0 ||
273       getContext().Target.getPointerWidth(0) != 32)
274     return 0;
275 
276   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
277   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
278 
279   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
280                                                        "ap");
281   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
282   llvm::Value *AddrTyped =
283     Builder.CreateBitCast(Addr,
284                           llvm::PointerType::getUnqual(ConvertType(Ty)));
285 
286   uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
287   const unsigned ArgumentSizeInBytes = 4;
288   if (SizeInBytes < ArgumentSizeInBytes)
289     SizeInBytes = ArgumentSizeInBytes;
290 
291   llvm::Value *NextAddr =
292     Builder.CreateGEP(Addr,
293                       llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
294                       "ap.next");
295   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
296 
297   return AddrTyped;
298 }
299 
300