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