xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 92ae16b0ae05dd1128d5492faaac9cdb15c7476a)
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 "clang/AST/DeclCXX.h"
22 #include "llvm/Target/TargetData.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
27   : BlockFunction(cgm, *this, Builder), CGM(cgm),
28     Target(CGM.getContext().Target),
29     Builder(cgm.getModule().getContext()),
30     DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
31     CXXThisDecl(0) {
32   LLVMIntTy = ConvertType(getContext().IntTy);
33   LLVMPointerWidth = Target.getPointerWidth(0);
34 }
35 
36 ASTContext &CodeGenFunction::getContext() const {
37   return CGM.getContext();
38 }
39 
40 
41 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42   llvm::BasicBlock *&BB = LabelMap[S];
43   if (BB) return BB;
44 
45   // Create, but don't insert, the new block.
46   return BB = createBasicBlock(S->getName());
47 }
48 
49 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50   llvm::Value *Res = LocalDeclMap[VD];
51   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52   return Res;
53 }
54 
55 llvm::Constant *
56 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
58 }
59 
60 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61   return CGM.getTypes().ConvertTypeForMem(T);
62 }
63 
64 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65   return CGM.getTypes().ConvertType(T);
66 }
67 
68 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
69   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
70     T->isMemberFunctionPointerType();
71 }
72 
73 void CodeGenFunction::EmitReturnBlock() {
74   // For cleanliness, we try to avoid emitting the return block for
75   // simple cases.
76   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
77 
78   if (CurBB) {
79     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
80 
81     // We have a valid insert point, reuse it if it is empty or there are no
82     // explicit jumps to the return block.
83     if (CurBB->empty() || ReturnBlock->use_empty()) {
84       ReturnBlock->replaceAllUsesWith(CurBB);
85       delete ReturnBlock;
86     } else
87       EmitBlock(ReturnBlock);
88     return;
89   }
90 
91   // Otherwise, if the return block is the target of a single direct
92   // branch then we can just put the code in that block instead. This
93   // cleans up functions which started with a unified return block.
94   if (ReturnBlock->hasOneUse()) {
95     llvm::BranchInst *BI =
96       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
97     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
98       // Reset insertion point and delete the branch.
99       Builder.SetInsertPoint(BI->getParent());
100       BI->eraseFromParent();
101       delete ReturnBlock;
102       return;
103     }
104   }
105 
106   // FIXME: We are at an unreachable point, there is no reason to emit the block
107   // unless it has uses. However, we still need a place to put the debug
108   // region.end for now.
109 
110   EmitBlock(ReturnBlock);
111 }
112 
113 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
114   // Finish emission of indirect switches.
115   EmitIndirectSwitches();
116 
117   assert(BreakContinueStack.empty() &&
118          "mismatched push/pop in break/continue stack!");
119   assert(BlockScopes.empty() &&
120          "did not remove all blocks from block scope map!");
121   assert(CleanupEntries.empty() &&
122          "mismatched push/pop in cleanup stack!");
123 
124   // Emit function epilog (to return).
125   EmitReturnBlock();
126 
127   // Emit debug descriptor for function end.
128   if (CGDebugInfo *DI = getDebugInfo()) {
129     DI->setLocation(EndLoc);
130     DI->EmitRegionEnd(CurFn, Builder);
131   }
132 
133   EmitFunctionEpilog(*CurFnInfo, ReturnValue);
134 
135   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
136   llvm::Instruction *Ptr = AllocaInsertPt;
137   AllocaInsertPt = 0;
138   Ptr->eraseFromParent();
139 }
140 
141 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
142                                     llvm::Function *Fn,
143                                     const FunctionArgList &Args,
144                                     SourceLocation StartLoc) {
145   const Decl *D = GD.getDecl();
146 
147   DidCallStackSave = false;
148   CurCodeDecl = CurFuncDecl = D;
149   FnRetTy = RetTy;
150   CurFn = Fn;
151   assert(CurFn->isDeclaration() && "Function already has body?");
152 
153   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
154 
155   // Create a marker to make it easy to insert allocas into the entryblock
156   // later.  Don't create this with the builder, because we don't want it
157   // folded.
158   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
159   AllocaInsertPt = new llvm::BitCastInst(Undef,
160                                          llvm::Type::getInt32Ty(VMContext), "",
161                                          EntryBB);
162   if (Builder.isNamePreserving())
163     AllocaInsertPt->setName("allocapt");
164 
165   ReturnBlock = createBasicBlock("return");
166   ReturnValue = 0;
167   if (!RetTy->isVoidType())
168     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
169 
170   Builder.SetInsertPoint(EntryBB);
171 
172   // Emit subprogram debug descriptor.
173   // FIXME: The cast here is a huge hack.
174   if (CGDebugInfo *DI = getDebugInfo()) {
175     DI->setLocation(StartLoc);
176     if (isa<FunctionDecl>(D)) {
177       DI->EmitFunctionStart(CGM.getMangledName(GD), RetTy, CurFn, Builder);
178     } else {
179       // Just use LLVM function name.
180 
181       // FIXME: Remove unnecessary conversion to std::string when API settles.
182       DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
183                             RetTy, CurFn, Builder);
184     }
185   }
186 
187   // FIXME: Leaked.
188   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
189   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
190 
191   // If any of the arguments have a variably modified type, make sure to
192   // emit the type size.
193   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
194        i != e; ++i) {
195     QualType Ty = i->second;
196 
197     if (Ty->isVariablyModifiedType())
198       EmitVLASize(Ty);
199   }
200 }
201 
202 void CodeGenFunction::GenerateCode(GlobalDecl GD,
203                                    llvm::Function *Fn) {
204   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
205 
206   // Check if we should generate debug info for this function.
207   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
208     DebugInfo = CGM.getDebugInfo();
209 
210   FunctionArgList Args;
211 
212   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
213     if (MD->isInstance()) {
214       // Create the implicit 'this' decl.
215       // FIXME: I'm not entirely sure I like using a fake decl just for code
216       // generation. Maybe we can come up with a better way?
217       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
218                                               &getContext().Idents.get("this"),
219                                               MD->getThisType(getContext()));
220       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
221     }
222   }
223 
224   if (FD->getNumParams()) {
225     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
226     assert(FProto && "Function def must have prototype!");
227 
228     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
229       Args.push_back(std::make_pair(FD->getParamDecl(i),
230                                     FProto->getArgType(i)));
231   }
232 
233   // FIXME: Support CXXTryStmt here, too.
234   if (const CompoundStmt *S = FD->getCompoundBody()) {
235     StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
236     const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
237     llvm::BasicBlock *DtorEpilogue = 0;
238     if (DD) {
239       DtorEpilogue = createBasicBlock("dtor.epilogue");
240 
241       PushCleanupBlock(DtorEpilogue);
242     }
243 
244     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
245       EmitCtorPrologue(CD, GD.getCtorType());
246     EmitStmt(S);
247 
248     if (DD) {
249       CleanupBlockInfo Info = PopCleanupBlock();
250 
251       assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
252       EmitBlock(DtorEpilogue);
253       EmitDtorEpilogue(DD, GD.getDtorType());
254 
255       if (Info.SwitchBlock)
256         EmitBlock(Info.SwitchBlock);
257       if (Info.EndBlock)
258         EmitBlock(Info.EndBlock);
259     }
260     FinishFunction(S->getRBracLoc());
261   } else if (FD->isImplicit()) {
262     const CXXRecordDecl *ClassDecl =
263       cast<CXXRecordDecl>(FD->getDeclContext());
264     (void) ClassDecl;
265     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
266       // FIXME: For C++0x, we want to look for implicit *definitions* of
267       // these special member functions, rather than implicit *declarations*.
268       if (CD->isCopyConstructor(getContext())) {
269         assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
270                "Cannot synthesize a non-implicit copy constructor");
271         SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
272       } else if (CD->isDefaultConstructor()) {
273         assert(!ClassDecl->hasUserDeclaredConstructor() &&
274                "Cannot synthesize a non-implicit default constructor.");
275         SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
276       } else {
277         assert(false && "Implicit constructor cannot be synthesized");
278       }
279     } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
280       assert(!ClassDecl->hasUserDeclaredDestructor() &&
281              "Cannot synthesize a non-implicit destructor");
282       SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
283     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
284       assert(MD->isCopyAssignment() &&
285              !ClassDecl->hasUserDeclaredCopyAssignment() &&
286              "Cannot synthesize a method that is not an implicit-defined "
287              "copy constructor");
288       SynthesizeCXXCopyAssignment(MD, Fn, Args);
289     } else {
290       assert(false && "Cannot synthesize unknown implicit function");
291     }
292   }
293 
294   // Destroy the 'this' declaration.
295   if (CXXThisDecl)
296     CXXThisDecl->Destroy(getContext());
297 }
298 
299 /// ContainsLabel - Return true if the statement contains a label in it.  If
300 /// this statement is not executed normally, it not containing a label means
301 /// that we can just remove the code.
302 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
303   // Null statement, not a label!
304   if (S == 0) return false;
305 
306   // If this is a label, we have to emit the code, consider something like:
307   // if (0) {  ...  foo:  bar(); }  goto foo;
308   if (isa<LabelStmt>(S))
309     return true;
310 
311   // If this is a case/default statement, and we haven't seen a switch, we have
312   // to emit the code.
313   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
314     return true;
315 
316   // If this is a switch statement, we want to ignore cases below it.
317   if (isa<SwitchStmt>(S))
318     IgnoreCaseStmts = true;
319 
320   // Scan subexpressions for verboten labels.
321   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
322        I != E; ++I)
323     if (ContainsLabel(*I, IgnoreCaseStmts))
324       return true;
325 
326   return false;
327 }
328 
329 
330 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
331 /// a constant, or if it does but contains a label, return 0.  If it constant
332 /// folds to 'true' and does not contain a label, return 1, if it constant folds
333 /// to 'false' and does not contain a label, return -1.
334 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
335   // FIXME: Rename and handle conversion of other evaluatable things
336   // to bool.
337   Expr::EvalResult Result;
338   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
339       Result.HasSideEffects)
340     return 0;  // Not foldable, not integer or not fully evaluatable.
341 
342   if (CodeGenFunction::ContainsLabel(Cond))
343     return 0;  // Contains a label.
344 
345   return Result.Val.getInt().getBoolValue() ? 1 : -1;
346 }
347 
348 
349 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
350 /// statement) to the specified blocks.  Based on the condition, this might try
351 /// to simplify the codegen of the conditional based on the branch.
352 ///
353 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
354                                            llvm::BasicBlock *TrueBlock,
355                                            llvm::BasicBlock *FalseBlock) {
356   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
357     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
358 
359   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
360     // Handle X && Y in a condition.
361     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
362       // If we have "1 && X", simplify the code.  "0 && X" would have constant
363       // folded if the case was simple enough.
364       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
365         // br(1 && X) -> br(X).
366         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
367       }
368 
369       // If we have "X && 1", simplify the code to use an uncond branch.
370       // "X && 0" would have been constant folded to 0.
371       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
372         // br(X && 1) -> br(X).
373         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
374       }
375 
376       // Emit the LHS as a conditional.  If the LHS conditional is false, we
377       // want to jump to the FalseBlock.
378       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
379       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
380       EmitBlock(LHSTrue);
381 
382       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
383       return;
384     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
385       // If we have "0 || X", simplify the code.  "1 || X" would have constant
386       // folded if the case was simple enough.
387       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
388         // br(0 || X) -> br(X).
389         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
390       }
391 
392       // If we have "X || 0", simplify the code to use an uncond branch.
393       // "X || 1" would have been constant folded to 1.
394       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
395         // br(X || 0) -> br(X).
396         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
397       }
398 
399       // Emit the LHS as a conditional.  If the LHS conditional is true, we
400       // want to jump to the TrueBlock.
401       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
402       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
403       EmitBlock(LHSFalse);
404 
405       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
406       return;
407     }
408   }
409 
410   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
411     // br(!x, t, f) -> br(x, f, t)
412     if (CondUOp->getOpcode() == UnaryOperator::LNot)
413       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
414   }
415 
416   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
417     // Handle ?: operator.
418 
419     // Just ignore GNU ?: extension.
420     if (CondOp->getLHS()) {
421       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
422       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
423       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
424       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
425       EmitBlock(LHSBlock);
426       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
427       EmitBlock(RHSBlock);
428       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
429       return;
430     }
431   }
432 
433   // Emit the code with the fully general case.
434   llvm::Value *CondV = EvaluateExprAsBool(Cond);
435   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
436 }
437 
438 /// ErrorUnsupported - Print out an error that codegen doesn't support the
439 /// specified stmt yet.
440 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
441                                        bool OmitOnError) {
442   CGM.ErrorUnsupported(S, Type, OmitOnError);
443 }
444 
445 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
446   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
447   return LabelIDs.insert(std::make_pair(L, LabelIDs.size()+1)).first->second;
448 }
449 
450 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
451   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
452   if (DestPtr->getType() != BP)
453     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
454 
455   // Get size and alignment info for this aggregate.
456   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
457 
458   // Don't bother emitting a zero-byte memset.
459   if (TypeInfo.first == 0)
460     return;
461 
462   // FIXME: Handle variable sized types.
463   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
464                                                     LLVMPointerWidth);
465 
466   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
467                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
468                       // TypeInfo.first describes size in bits.
469                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
470                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
471                                              TypeInfo.second/8));
472 }
473 
474 void CodeGenFunction::EmitIndirectSwitches() {
475   llvm::BasicBlock *Default;
476 
477   if (IndirectSwitches.empty())
478     return;
479 
480   if (!LabelIDs.empty()) {
481     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
482   } else {
483     // No possible targets for indirect goto, just emit an infinite
484     // loop.
485     Default = createBasicBlock("indirectgoto.loop", CurFn);
486     llvm::BranchInst::Create(Default, Default);
487   }
488 
489   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
490          e = IndirectSwitches.end(); i != e; ++i) {
491     llvm::SwitchInst *I = *i;
492 
493     I->setSuccessor(0, Default);
494     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
495            LE = LabelIDs.end(); LI != LE; ++LI) {
496       I->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
497                                         LI->second),
498                  getBasicBlockForLabel(LI->first));
499     }
500   }
501 }
502 
503 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
504   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
505 
506   assert(SizeEntry && "Did not emit size for type");
507   return SizeEntry;
508 }
509 
510 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
511   assert(Ty->isVariablyModifiedType() &&
512          "Must pass variably modified type to EmitVLASizes!");
513 
514   EnsureInsertPoint();
515 
516   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
517     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
518 
519     if (!SizeEntry) {
520       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
521 
522       // Get the element size;
523       QualType ElemTy = VAT->getElementType();
524       llvm::Value *ElemSize;
525       if (ElemTy->isVariableArrayType())
526         ElemSize = EmitVLASize(ElemTy);
527       else
528         ElemSize = llvm::ConstantInt::get(SizeTy,
529                                           getContext().getTypeSize(ElemTy) / 8);
530 
531       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
532       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
533 
534       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
535     }
536 
537     return SizeEntry;
538   }
539 
540   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
541     EmitVLASize(AT->getElementType());
542     return 0;
543   }
544 
545   const PointerType *PT = Ty->getAs<PointerType>();
546   assert(PT && "unknown VM type!");
547   EmitVLASize(PT->getPointeeType());
548   return 0;
549 }
550 
551 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
552   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
553     return EmitScalarExpr(E);
554   }
555   return EmitLValue(E).getAddress();
556 }
557 
558 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
559   CleanupEntries.push_back(CleanupEntry(CleanupBlock));
560 }
561 
562 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
563   assert(CleanupEntries.size() >= OldCleanupStackSize &&
564          "Cleanup stack mismatch!");
565 
566   while (CleanupEntries.size() > OldCleanupStackSize)
567     EmitCleanupBlock();
568 }
569 
570 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
571   CleanupEntry &CE = CleanupEntries.back();
572 
573   llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
574 
575   std::vector<llvm::BasicBlock *> Blocks;
576   std::swap(Blocks, CE.Blocks);
577 
578   std::vector<llvm::BranchInst *> BranchFixups;
579   std::swap(BranchFixups, CE.BranchFixups);
580 
581   CleanupEntries.pop_back();
582 
583   // Check if any branch fixups pointed to the scope we just popped. If so,
584   // we can remove them.
585   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
586     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
587     BlockScopeMap::iterator I = BlockScopes.find(Dest);
588 
589     if (I == BlockScopes.end())
590       continue;
591 
592     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
593 
594     if (I->second == CleanupEntries.size()) {
595       // We don't need to do this branch fixup.
596       BranchFixups[i] = BranchFixups.back();
597       BranchFixups.pop_back();
598       i--;
599       e--;
600       continue;
601     }
602   }
603 
604   llvm::BasicBlock *SwitchBlock = 0;
605   llvm::BasicBlock *EndBlock = 0;
606   if (!BranchFixups.empty()) {
607     SwitchBlock = createBasicBlock("cleanup.switch");
608     EndBlock = createBasicBlock("cleanup.end");
609 
610     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
611 
612     Builder.SetInsertPoint(SwitchBlock);
613 
614     llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
615                                                 "cleanup.dst");
616     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
617 
618     // Create a switch instruction to determine where to jump next.
619     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
620                                                 BranchFixups.size());
621 
622     // Restore the current basic block (if any)
623     if (CurBB) {
624       Builder.SetInsertPoint(CurBB);
625 
626       // If we had a current basic block, we also need to emit an instruction
627       // to initialize the cleanup destination.
628       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
629                           DestCodePtr);
630     } else
631       Builder.ClearInsertionPoint();
632 
633     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
634       llvm::BranchInst *BI = BranchFixups[i];
635       llvm::BasicBlock *Dest = BI->getSuccessor(0);
636 
637       // Fixup the branch instruction to point to the cleanup block.
638       BI->setSuccessor(0, CleanupBlock);
639 
640       if (CleanupEntries.empty()) {
641         llvm::ConstantInt *ID;
642 
643         // Check if we already have a destination for this block.
644         if (Dest == SI->getDefaultDest())
645           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
646         else {
647           ID = SI->findCaseDest(Dest);
648           if (!ID) {
649             // No code found, get a new unique one by using the number of
650             // switch successors.
651             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
652                                         SI->getNumSuccessors());
653             SI->addCase(ID, Dest);
654           }
655         }
656 
657         // Store the jump destination before the branch instruction.
658         new llvm::StoreInst(ID, DestCodePtr, BI);
659       } else {
660         // We need to jump through another cleanup block. Create a pad block
661         // with a branch instruction that jumps to the final destination and
662         // add it as a branch fixup to the current cleanup scope.
663 
664         // Create the pad block.
665         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
666 
667         // Create a unique case ID.
668         llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
669                                                        SI->getNumSuccessors());
670 
671         // Store the jump destination before the branch instruction.
672         new llvm::StoreInst(ID, DestCodePtr, BI);
673 
674         // Add it as the destination.
675         SI->addCase(ID, CleanupPad);
676 
677         // Create the branch to the final destination.
678         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
679         CleanupPad->getInstList().push_back(BI);
680 
681         // And add it as a branch fixup.
682         CleanupEntries.back().BranchFixups.push_back(BI);
683       }
684     }
685   }
686 
687   // Remove all blocks from the block scope map.
688   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
689     assert(BlockScopes.count(Blocks[i]) &&
690            "Did not find block in scope map!");
691 
692     BlockScopes.erase(Blocks[i]);
693   }
694 
695   return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
696 }
697 
698 void CodeGenFunction::EmitCleanupBlock() {
699   CleanupBlockInfo Info = PopCleanupBlock();
700 
701   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
702   if (CurBB && !CurBB->getTerminator() &&
703       Info.CleanupBlock->getNumUses() == 0) {
704     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
705     delete Info.CleanupBlock;
706   } else
707     EmitBlock(Info.CleanupBlock);
708 
709   if (Info.SwitchBlock)
710     EmitBlock(Info.SwitchBlock);
711   if (Info.EndBlock)
712     EmitBlock(Info.EndBlock);
713 }
714 
715 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
716   assert(!CleanupEntries.empty() &&
717          "Trying to add branch fixup without cleanup block!");
718 
719   // FIXME: We could be more clever here and check if there's already a branch
720   // fixup for this destination and recycle it.
721   CleanupEntries.back().BranchFixups.push_back(BI);
722 }
723 
724 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
725   if (!HaveInsertPoint())
726     return;
727 
728   llvm::BranchInst* BI = Builder.CreateBr(Dest);
729 
730   Builder.ClearInsertionPoint();
731 
732   // The stack is empty, no need to do any cleanup.
733   if (CleanupEntries.empty())
734     return;
735 
736   if (!Dest->getParent()) {
737     // We are trying to branch to a block that hasn't been inserted yet.
738     AddBranchFixup(BI);
739     return;
740   }
741 
742   BlockScopeMap::iterator I = BlockScopes.find(Dest);
743   if (I == BlockScopes.end()) {
744     // We are trying to jump to a block that is outside of any cleanup scope.
745     AddBranchFixup(BI);
746     return;
747   }
748 
749   assert(I->second < CleanupEntries.size() &&
750          "Trying to branch into cleanup region");
751 
752   if (I->second == CleanupEntries.size() - 1) {
753     // We have a branch to a block in the same scope.
754     return;
755   }
756 
757   AddBranchFixup(BI);
758 }
759