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