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