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