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->getIdentifier()->getName(),
125                             RetTy, CurFn, Builder);
126     } else {
127       // Just use LLVM function name.
128       DI->EmitFunctionStart(Fn->getName().c_str(),
129                             RetTy, CurFn, Builder);
130     }
131   }
132 
133   EmitFunctionProlog(CurFn, FnRetTy, Args);
134 
135   // If any of the arguments have a variably modified type, make sure to
136   // emit the type size.
137   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
138        i != e; ++i) {
139     QualType Ty = i->second;
140 
141     if (Ty->isVariablyModifiedType())
142       EmitVLASize(Ty);
143   }
144 }
145 
146 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
147                                    llvm::Function *Fn) {
148   FunctionArgList Args;
149   if (FD->getNumParams()) {
150     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
151     assert(FProto && "Function def must have prototype!");
152 
153     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
154       Args.push_back(std::make_pair(FD->getParamDecl(i),
155                                     FProto->getArgType(i)));
156   }
157 
158   StartFunction(FD, FD->getResultType(), Fn, Args,
159                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
160 
161   EmitStmt(FD->getBody());
162 
163   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
164   if (S) {
165     FinishFunction(S->getRBracLoc());
166   } else {
167     FinishFunction();
168   }
169 }
170 
171 /// ContainsLabel - Return true if the statement contains a label in it.  If
172 /// this statement is not executed normally, it not containing a label means
173 /// that we can just remove the code.
174 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
175   // Null statement, not a label!
176   if (S == 0) return false;
177 
178   // If this is a label, we have to emit the code, consider something like:
179   // if (0) {  ...  foo:  bar(); }  goto foo;
180   if (isa<LabelStmt>(S))
181     return true;
182 
183   // If this is a case/default statement, and we haven't seen a switch, we have
184   // to emit the code.
185   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
186     return true;
187 
188   // If this is a switch statement, we want to ignore cases below it.
189   if (isa<SwitchStmt>(S))
190     IgnoreCaseStmts = true;
191 
192   // Scan subexpressions for verboten labels.
193   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
194        I != E; ++I)
195     if (ContainsLabel(*I, IgnoreCaseStmts))
196       return true;
197 
198   return false;
199 }
200 
201 
202 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
203 /// a constant, or if it does but contains a label, return 0.  If it constant
204 /// folds to 'true' and does not contain a label, return 1, if it constant folds
205 /// to 'false' and does not contain a label, return -1.
206 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
207   // FIXME: Rename and handle conversion of other evaluatable things
208   // to bool.
209   Expr::EvalResult Result;
210   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
211       Result.HasSideEffects)
212     return 0;  // Not foldable, not integer or not fully evaluatable.
213 
214   if (CodeGenFunction::ContainsLabel(Cond))
215     return 0;  // Contains a label.
216 
217   return Result.Val.getInt().getBoolValue() ? 1 : -1;
218 }
219 
220 
221 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
222 /// statement) to the specified blocks.  Based on the condition, this might try
223 /// to simplify the codegen of the conditional based on the branch.
224 ///
225 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
226                                            llvm::BasicBlock *TrueBlock,
227                                            llvm::BasicBlock *FalseBlock) {
228   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
229     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
230 
231   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
232     // Handle X && Y in a condition.
233     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
234       // If we have "1 && X", simplify the code.  "0 && X" would have constant
235       // folded if the case was simple enough.
236       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
237         // br(1 && X) -> br(X).
238         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
239       }
240 
241       // If we have "X && 1", simplify the code to use an uncond branch.
242       // "X && 0" would have been constant folded to 0.
243       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
244         // br(X && 1) -> br(X).
245         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
246       }
247 
248       // Emit the LHS as a conditional.  If the LHS conditional is false, we
249       // want to jump to the FalseBlock.
250       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
251       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
252       EmitBlock(LHSTrue);
253 
254       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
255       return;
256     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
257       // If we have "0 || X", simplify the code.  "1 || X" would have constant
258       // folded if the case was simple enough.
259       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
260         // br(0 || X) -> br(X).
261         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
262       }
263 
264       // If we have "X || 0", simplify the code to use an uncond branch.
265       // "X || 1" would have been constant folded to 1.
266       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
267         // br(X || 0) -> br(X).
268         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
269       }
270 
271       // Emit the LHS as a conditional.  If the LHS conditional is true, we
272       // want to jump to the TrueBlock.
273       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
274       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
275       EmitBlock(LHSFalse);
276 
277       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
278       return;
279     }
280   }
281 
282   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
283     // br(!x, t, f) -> br(x, f, t)
284     if (CondUOp->getOpcode() == UnaryOperator::LNot)
285       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
286   }
287 
288   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
289     // Handle ?: operator.
290 
291     // Just ignore GNU ?: extension.
292     if (CondOp->getLHS()) {
293       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
294       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
295       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
296       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
297       EmitBlock(LHSBlock);
298       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
299       EmitBlock(RHSBlock);
300       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
301       return;
302     }
303   }
304 
305   // Emit the code with the fully general case.
306   llvm::Value *CondV = EvaluateExprAsBool(Cond);
307   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
308 }
309 
310 /// getCGRecordLayout - Return record layout info.
311 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
312                                                          QualType Ty) {
313   const RecordType *RTy = Ty->getAsRecordType();
314   assert (RTy && "Unexpected type. RecordType expected here.");
315 
316   return CGT.getCGRecordLayout(RTy->getDecl());
317 }
318 
319 /// ErrorUnsupported - Print out an error that codegen doesn't support the
320 /// specified stmt yet.
321 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
322                                        bool OmitOnError) {
323   CGM.ErrorUnsupported(S, Type, OmitOnError);
324 }
325 
326 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
327   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
328   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
329 }
330 
331 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
332 {
333   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
334   if (DestPtr->getType() != BP)
335     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
336 
337   // Get size and alignment info for this aggregate.
338   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
339 
340   // FIXME: Handle variable sized types.
341   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
342 
343   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
344                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
345                       // TypeInfo.first describes size in bits.
346                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
347                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
348                                              TypeInfo.second/8));
349 }
350 
351 void CodeGenFunction::EmitIndirectSwitches() {
352   llvm::BasicBlock *Default;
353 
354   if (IndirectSwitches.empty())
355     return;
356 
357   if (!LabelIDs.empty()) {
358     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
359   } else {
360     // No possible targets for indirect goto, just emit an infinite
361     // loop.
362     Default = createBasicBlock("indirectgoto.loop", CurFn);
363     llvm::BranchInst::Create(Default, Default);
364   }
365 
366   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
367          e = IndirectSwitches.end(); i != e; ++i) {
368     llvm::SwitchInst *I = *i;
369 
370     I->setSuccessor(0, Default);
371     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
372            LE = LabelIDs.end(); LI != LE; ++LI) {
373       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
374                                         LI->second),
375                  getBasicBlockForLabel(LI->first));
376     }
377   }
378 }
379 
380 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
381 {
382   // FIXME: This entire method is hardcoded for 32-bit X86.
383 
384   const char *TargetPrefix = getContext().Target.getTargetPrefix();
385 
386   if (strcmp(TargetPrefix, "x86") != 0 ||
387       getContext().Target.getPointerWidth(0) != 32)
388     return 0;
389 
390   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
391   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
392 
393   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
394                                                        "ap");
395   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
396   llvm::Value *AddrTyped =
397     Builder.CreateBitCast(Addr,
398                           llvm::PointerType::getUnqual(ConvertType(Ty)));
399 
400   uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
401   const unsigned ArgumentSizeInBytes = 4;
402   if (SizeInBytes < ArgumentSizeInBytes)
403     SizeInBytes = ArgumentSizeInBytes;
404 
405   llvm::Value *NextAddr =
406     Builder.CreateGEP(Addr,
407                       llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
408                       "ap.next");
409   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
410 
411   return AddrTyped;
412 }
413 
414 
415 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
416 {
417   llvm::Value *&SizeEntry = VLASizeMap[VAT];
418 
419   assert(SizeEntry && "Did not emit size for type");
420   return SizeEntry;
421 }
422 
423 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
424 {
425   assert(Ty->isVariablyModifiedType() &&
426          "Must pass variably modified type to EmitVLASizes!");
427 
428   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
429     llvm::Value *&SizeEntry = VLASizeMap[VAT];
430 
431     if (!SizeEntry) {
432       // Get the element size;
433       llvm::Value *ElemSize;
434 
435       QualType ElemTy = VAT->getElementType();
436 
437       if (ElemTy->isVariableArrayType())
438         ElemSize = EmitVLASize(ElemTy);
439       else {
440         // FIXME: We use Int32Ty here because the alloca instruction takes a
441         // 32-bit integer. What should we do about overflow?
442         ElemSize = llvm::ConstantInt::get(llvm::Type::Int32Ty,
443                                           getContext().getTypeSize(ElemTy) / 8);
444       }
445 
446       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
447 
448       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
449     }
450 
451     return SizeEntry;
452   } else if (const PointerType *PT = Ty->getAsPointerType())
453     EmitVLASize(PT->getPointeeType());
454   else {
455     assert(0 && "unknown VM type!");
456   }
457 
458   return 0;
459 }
460