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/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "llvm/Support/CFG.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
26   : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
27     CaseRangeBlock(NULL) {
28     LLVMIntTy = ConvertType(getContext().IntTy);
29     LLVMPointerWidth = Target.getPointerWidth(0);
30 }
31 
32 ASTContext &CodeGenFunction::getContext() const {
33   return CGM.getContext();
34 }
35 
36 
37 llvm::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.
42   return BB = createBasicBlock(S->getName());
43 }
44 
45 llvm::Constant *
46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
47   return cast<llvm::Constant>(LocalDeclMap[BVD]);
48 }
49 
50 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51 {
52   return LocalDeclMap[VD];
53 }
54 
55 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56   return CGM.getTypes().ConvertType(T);
57 }
58 
59 bool CodeGenFunction::isObjCPointerType(QualType T) {
60   // All Objective-C types are pointers.
61   return T->isObjCInterfaceType() ||
62     T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63 }
64 
65 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
66   return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
68 }
69 
70 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
71   // Finish emission of indirect switches.
72   EmitIndirectSwitches();
73 
74   assert(BreakContinueStack.empty() &&
75          "mismatched push/pop in break/continue stack!");
76 
77   // Emit function epilog (to return). This has the nice side effect
78   // of also automatically handling code that falls off the end.
79   EmitBlock(ReturnBlock);
80 
81   // Emit debug descriptor for function end.
82   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
83     DI->setLocation(EndLoc);
84     DI->EmitRegionEnd(CurFn, Builder);
85   }
86 
87   EmitFunctionEpilog(FnRetTy, ReturnValue);
88 
89   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
90   AllocaInsertPt->eraseFromParent();
91   AllocaInsertPt = 0;
92 }
93 
94 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
95                                     llvm::Function *Fn,
96                                     const FunctionArgList &Args,
97                                     SourceLocation StartLoc) {
98   CurFuncDecl = D;
99   FnRetTy = RetTy;
100   CurFn = Fn;
101   assert(CurFn->isDeclaration() && "Function already has body?");
102 
103   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
104 
105   // Create a marker to make it easy to insert allocas into the entryblock
106   // later.  Don't create this with the builder, because we don't want it
107   // folded.
108   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
109   AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
110                                          EntryBB);
111 
112   ReturnBlock = createBasicBlock("return");
113   ReturnValue = 0;
114   if (!RetTy->isVoidType())
115     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
116 
117   Builder.SetInsertPoint(EntryBB);
118 
119   // Emit subprogram debug descriptor.
120   // FIXME: The cast here is a huge hack.
121   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
122     DI->setLocation(StartLoc);
123     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
124       DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder);
125     } else {
126       // Just use LLVM function name.
127       DI->EmitFunctionStart(Fn->getName().c_str(),
128                             RetTy, CurFn, Builder);
129     }
130   }
131 
132   EmitFunctionProlog(CurFn, FnRetTy, Args);
133 }
134 
135 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
136                                    llvm::Function *Fn) {
137   FunctionArgList Args;
138   if (FD->getNumParams()) {
139     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
140     assert(FProto && "Function def must have prototype!");
141 
142     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
143       Args.push_back(std::make_pair(FD->getParamDecl(i),
144                                     FProto->getArgType(i)));
145   }
146 
147   StartFunction(FD, FD->getResultType(), Fn, Args,
148                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
149 
150   EmitStmt(FD->getBody());
151 
152   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
153   if (S) {
154     FinishFunction(S->getRBracLoc());
155   } else {
156     FinishFunction();
157   }
158 }
159 
160 /// ContainsLabel - Return true if the statement contains a label in it.  If
161 /// this statement is not executed normally, it not containing a label means
162 /// that we can just remove the code.
163 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
164   // Null statement, not a label!
165   if (S == 0) return false;
166 
167   // If this is a label, we have to emit the code, consider something like:
168   // if (0) {  ...  foo:  bar(); }  goto foo;
169   if (isa<LabelStmt>(S))
170     return true;
171 
172   // If this is a case/default statement, and we haven't seen a switch, we have
173   // to emit the code.
174   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
175     return true;
176 
177   // If this is a switch statement, we want to ignore cases below it.
178   if (isa<SwitchStmt>(S))
179     IgnoreCaseStmts = true;
180 
181   // Scan subexpressions for verboten labels.
182   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
183        I != E; ++I)
184     if (ContainsLabel(*I, IgnoreCaseStmts))
185       return true;
186 
187   return false;
188 }
189 
190 
191 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
192 /// a constant, or if it does but contains a label, return 0.  If it constant
193 /// folds to 'true' and does not contain a label, return 1, if it constant folds
194 /// to 'false' and does not contain a label, return -1.
195 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
196   APValue V;
197   if (!Cond->tryEvaluate(V, getContext()))
198     return 0;  // Not foldable.
199 
200   if (CodeGenFunction::ContainsLabel(Cond))
201     return 0;  // Contains a label.
202 
203   return V.getInt().getBoolValue() ? 1 : -1;
204 }
205 
206 
207 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
208 /// statement) to the specified blocks.  Based on the condition, this might try
209 /// to simplify the codegen of the conditional based on the branch.
210 ///
211 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
212                                            llvm::BasicBlock *TrueBlock,
213                                            llvm::BasicBlock *FalseBlock) {
214   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
215     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
216 
217   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
218     // Handle X && Y in a condition.
219     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
220       // If we have "1 && X", simplify the code.  "0 && X" would have constant
221       // folded if the case was simple enough.
222       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
223         // br(1 && X) -> br(X).
224         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
225       }
226 
227       // If we have "X && 1", simplify the code to use an uncond branch.
228       // "X && 0" would have been constant folded to 0.
229       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
230         // br(X && 1) -> br(X).
231         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
232       }
233 
234       // Emit the LHS as a conditional.  If the LHS conditional is false, we
235       // want to jump to the FalseBlock.
236       llvm::BasicBlock *LHSTrue = createBasicBlock("land_lhs_true");
237       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
238       EmitBlock(LHSTrue);
239 
240       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
241       return;
242     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
243       // If we have "0 || X", simplify the code.  "1 || X" would have constant
244       // folded if the case was simple enough.
245       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
246         // br(0 || X) -> br(X).
247         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
248       }
249 
250       // If we have "X || 0", simplify the code to use an uncond branch.
251       // "X || 1" would have been constant folded to 1.
252       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
253         // br(X || 0) -> br(X).
254         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
255       }
256 
257       // Emit the LHS as a conditional.  If the LHS conditional is true, we
258       // want to jump to the TrueBlock.
259       llvm::BasicBlock *LHSFalse = createBasicBlock("lor_lhs_false");
260       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
261       EmitBlock(LHSFalse);
262 
263       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
264       return;
265     }
266   }
267 
268   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
269     // br(!x, t, f) -> br(x, f, t)
270     if (CondUOp->getOpcode() == UnaryOperator::LNot)
271       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
272   }
273 
274   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
275     // Handle ?: operator.
276 
277     // Just ignore GNU ?: extension.
278     if (CondOp->getLHS()) {
279       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
280       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
281       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
282       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
283       EmitBlock(LHSBlock);
284       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
285       EmitBlock(RHSBlock);
286       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
287       return;
288     }
289   }
290 
291   // Emit the code with the fully general case.
292   llvm::Value *CondV = EvaluateExprAsBool(Cond);
293   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
294 }
295 
296 /// getCGRecordLayout - Return record layout info.
297 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
298                                                          QualType Ty) {
299   const RecordType *RTy = Ty->getAsRecordType();
300   assert (RTy && "Unexpected type. RecordType expected here.");
301 
302   return CGT.getCGRecordLayout(RTy->getDecl());
303 }
304 
305 /// ErrorUnsupported - Print out an error that codegen doesn't support the
306 /// specified stmt yet.
307 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
308                                        bool OmitOnError) {
309   CGM.ErrorUnsupported(S, Type, OmitOnError);
310 }
311 
312 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
313   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
314   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
315 }
316 
317 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
318 {
319   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
320   if (DestPtr->getType() != BP)
321     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
322 
323   // Get size and alignment info for this aggregate.
324   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
325 
326   // FIXME: Handle variable sized types.
327   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
328 
329   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
330                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
331                       // TypeInfo.first describes size in bits.
332                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
333                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
334                                              TypeInfo.second/8));
335 }
336 
337 void CodeGenFunction::EmitIndirectSwitches() {
338   llvm::BasicBlock *Default;
339 
340   if (IndirectSwitches.empty())
341     return;
342 
343   if (!LabelIDs.empty()) {
344     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
345   } else {
346     // No possible targets for indirect goto, just emit an infinite
347     // loop.
348     Default = createBasicBlock("indirectgoto.loop", CurFn);
349     llvm::BranchInst::Create(Default, Default);
350   }
351 
352   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
353          e = IndirectSwitches.end(); i != e; ++i) {
354     llvm::SwitchInst *I = *i;
355 
356     I->setSuccessor(0, Default);
357     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
358            LE = LabelIDs.end(); LI != LE; ++LI) {
359       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
360                                         LI->second),
361                  getBasicBlockForLabel(LI->first));
362     }
363   }
364 }
365 
366 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
367 {
368   // FIXME: This entire method is hardcoded for 32-bit X86.
369 
370   const char *TargetPrefix = getContext().Target.getTargetPrefix();
371 
372   if (strcmp(TargetPrefix, "x86") != 0 ||
373       getContext().Target.getPointerWidth(0) != 32)
374     return 0;
375 
376   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
377   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
378 
379   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
380                                                        "ap");
381   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
382   llvm::Value *AddrTyped =
383     Builder.CreateBitCast(Addr,
384                           llvm::PointerType::getUnqual(ConvertType(Ty)));
385 
386   uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
387   const unsigned ArgumentSizeInBytes = 4;
388   if (SizeInBytes < ArgumentSizeInBytes)
389     SizeInBytes = ArgumentSizeInBytes;
390 
391   llvm::Value *NextAddr =
392     Builder.CreateGEP(Addr,
393                       llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
394                       "ap.next");
395   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
396 
397   return AddrTyped;
398 }
399 
400