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 "CGException.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/AST/APValue.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Intrinsics.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
31   : BlockFunction(cgm, *this, Builder), CGM(cgm),
32     Target(CGM.getContext().Target),
33     Builder(cgm.getModule().getContext()),
34     NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
35     ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
36     SwitchInsn(0), CaseRangeBlock(0),
37     DidCallStackSave(false), UnreachableBlock(0),
38     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
39     ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
40     TrapBB(0) {
41 
42   // Get some frequently used types.
43   LLVMPointerWidth = Target.getPointerWidth(0);
44   llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
45   IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
46   Int32Ty  = llvm::Type::getInt32Ty(LLVMContext);
47   Int64Ty  = llvm::Type::getInt64Ty(LLVMContext);
48 
49   Exceptions = getContext().getLangOptions().Exceptions;
50   CatchUndefined = getContext().getLangOptions().CatchUndefined;
51   CGM.getMangleContext().startNewFunction();
52 }
53 
54 ASTContext &CodeGenFunction::getContext() const {
55   return CGM.getContext();
56 }
57 
58 
59 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
60   llvm::Value *Res = LocalDeclMap[VD];
61   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
62   return Res;
63 }
64 
65 llvm::Constant *
66 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
67   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
68 }
69 
70 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
71   return CGM.getTypes().ConvertTypeForMem(T);
72 }
73 
74 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
75   return CGM.getTypes().ConvertType(T);
76 }
77 
78 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
79   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
80     T->isMemberFunctionPointerType();
81 }
82 
83 void CodeGenFunction::EmitReturnBlock() {
84   // For cleanliness, we try to avoid emitting the return block for
85   // simple cases.
86   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
87 
88   if (CurBB) {
89     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
90 
91     // We have a valid insert point, reuse it if it is empty or there are no
92     // explicit jumps to the return block.
93     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
94       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
95       delete ReturnBlock.getBlock();
96     } else
97       EmitBlock(ReturnBlock.getBlock());
98     return;
99   }
100 
101   // Otherwise, if the return block is the target of a single direct
102   // branch then we can just put the code in that block instead. This
103   // cleans up functions which started with a unified return block.
104   if (ReturnBlock.getBlock()->hasOneUse()) {
105     llvm::BranchInst *BI =
106       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
107     if (BI && BI->isUnconditional() &&
108         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
109       // Reset insertion point and delete the branch.
110       Builder.SetInsertPoint(BI->getParent());
111       BI->eraseFromParent();
112       delete ReturnBlock.getBlock();
113       return;
114     }
115   }
116 
117   // FIXME: We are at an unreachable point, there is no reason to emit the block
118   // unless it has uses. However, we still need a place to put the debug
119   // region.end for now.
120 
121   EmitBlock(ReturnBlock.getBlock());
122 }
123 
124 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
125   if (!BB) return;
126   if (!BB->use_empty())
127     return CGF.CurFn->getBasicBlockList().push_back(BB);
128   delete BB;
129 }
130 
131 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
132   assert(BreakContinueStack.empty() &&
133          "mismatched push/pop in break/continue stack!");
134 
135   // Emit function epilog (to return).
136   EmitReturnBlock();
137 
138   EmitFunctionInstrumentation("__cyg_profile_func_exit");
139 
140   // Emit debug descriptor for function end.
141   if (CGDebugInfo *DI = getDebugInfo()) {
142     DI->setLocation(EndLoc);
143     DI->EmitFunctionEnd(Builder);
144   }
145 
146   EmitFunctionEpilog(*CurFnInfo);
147   EmitEndEHSpec(CurCodeDecl);
148 
149   assert(EHStack.empty() &&
150          "did not remove all scopes from cleanup stack!");
151 
152   // If someone did an indirect goto, emit the indirect goto block at the end of
153   // the function.
154   if (IndirectBranch) {
155     EmitBlock(IndirectBranch->getParent());
156     Builder.ClearInsertionPoint();
157   }
158 
159   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
160   llvm::Instruction *Ptr = AllocaInsertPt;
161   AllocaInsertPt = 0;
162   Ptr->eraseFromParent();
163 
164   // If someone took the address of a label but never did an indirect goto, we
165   // made a zero entry PHI node, which is illegal, zap it now.
166   if (IndirectBranch) {
167     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
168     if (PN->getNumIncomingValues() == 0) {
169       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
170       PN->eraseFromParent();
171     }
172   }
173 
174   EmitIfUsed(*this, RethrowBlock.getBlock());
175   EmitIfUsed(*this, TerminateLandingPad);
176   EmitIfUsed(*this, TerminateHandler);
177   EmitIfUsed(*this, UnreachableBlock);
178 
179   if (CGM.getCodeGenOpts().EmitDeclMetadata)
180     EmitDeclMetadata();
181 }
182 
183 /// ShouldInstrumentFunction - Return true if the current function should be
184 /// instrumented with __cyg_profile_func_* calls
185 bool CodeGenFunction::ShouldInstrumentFunction() {
186   if (!CGM.getCodeGenOpts().InstrumentFunctions)
187     return false;
188   if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
189     return false;
190   return true;
191 }
192 
193 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
194 /// instrumentation function with the current function and the call site, if
195 /// function instrumentation is enabled.
196 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
197   if (!ShouldInstrumentFunction())
198     return;
199 
200   const llvm::PointerType *PointerTy;
201   const llvm::FunctionType *FunctionTy;
202   std::vector<const llvm::Type*> ProfileFuncArgs;
203 
204   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
205   PointerTy = llvm::Type::getInt8PtrTy(VMContext);
206   ProfileFuncArgs.push_back(PointerTy);
207   ProfileFuncArgs.push_back(PointerTy);
208   FunctionTy = llvm::FunctionType::get(
209     llvm::Type::getVoidTy(VMContext),
210     ProfileFuncArgs, false);
211 
212   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
213   llvm::CallInst *CallSite = Builder.CreateCall(
214     CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
215     llvm::ConstantInt::get(Int32Ty, 0),
216     "callsite");
217 
218   Builder.CreateCall2(F,
219                       llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
220                       CallSite);
221 }
222 
223 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
224                                     llvm::Function *Fn,
225                                     const FunctionArgList &Args,
226                                     SourceLocation StartLoc) {
227   const Decl *D = GD.getDecl();
228 
229   DidCallStackSave = false;
230   CurCodeDecl = CurFuncDecl = D;
231   FnRetTy = RetTy;
232   CurFn = Fn;
233   assert(CurFn->isDeclaration() && "Function already has body?");
234 
235   // Pass inline keyword to optimizer if it appears explicitly on any
236   // declaration.
237   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
238     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
239            RE = FD->redecls_end(); RI != RE; ++RI)
240       if (RI->isInlineSpecified()) {
241         Fn->addFnAttr(llvm::Attribute::InlineHint);
242         break;
243       }
244 
245   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
246 
247   // Create a marker to make it easy to insert allocas into the entryblock
248   // later.  Don't create this with the builder, because we don't want it
249   // folded.
250   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
251   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
252   if (Builder.isNamePreserving())
253     AllocaInsertPt->setName("allocapt");
254 
255   ReturnBlock = getJumpDestInCurrentScope("return");
256 
257   Builder.SetInsertPoint(EntryBB);
258 
259   QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
260                                                  false, false, 0, 0,
261                                                  /*FIXME?*/
262                                                  FunctionType::ExtInfo());
263 
264   // Emit subprogram debug descriptor.
265   if (CGDebugInfo *DI = getDebugInfo()) {
266     DI->setLocation(StartLoc);
267     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
268   }
269 
270   EmitFunctionInstrumentation("__cyg_profile_func_enter");
271 
272   // FIXME: Leaked.
273   // CC info is ignored, hopefully?
274   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
275                                               FunctionType::ExtInfo());
276 
277   if (RetTy->isVoidType()) {
278     // Void type; nothing to return.
279     ReturnValue = 0;
280   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
281              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
282     // Indirect aggregate return; emit returned value directly into sret slot.
283     // This reduces code size, and affects correctness in C++.
284     ReturnValue = CurFn->arg_begin();
285   } else {
286     ReturnValue = CreateIRTemp(RetTy, "retval");
287   }
288 
289   EmitStartEHSpec(CurCodeDecl);
290   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
291 
292   if (CXXThisDecl)
293     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
294   if (CXXVTTDecl)
295     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
296 
297   // If any of the arguments have a variably modified type, make sure to
298   // emit the type size.
299   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
300        i != e; ++i) {
301     QualType Ty = i->second;
302 
303     if (Ty->isVariablyModifiedType())
304       EmitVLASize(Ty);
305   }
306 }
307 
308 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
309   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
310   assert(FD->getBody());
311   EmitStmt(FD->getBody());
312 }
313 
314 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
315   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
316 
317   // Check if we should generate debug info for this function.
318   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
319     DebugInfo = CGM.getDebugInfo();
320 
321   FunctionArgList Args;
322 
323   CurGD = GD;
324   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
325     if (MD->isInstance()) {
326       // Create the implicit 'this' decl.
327       // FIXME: I'm not entirely sure I like using a fake decl just for code
328       // generation. Maybe we can come up with a better way?
329       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
330                                               FD->getLocation(),
331                                               &getContext().Idents.get("this"),
332                                               MD->getThisType(getContext()));
333       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
334 
335       // Check if we need a VTT parameter as well.
336       if (CodeGenVTables::needsVTTParameter(GD)) {
337         // FIXME: The comment about using a fake decl above applies here too.
338         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
339         CXXVTTDecl =
340           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
341                                     &getContext().Idents.get("vtt"), T);
342         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
343       }
344     }
345   }
346 
347   if (FD->getNumParams()) {
348     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
349     assert(FProto && "Function def must have prototype!");
350 
351     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
352       Args.push_back(std::make_pair(FD->getParamDecl(i),
353                                     FProto->getArgType(i)));
354   }
355 
356   SourceRange BodyRange;
357   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
358 
359   // Emit the standard function prologue.
360   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
361 
362   // Generate the body of the function.
363   if (isa<CXXDestructorDecl>(FD))
364     EmitDestructorBody(Args);
365   else if (isa<CXXConstructorDecl>(FD))
366     EmitConstructorBody(Args);
367   else
368     EmitFunctionBody(Args);
369 
370   // Emit the standard function epilogue.
371   FinishFunction(BodyRange.getEnd());
372 
373   // Destroy the 'this' declaration.
374   if (CXXThisDecl)
375     CXXThisDecl->Destroy(getContext());
376 
377   // Destroy the VTT declaration.
378   if (CXXVTTDecl)
379     CXXVTTDecl->Destroy(getContext());
380 }
381 
382 /// ContainsLabel - Return true if the statement contains a label in it.  If
383 /// this statement is not executed normally, it not containing a label means
384 /// that we can just remove the code.
385 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
386   // Null statement, not a label!
387   if (S == 0) return false;
388 
389   // If this is a label, we have to emit the code, consider something like:
390   // if (0) {  ...  foo:  bar(); }  goto foo;
391   if (isa<LabelStmt>(S))
392     return true;
393 
394   // If this is a case/default statement, and we haven't seen a switch, we have
395   // to emit the code.
396   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
397     return true;
398 
399   // If this is a switch statement, we want to ignore cases below it.
400   if (isa<SwitchStmt>(S))
401     IgnoreCaseStmts = true;
402 
403   // Scan subexpressions for verboten labels.
404   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
405        I != E; ++I)
406     if (ContainsLabel(*I, IgnoreCaseStmts))
407       return true;
408 
409   return false;
410 }
411 
412 
413 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
414 /// a constant, or if it does but contains a label, return 0.  If it constant
415 /// folds to 'true' and does not contain a label, return 1, if it constant folds
416 /// to 'false' and does not contain a label, return -1.
417 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
418   // FIXME: Rename and handle conversion of other evaluatable things
419   // to bool.
420   Expr::EvalResult Result;
421   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
422       Result.HasSideEffects)
423     return 0;  // Not foldable, not integer or not fully evaluatable.
424 
425   if (CodeGenFunction::ContainsLabel(Cond))
426     return 0;  // Contains a label.
427 
428   return Result.Val.getInt().getBoolValue() ? 1 : -1;
429 }
430 
431 
432 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
433 /// statement) to the specified blocks.  Based on the condition, this might try
434 /// to simplify the codegen of the conditional based on the branch.
435 ///
436 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
437                                            llvm::BasicBlock *TrueBlock,
438                                            llvm::BasicBlock *FalseBlock) {
439   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
440     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
441 
442   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
443     // Handle X && Y in a condition.
444     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
445       // If we have "1 && X", simplify the code.  "0 && X" would have constant
446       // folded if the case was simple enough.
447       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
448         // br(1 && X) -> br(X).
449         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
450       }
451 
452       // If we have "X && 1", simplify the code to use an uncond branch.
453       // "X && 0" would have been constant folded to 0.
454       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
455         // br(X && 1) -> br(X).
456         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
457       }
458 
459       // Emit the LHS as a conditional.  If the LHS conditional is false, we
460       // want to jump to the FalseBlock.
461       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
462       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
463       EmitBlock(LHSTrue);
464 
465       // Any temporaries created here are conditional.
466       BeginConditionalBranch();
467       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
468       EndConditionalBranch();
469 
470       return;
471     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
472       // If we have "0 || X", simplify the code.  "1 || X" would have constant
473       // folded if the case was simple enough.
474       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
475         // br(0 || X) -> br(X).
476         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
477       }
478 
479       // If we have "X || 0", simplify the code to use an uncond branch.
480       // "X || 1" would have been constant folded to 1.
481       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
482         // br(X || 0) -> br(X).
483         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
484       }
485 
486       // Emit the LHS as a conditional.  If the LHS conditional is true, we
487       // want to jump to the TrueBlock.
488       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
489       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
490       EmitBlock(LHSFalse);
491 
492       // Any temporaries created here are conditional.
493       BeginConditionalBranch();
494       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
495       EndConditionalBranch();
496 
497       return;
498     }
499   }
500 
501   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
502     // br(!x, t, f) -> br(x, f, t)
503     if (CondUOp->getOpcode() == UnaryOperator::LNot)
504       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
505   }
506 
507   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
508     // Handle ?: operator.
509 
510     // Just ignore GNU ?: extension.
511     if (CondOp->getLHS()) {
512       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
513       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
514       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
515       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
516       EmitBlock(LHSBlock);
517       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
518       EmitBlock(RHSBlock);
519       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
520       return;
521     }
522   }
523 
524   // Emit the code with the fully general case.
525   llvm::Value *CondV = EvaluateExprAsBool(Cond);
526   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
527 }
528 
529 /// ErrorUnsupported - Print out an error that codegen doesn't support the
530 /// specified stmt yet.
531 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
532                                        bool OmitOnError) {
533   CGM.ErrorUnsupported(S, Type, OmitOnError);
534 }
535 
536 void
537 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
538   // If the type contains a pointer to data member we can't memset it to zero.
539   // Instead, create a null constant and copy it to the destination.
540   if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
541     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
542 
543     llvm::GlobalVariable *NullVariable =
544       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
545                                /*isConstant=*/true,
546                                llvm::GlobalVariable::PrivateLinkage,
547                                NullConstant, llvm::Twine());
548     EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
549     return;
550   }
551 
552 
553   // Ignore empty classes in C++.
554   if (getContext().getLangOptions().CPlusPlus) {
555     if (const RecordType *RT = Ty->getAs<RecordType>()) {
556       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
557         return;
558     }
559   }
560 
561   // Otherwise, just memset the whole thing to zero.  This is legal
562   // because in LLVM, all default initializers (other than the ones we just
563   // handled above) are guaranteed to have a bit pattern of all zeros.
564   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
565   if (DestPtr->getType() != BP)
566     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
567 
568   // Get size and alignment info for this aggregate.
569   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
570 
571   // Don't bother emitting a zero-byte memset.
572   if (TypeInfo.first == 0)
573     return;
574 
575   // FIXME: Handle variable sized types.
576   Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
577                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
578                       // TypeInfo.first describes size in bits.
579                       llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
580                       llvm::ConstantInt::get(Int32Ty, TypeInfo.second/8),
581                       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
582                                              0));
583 }
584 
585 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
586   // Make sure that there is a block for the indirect goto.
587   if (IndirectBranch == 0)
588     GetIndirectGotoBlock();
589 
590   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
591 
592   // Make sure the indirect branch includes all of the address-taken blocks.
593   IndirectBranch->addDestination(BB);
594   return llvm::BlockAddress::get(CurFn, BB);
595 }
596 
597 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
598   // If we already made the indirect branch for indirect goto, return its block.
599   if (IndirectBranch) return IndirectBranch->getParent();
600 
601   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
602 
603   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
604 
605   // Create the PHI node that indirect gotos will add entries to.
606   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
607 
608   // Create the indirect branch instruction.
609   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
610   return IndirectBranch->getParent();
611 }
612 
613 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
614   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
615 
616   assert(SizeEntry && "Did not emit size for type");
617   return SizeEntry;
618 }
619 
620 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
621   assert(Ty->isVariablyModifiedType() &&
622          "Must pass variably modified type to EmitVLASizes!");
623 
624   EnsureInsertPoint();
625 
626   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
627     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
628 
629     if (!SizeEntry) {
630       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
631 
632       // Get the element size;
633       QualType ElemTy = VAT->getElementType();
634       llvm::Value *ElemSize;
635       if (ElemTy->isVariableArrayType())
636         ElemSize = EmitVLASize(ElemTy);
637       else
638         ElemSize = llvm::ConstantInt::get(SizeTy,
639             getContext().getTypeSizeInChars(ElemTy).getQuantity());
640 
641       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
642       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
643 
644       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
645     }
646 
647     return SizeEntry;
648   }
649 
650   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
651     EmitVLASize(AT->getElementType());
652     return 0;
653   }
654 
655   const PointerType *PT = Ty->getAs<PointerType>();
656   assert(PT && "unknown VM type!");
657   EmitVLASize(PT->getPointeeType());
658   return 0;
659 }
660 
661 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
662   if (CGM.getContext().getBuiltinVaListType()->isArrayType())
663     return EmitScalarExpr(E);
664   return EmitLValue(E).getAddress();
665 }
666 
667 /// Pops cleanup blocks until the given savepoint is reached.
668 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
669   assert(Old.isValid());
670 
671   while (EHStack.stable_begin() != Old) {
672     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
673 
674     // As long as Old strictly encloses the scope's enclosing normal
675     // cleanup, we're going to emit another normal cleanup which
676     // fallthrough can propagate through.
677     bool FallThroughIsBranchThrough =
678       Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
679 
680     PopCleanupBlock(FallThroughIsBranchThrough);
681   }
682 }
683 
684 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
685                                            EHCleanupScope &Scope) {
686   assert(Scope.isNormalCleanup());
687   llvm::BasicBlock *Entry = Scope.getNormalBlock();
688   if (!Entry) {
689     Entry = CGF.createBasicBlock("cleanup");
690     Scope.setNormalBlock(Entry);
691   }
692   return Entry;
693 }
694 
695 static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
696                                        EHCleanupScope &Scope) {
697   assert(Scope.isEHCleanup());
698   llvm::BasicBlock *Entry = Scope.getEHBlock();
699   if (!Entry) {
700     Entry = CGF.createBasicBlock("eh.cleanup");
701     Scope.setEHBlock(Entry);
702   }
703   return Entry;
704 }
705 
706 /// Transitions the terminator of the given exit-block of a cleanup to
707 /// be a cleanup switch.
708 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
709                                                    llvm::BasicBlock *Block) {
710   // If it's a branch, turn it into a switch whose default
711   // destination is its original target.
712   llvm::TerminatorInst *Term = Block->getTerminator();
713   assert(Term && "can't transition block without terminator");
714 
715   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
716     assert(Br->isUnconditional());
717     llvm::LoadInst *Load =
718       new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
719     llvm::SwitchInst *Switch =
720       llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
721     Br->eraseFromParent();
722     return Switch;
723   } else {
724     return cast<llvm::SwitchInst>(Term);
725   }
726 }
727 
728 /// Attempts to reduce a cleanup's entry block to a fallthrough.  This
729 /// is basically llvm::MergeBlockIntoPredecessor, except
730 /// simplified/optimized for the tighter constraints on cleanup blocks.
731 ///
732 /// Returns the new block, whatever it is.
733 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
734                                               llvm::BasicBlock *Entry) {
735   llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
736   if (!Pred) return Entry;
737 
738   llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
739   if (!Br || Br->isConditional()) return Entry;
740   assert(Br->getSuccessor(0) == Entry);
741 
742   // If we were previously inserting at the end of the cleanup entry
743   // block, we'll need to continue inserting at the end of the
744   // predecessor.
745   bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
746   assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
747 
748   // Kill the branch.
749   Br->eraseFromParent();
750 
751   // Merge the blocks.
752   Pred->getInstList().splice(Pred->end(), Entry->getInstList());
753 
754   // Kill the entry block.
755   Entry->eraseFromParent();
756 
757   if (WasInsertBlock)
758     CGF.Builder.SetInsertPoint(Pred);
759 
760   return Pred;
761 }
762 
763 static void EmitCleanup(CodeGenFunction &CGF,
764                         EHScopeStack::Cleanup *Fn,
765                         bool ForEH) {
766   if (ForEH) CGF.EHStack.pushTerminate();
767   Fn->Emit(CGF, ForEH);
768   if (ForEH) CGF.EHStack.popTerminate();
769   assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
770 }
771 
772 /// Pops a cleanup block.  If the block includes a normal cleanup, the
773 /// current insertion point is threaded through the cleanup, as are
774 /// any branch fixups on the cleanup.
775 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
776   assert(!EHStack.empty() && "cleanup stack is empty!");
777   assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
778   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
779   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
780 
781   // Check whether we need an EH cleanup.  This is only true if we've
782   // generated a lazy EH cleanup block.
783   bool RequiresEHCleanup = Scope.hasEHBranches();
784 
785   // Check the three conditions which might require a normal cleanup:
786 
787   // - whether there are branch fix-ups through this cleanup
788   unsigned FixupDepth = Scope.getFixupDepth();
789   bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
790 
791   // - whether there are branch-throughs or branch-afters
792   bool HasExistingBranches = Scope.hasBranches();
793 
794   // - whether there's a fallthrough
795   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
796   bool HasFallthrough = (FallthroughSource != 0);
797 
798   bool RequiresNormalCleanup = false;
799   if (Scope.isNormalCleanup() &&
800       (HasFixups || HasExistingBranches || HasFallthrough)) {
801     RequiresNormalCleanup = true;
802   }
803 
804   // If we don't need the cleanup at all, we're done.
805   if (!RequiresNormalCleanup && !RequiresEHCleanup) {
806     EHStack.popCleanup(); // safe because there are no fixups
807     assert(EHStack.getNumBranchFixups() == 0 ||
808            EHStack.hasNormalCleanups());
809     return;
810   }
811 
812   // Copy the cleanup emission data out.  Note that SmallVector
813   // guarantees maximal alignment for its buffer regardless of its
814   // type parameter.
815   llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
816   CleanupBuffer.reserve(Scope.getCleanupSize());
817   memcpy(CleanupBuffer.data(),
818          Scope.getCleanupBuffer(), Scope.getCleanupSize());
819   CleanupBuffer.set_size(Scope.getCleanupSize());
820   EHScopeStack::Cleanup *Fn =
821     reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
822 
823   // We want to emit the EH cleanup after the normal cleanup, but go
824   // ahead and do the setup for the EH cleanup while the scope is still
825   // alive.
826   llvm::BasicBlock *EHEntry = 0;
827   llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
828   if (RequiresEHCleanup) {
829     EHEntry = CreateEHEntry(*this, Scope);
830 
831     // Figure out the branch-through dest if necessary.
832     llvm::BasicBlock *EHBranchThroughDest = 0;
833     if (Scope.hasEHBranchThroughs()) {
834       assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
835       EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
836       EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
837     }
838 
839     // If we have exactly one branch-after and no branch-throughs, we
840     // can dispatch it without a switch.
841     if (!Scope.hasBranchThroughs() &&
842         Scope.getNumEHBranchAfters() == 1) {
843       assert(!EHBranchThroughDest);
844 
845       // TODO: remove the spurious eh.cleanup.dest stores if this edge
846       // never went through any switches.
847       llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
848       EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
849 
850     // Otherwise, if we have any branch-afters, we need a switch.
851     } else if (Scope.getNumEHBranchAfters()) {
852       // The default of the switch belongs to the branch-throughs if
853       // they exist.
854       llvm::BasicBlock *Default =
855         (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
856 
857       const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
858 
859       llvm::LoadInst *Load =
860         new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
861       llvm::SwitchInst *Switch =
862         llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
863 
864       EHInstsToAppend.push_back(Load);
865       EHInstsToAppend.push_back(Switch);
866 
867       for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
868         Switch->addCase(Scope.getEHBranchAfterIndex(I),
869                         Scope.getEHBranchAfterBlock(I));
870 
871     // Otherwise, we have only branch-throughs; jump to the next EH
872     // cleanup.
873     } else {
874       assert(EHBranchThroughDest);
875       EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
876     }
877   }
878 
879   if (!RequiresNormalCleanup) {
880     EHStack.popCleanup();
881   } else {
882     // As a kindof crazy internal case, branch-through fall-throughs
883     // leave the insertion point set to the end of the last cleanup.
884     bool HasPrebranchedFallthrough =
885       (HasFallthrough && FallthroughSource->getTerminator());
886     assert(!HasPrebranchedFallthrough ||
887            FallthroughSource->getTerminator()->getSuccessor(0)
888              == Scope.getNormalBlock());
889 
890     // If we have a fallthrough and no other need for the cleanup,
891     // emit it directly.
892     if (HasFallthrough && !HasPrebranchedFallthrough &&
893         !HasFixups && !HasExistingBranches) {
894 
895       // Fixups can cause us to optimistically create a normal block,
896       // only to later have no real uses for it.  Just delete it in
897       // this case.
898       // TODO: we can potentially simplify all the uses after this.
899       if (Scope.getNormalBlock()) {
900         Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
901         delete Scope.getNormalBlock();
902       }
903 
904       EHStack.popCleanup();
905 
906       EmitCleanup(*this, Fn, /*ForEH*/ false);
907 
908     // Otherwise, the best approach is to thread everything through
909     // the cleanup block and then try to clean up after ourselves.
910     } else {
911       // Force the entry block to exist.
912       llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
913 
914       // If there's a fallthrough, we need to store the cleanup
915       // destination index.  For fall-throughs this is always zero.
916       if (HasFallthrough && !HasPrebranchedFallthrough)
917         Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
918 
919       // Emit the entry block.  This implicitly branches to it if we
920       // have fallthrough.  All the fixups and existing branches should
921       // already be branched to it.
922       EmitBlock(NormalEntry);
923 
924       bool HasEnclosingCleanups =
925         (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
926 
927       // Compute the branch-through dest if we need it:
928       //   - if there are branch-throughs threaded through the scope
929       //   - if fall-through is a branch-through
930       //   - if there are fixups that will be optimistically forwarded
931       //     to the enclosing cleanup
932       llvm::BasicBlock *BranchThroughDest = 0;
933       if (Scope.hasBranchThroughs() ||
934           (HasFallthrough && FallthroughIsBranchThrough) ||
935           (HasFixups && HasEnclosingCleanups)) {
936         assert(HasEnclosingCleanups);
937         EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
938         BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
939       }
940 
941       llvm::BasicBlock *FallthroughDest = 0;
942       llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
943 
944       // If there's exactly one branch-after and no other threads,
945       // we can route it without a switch.
946       if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
947           Scope.getNumBranchAfters() == 1) {
948         assert(!BranchThroughDest);
949 
950         // TODO: clean up the possibly dead stores to the cleanup dest slot.
951         llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
952         InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
953 
954       // Build a switch-out if we need it:
955       //   - if there are branch-afters threaded through the scope
956       //   - if fall-through is a branch-after
957       //   - if there are fixups that have nowhere left to go and
958       //     so must be immediately resolved
959       } else if (Scope.getNumBranchAfters() ||
960                  (HasFallthrough && !FallthroughIsBranchThrough) ||
961                  (HasFixups && !HasEnclosingCleanups)) {
962 
963         llvm::BasicBlock *Default =
964           (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
965 
966         // TODO: base this on the number of branch-afters and fixups
967         const unsigned SwitchCapacity = 10;
968 
969         llvm::LoadInst *Load =
970           new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
971         llvm::SwitchInst *Switch =
972           llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
973 
974         InstsToAppend.push_back(Load);
975         InstsToAppend.push_back(Switch);
976 
977         // Branch-after fallthrough.
978         if (HasFallthrough && !FallthroughIsBranchThrough) {
979           FallthroughDest = createBasicBlock("cleanup.cont");
980           Switch->addCase(Builder.getInt32(0), FallthroughDest);
981         }
982 
983         for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
984           Switch->addCase(Scope.getBranchAfterIndex(I),
985                           Scope.getBranchAfterBlock(I));
986         }
987 
988         if (HasFixups && !HasEnclosingCleanups)
989           ResolveAllBranchFixups(Switch);
990       } else {
991         // We should always have a branch-through destination in this case.
992         assert(BranchThroughDest);
993         InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
994       }
995 
996       // We're finally ready to pop the cleanup.
997       EHStack.popCleanup();
998       assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
999 
1000       EmitCleanup(*this, Fn, /*ForEH*/ false);
1001 
1002       // Append the prepared cleanup prologue from above.
1003       llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1004       for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1005         NormalExit->getInstList().push_back(InstsToAppend[I]);
1006 
1007       // Optimistically hope that any fixups will continue falling through.
1008       for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1009            I < E; ++I) {
1010         BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1011         if (!Fixup.Destination) continue;
1012         if (!Fixup.OptimisticBranchBlock) {
1013           new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1014                               getNormalCleanupDestSlot(),
1015                               Fixup.InitialBranch);
1016           Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1017         }
1018         Fixup.OptimisticBranchBlock = NormalExit;
1019       }
1020 
1021       if (FallthroughDest)
1022         EmitBlock(FallthroughDest);
1023       else if (!HasFallthrough)
1024         Builder.ClearInsertionPoint();
1025 
1026       // Check whether we can merge NormalEntry into a single predecessor.
1027       // This might invalidate (non-IR) pointers to NormalEntry.
1028       llvm::BasicBlock *NewNormalEntry =
1029         SimplifyCleanupEntry(*this, NormalEntry);
1030 
1031       // If it did invalidate those pointers, and NormalEntry was the same
1032       // as NormalExit, go back and patch up the fixups.
1033       if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1034         for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1035                I < E; ++I)
1036           CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
1037     }
1038   }
1039 
1040   assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1041 
1042   // Emit the EH cleanup if required.
1043   if (RequiresEHCleanup) {
1044     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1045 
1046     EmitBlock(EHEntry);
1047     EmitCleanup(*this, Fn, /*ForEH*/ true);
1048 
1049     // Append the prepared cleanup prologue from above.
1050     llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1051     for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1052       EHExit->getInstList().push_back(EHInstsToAppend[I]);
1053 
1054     Builder.restoreIP(SavedIP);
1055 
1056     SimplifyCleanupEntry(*this, EHEntry);
1057   }
1058 }
1059 
1060 /// Terminate the current block by emitting a branch which might leave
1061 /// the current cleanup-protected scope.  The target scope may not yet
1062 /// be known, in which case this will require a fixup.
1063 ///
1064 /// As a side-effect, this method clears the insertion point.
1065 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
1066   if (!HaveInsertPoint())
1067     return;
1068 
1069   // Create the branch.
1070   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1071 
1072   // If we're not in a cleanup scope, or if the destination scope is
1073   // the current normal-cleanup scope, we don't need to worry about
1074   // fixups.
1075   if (!EHStack.hasNormalCleanups() ||
1076       Dest.getScopeDepth() == EHStack.getInnermostNormalCleanup()) {
1077     Builder.ClearInsertionPoint();
1078     return;
1079   }
1080 
1081   // If we can't resolve the destination cleanup scope, just add this
1082   // to the current cleanup scope as a branch fixup.
1083   if (!Dest.getScopeDepth().isValid()) {
1084     BranchFixup &Fixup = EHStack.addBranchFixup();
1085     Fixup.Destination = Dest.getBlock();
1086     Fixup.DestinationIndex = Dest.getDestIndex();
1087     Fixup.InitialBranch = BI;
1088     Fixup.OptimisticBranchBlock = 0;
1089 
1090     Builder.ClearInsertionPoint();
1091     return;
1092   }
1093 
1094   // Otherwise, thread through all the normal cleanups in scope.
1095 
1096   // Store the index at the start.
1097   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1098   new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1099 
1100   // Adjust BI to point to the first cleanup block.
1101   {
1102     EHCleanupScope &Scope =
1103       cast<EHCleanupScope>(*EHStack.find(EHStack.getInnermostNormalCleanup()));
1104     BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1105   }
1106 
1107   // Add this destination to all the scopes involved.
1108   EHScopeStack::stable_iterator I = EHStack.getInnermostNormalCleanup();
1109   EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1110   if (E.strictlyEncloses(I)) {
1111     while (true) {
1112       EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1113       assert(Scope.isNormalCleanup());
1114       I = Scope.getEnclosingNormalCleanup();
1115 
1116       // If this is the last cleanup we're propagating through, tell it
1117       // that there's a resolved jump moving through it.
1118       if (!E.strictlyEncloses(I)) {
1119         Scope.addBranchAfter(Index, Dest.getBlock());
1120         break;
1121       }
1122 
1123       // Otherwise, tell the scope that there's a jump propoagating
1124       // through it.  If this isn't new information, all the rest of
1125       // the work has been done before.
1126       if (!Scope.addBranchThrough(Dest.getBlock()))
1127         break;
1128     }
1129   }
1130 
1131   Builder.ClearInsertionPoint();
1132 }
1133 
1134 void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1135   // We should never get invalid scope depths for an UnwindDest; that
1136   // implies that the destination wasn't set up correctly.
1137   assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1138 
1139   if (!HaveInsertPoint())
1140     return;
1141 
1142   // Create the branch.
1143   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1144 
1145   // If the destination is in the same EH cleanup scope as us, we
1146   // don't need to thread through anything.
1147   if (Dest.getScopeDepth() == EHStack.getInnermostEHCleanup()) {
1148     Builder.ClearInsertionPoint();
1149     return;
1150   }
1151   assert(EHStack.hasEHCleanups());
1152 
1153   // Store the index at the start.
1154   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1155   new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
1156 
1157   // Adjust BI to point to the first cleanup block.
1158   {
1159     EHCleanupScope &Scope =
1160       cast<EHCleanupScope>(*EHStack.find(EHStack.getInnermostEHCleanup()));
1161     BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1162   }
1163 
1164   // Add this destination to all the scopes involved.
1165   for (EHScopeStack::stable_iterator
1166          I = EHStack.getInnermostEHCleanup(),
1167          E = Dest.getScopeDepth(); ; ) {
1168     assert(E.strictlyEncloses(I));
1169     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1170     assert(Scope.isEHCleanup());
1171     I = Scope.getEnclosingEHCleanup();
1172 
1173     // If this is the last cleanup we're propagating through, add this
1174     // as a branch-after.
1175     if (I == E) {
1176       Scope.addEHBranchAfter(Index, Dest.getBlock());
1177       break;
1178     }
1179 
1180     // Otherwise, add it as a branch-through.  If this isn't new
1181     // information, all the rest of the work has been done before.
1182     if (!Scope.addEHBranchThrough(Dest.getBlock()))
1183       break;
1184   }
1185 
1186   Builder.ClearInsertionPoint();
1187 }
1188 
1189 /// All the branch fixups on the EH stack have propagated out past the
1190 /// outermost normal cleanup; resolve them all by adding cases to the
1191 /// given switch instruction.
1192 void CodeGenFunction::ResolveAllBranchFixups(llvm::SwitchInst *Switch) {
1193   llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1194 
1195   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1196     // Skip this fixup if its destination isn't set or if we've
1197     // already treated it.
1198     BranchFixup &Fixup = EHStack.getBranchFixup(I);
1199     if (Fixup.Destination == 0) continue;
1200     if (!CasesAdded.insert(Fixup.Destination)) continue;
1201 
1202     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex),
1203                     Fixup.Destination);
1204   }
1205 
1206   EHStack.clearFixups();
1207 }
1208 
1209 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1210   assert(Block && "resolving a null target block");
1211   if (!EHStack.getNumBranchFixups()) return;
1212 
1213   assert(EHStack.hasNormalCleanups() &&
1214          "branch fixups exist with no normal cleanups on stack");
1215 
1216   llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1217   bool ResolvedAny = false;
1218 
1219   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1220     // Skip this fixup if its destination doesn't match.
1221     BranchFixup &Fixup = EHStack.getBranchFixup(I);
1222     if (Fixup.Destination != Block) continue;
1223 
1224     Fixup.Destination = 0;
1225     ResolvedAny = true;
1226 
1227     // If it doesn't have an optimistic branch block, LatestBranch is
1228     // already pointing to the right place.
1229     llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1230     if (!BranchBB)
1231       continue;
1232 
1233     // Don't process the same optimistic branch block twice.
1234     if (!ModifiedOptimisticBlocks.insert(BranchBB))
1235       continue;
1236 
1237     llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1238 
1239     // Add a case to the switch.
1240     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1241   }
1242 
1243   if (ResolvedAny)
1244     EHStack.popNullFixups();
1245 }
1246 
1247 llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1248   if (!NormalCleanupDest)
1249     NormalCleanupDest =
1250       CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1251   return NormalCleanupDest;
1252 }
1253 
1254 llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1255   if (!EHCleanupDest)
1256     EHCleanupDest =
1257       CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1258   return EHCleanupDest;
1259 }
1260