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