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