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