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