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