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