xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 6c4d255bf3d64fd2ecb48334e780c87f060f1280)
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     const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
264     llvm::BasicBlock *DtorEpilogue = 0;
265     if (DD) {
266       DtorEpilogue = createBasicBlock("dtor.epilogue");
267 
268       PushCleanupBlock(DtorEpilogue);
269     }
270 
271     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
272       EmitCtorPrologue(CD, GD.getCtorType());
273     EmitStmt(S);
274 
275     if (DD) {
276       CleanupBlockInfo Info = PopCleanupBlock();
277 
278       assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
279       EmitBlock(DtorEpilogue);
280       EmitDtorEpilogue(DD, GD.getDtorType());
281 
282       if (Info.SwitchBlock)
283         EmitBlock(Info.SwitchBlock);
284       if (Info.EndBlock)
285         EmitBlock(Info.EndBlock);
286     }
287     FinishFunction(S->getRBracLoc());
288   } else if (FD->isImplicit()) {
289     const CXXRecordDecl *ClassDecl =
290       cast<CXXRecordDecl>(FD->getDeclContext());
291     (void) ClassDecl;
292     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
293       // FIXME: For C++0x, we want to look for implicit *definitions* of
294       // these special member functions, rather than implicit *declarations*.
295       if (CD->isCopyConstructor(getContext())) {
296         assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
297                "Cannot synthesize a non-implicit copy constructor");
298         SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
299       } else if (CD->isDefaultConstructor()) {
300         assert(!ClassDecl->hasUserDeclaredConstructor() &&
301                "Cannot synthesize a non-implicit default constructor.");
302         SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
303       } else {
304         assert(false && "Implicit constructor cannot be synthesized");
305       }
306     } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
307       assert(!ClassDecl->hasUserDeclaredDestructor() &&
308              "Cannot synthesize a non-implicit destructor");
309       SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
310     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
311       assert(MD->isCopyAssignment() &&
312              !ClassDecl->hasUserDeclaredCopyAssignment() &&
313              "Cannot synthesize a method that is not an implicit-defined "
314              "copy constructor");
315       SynthesizeCXXCopyAssignment(MD, Fn, Args);
316     } else {
317       assert(false && "Cannot synthesize unknown implicit function");
318     }
319   }
320 
321   // Destroy the 'this' declaration.
322   if (CXXThisDecl)
323     CXXThisDecl->Destroy(getContext());
324 }
325 
326 /// ContainsLabel - Return true if the statement contains a label in it.  If
327 /// this statement is not executed normally, it not containing a label means
328 /// that we can just remove the code.
329 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
330   // Null statement, not a label!
331   if (S == 0) return false;
332 
333   // If this is a label, we have to emit the code, consider something like:
334   // if (0) {  ...  foo:  bar(); }  goto foo;
335   if (isa<LabelStmt>(S))
336     return true;
337 
338   // If this is a case/default statement, and we haven't seen a switch, we have
339   // to emit the code.
340   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
341     return true;
342 
343   // If this is a switch statement, we want to ignore cases below it.
344   if (isa<SwitchStmt>(S))
345     IgnoreCaseStmts = true;
346 
347   // Scan subexpressions for verboten labels.
348   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
349        I != E; ++I)
350     if (ContainsLabel(*I, IgnoreCaseStmts))
351       return true;
352 
353   return false;
354 }
355 
356 
357 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
358 /// a constant, or if it does but contains a label, return 0.  If it constant
359 /// folds to 'true' and does not contain a label, return 1, if it constant folds
360 /// to 'false' and does not contain a label, return -1.
361 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
362   // FIXME: Rename and handle conversion of other evaluatable things
363   // to bool.
364   Expr::EvalResult Result;
365   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
366       Result.HasSideEffects)
367     return 0;  // Not foldable, not integer or not fully evaluatable.
368 
369   if (CodeGenFunction::ContainsLabel(Cond))
370     return 0;  // Contains a label.
371 
372   return Result.Val.getInt().getBoolValue() ? 1 : -1;
373 }
374 
375 
376 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
377 /// statement) to the specified blocks.  Based on the condition, this might try
378 /// to simplify the codegen of the conditional based on the branch.
379 ///
380 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
381                                            llvm::BasicBlock *TrueBlock,
382                                            llvm::BasicBlock *FalseBlock) {
383   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
384     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
385 
386   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
387     // Handle X && Y in a condition.
388     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
389       // If we have "1 && X", simplify the code.  "0 && X" would have constant
390       // folded if the case was simple enough.
391       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
392         // br(1 && X) -> br(X).
393         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
394       }
395 
396       // If we have "X && 1", simplify the code to use an uncond branch.
397       // "X && 0" would have been constant folded to 0.
398       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
399         // br(X && 1) -> br(X).
400         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
401       }
402 
403       // Emit the LHS as a conditional.  If the LHS conditional is false, we
404       // want to jump to the FalseBlock.
405       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
406       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
407       EmitBlock(LHSTrue);
408 
409       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
410       return;
411     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
412       // If we have "0 || X", simplify the code.  "1 || X" would have constant
413       // folded if the case was simple enough.
414       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
415         // br(0 || X) -> br(X).
416         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
417       }
418 
419       // If we have "X || 0", simplify the code to use an uncond branch.
420       // "X || 1" would have been constant folded to 1.
421       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
422         // br(X || 0) -> br(X).
423         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
424       }
425 
426       // Emit the LHS as a conditional.  If the LHS conditional is true, we
427       // want to jump to the TrueBlock.
428       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
429       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
430       EmitBlock(LHSFalse);
431 
432       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
433       return;
434     }
435   }
436 
437   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
438     // br(!x, t, f) -> br(x, f, t)
439     if (CondUOp->getOpcode() == UnaryOperator::LNot)
440       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
441   }
442 
443   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
444     // Handle ?: operator.
445 
446     // Just ignore GNU ?: extension.
447     if (CondOp->getLHS()) {
448       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
449       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
450       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
451       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
452       EmitBlock(LHSBlock);
453       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
454       EmitBlock(RHSBlock);
455       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
456       return;
457     }
458   }
459 
460   // Emit the code with the fully general case.
461   llvm::Value *CondV = EvaluateExprAsBool(Cond);
462   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
463 }
464 
465 /// ErrorUnsupported - Print out an error that codegen doesn't support the
466 /// specified stmt yet.
467 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
468                                        bool OmitOnError) {
469   CGM.ErrorUnsupported(S, Type, OmitOnError);
470 }
471 
472 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
473   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
474   if (DestPtr->getType() != BP)
475     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
476 
477   // Get size and alignment info for this aggregate.
478   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
479 
480   // Don't bother emitting a zero-byte memset.
481   if (TypeInfo.first == 0)
482     return;
483 
484   // FIXME: Handle variable sized types.
485   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
486                                                     LLVMPointerWidth);
487 
488   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
489                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
490                       // TypeInfo.first describes size in bits.
491                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
492                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
493                                              TypeInfo.second/8));
494 }
495 
496 #ifndef USEINDIRECTBRANCH
497 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
498   // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
499   unsigned &Entry = LabelIDs[L];
500   if (Entry) return Entry;
501 #else
502 
503 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
504   // Make sure that there is a block for the indirect goto.
505   if (IndirectBranch == 0)
506     GetIndirectGotoBlock();
507 #endif
508 
509 #ifndef USEINDIRECTBRANCH
510   Entry = LabelIDs.size();
511 #else
512   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
513 #endif
514 
515 #ifndef USEINDIRECTBRANCH
516   // If this is the first "address taken" of a label and the indirect goto has
517   // already been seen, add this to it.
518   if (IndirectGotoSwitch) {
519     // If this is the first address-taken label, set it as the default dest.
520     if (Entry == 1)
521       IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
522     else {
523       // Otherwise add it to the switch as a new dest.
524       const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
525       IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
526                                   getBasicBlockForLabel(L));
527     }
528   }
529 
530   return Entry;
531 #else
532   // Make sure the indirect branch includes all of the address-taken blocks.
533   IndirectBranch->addDestination(BB);
534   return llvm::BlockAddress::get(CurFn, BB);
535 #endif
536 }
537 
538 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
539 #ifndef USEINDIRECTBRANCH
540   // If we already made the switch stmt for indirect goto, return its block.
541   if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
542 #else
543   // If we already made the indirect branch for indirect goto, return its block.
544   if (IndirectBranch) return IndirectBranch->getParent();
545 #endif
546 
547 #ifndef USEINDIRECTBRANCH
548   EmitBlock(createBasicBlock("indirectgoto"));
549 #else
550   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
551 #endif
552 
553 #ifndef USEINDIRECTBRANCH
554   const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
555 #else
556   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
557 #endif
558 
559   // Create the PHI node that indirect gotos will add entries to.
560 #ifndef USEINDIRECTBRANCH
561   llvm::Value *DestVal = Builder.CreatePHI(Int32Ty, "indirect.goto.dest");
562 #else
563   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
564 #endif
565 
566 #ifndef USEINDIRECTBRANCH
567   // Create the switch instruction.  For now, set the insert block to this block
568   // which will be fixed as labels are added.
569   IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
570 
571   // Clear the insertion point to indicate we are in unreachable code.
572   Builder.ClearInsertionPoint();
573 
574   // If we already have labels created, add them.
575   if (!LabelIDs.empty()) {
576     // Invert LabelID's so that the order is determinstic.
577     std::vector<const LabelStmt*> AddrTakenLabelsByID;
578     AddrTakenLabelsByID.resize(LabelIDs.size());
579 
580     for (std::map<const LabelStmt*,unsigned>::iterator
581          LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
582       assert(LI->second-1 < AddrTakenLabelsByID.size() &&
583              "Numbering inconsistent");
584       AddrTakenLabelsByID[LI->second-1] = LI->first;
585     }
586 
587     // Set the default entry as the first block.
588     IndirectGotoSwitch->setSuccessor(0,
589                                 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
590 
591     // FIXME: The iteration order of this is nondeterminstic!
592     for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
593       IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
594                                  getBasicBlockForLabel(AddrTakenLabelsByID[i]));
595   } else {
596     // Otherwise, create a dead block and set it as the default dest.  This will
597     // be removed by the optimizers after the indirect goto is set up.
598     llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
599     EmitBlock(Dummy);
600     IndirectGotoSwitch->setSuccessor(0, Dummy);
601     Builder.CreateUnreachable();
602     Builder.ClearInsertionPoint();
603   }
604 
605   return IndirectGotoSwitch->getParent();
606 #else
607   // Create the indirect branch instruction.
608   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
609   return IndirectBranch->getParent();
610 #endif
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().getTypeSize(ElemTy) / 8);
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   }
665   return EmitLValue(E).getAddress();
666 }
667 
668 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
669   CleanupEntries.push_back(CleanupEntry(CleanupBlock));
670 }
671 
672 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
673   assert(CleanupEntries.size() >= OldCleanupStackSize &&
674          "Cleanup stack mismatch!");
675 
676   while (CleanupEntries.size() > OldCleanupStackSize)
677     EmitCleanupBlock();
678 }
679 
680 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
681   CleanupEntry &CE = CleanupEntries.back();
682 
683   llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
684 
685   std::vector<llvm::BasicBlock *> Blocks;
686   std::swap(Blocks, CE.Blocks);
687 
688   std::vector<llvm::BranchInst *> BranchFixups;
689   std::swap(BranchFixups, CE.BranchFixups);
690 
691   CleanupEntries.pop_back();
692 
693   // Check if any branch fixups pointed to the scope we just popped. If so,
694   // we can remove them.
695   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
696     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
697     BlockScopeMap::iterator I = BlockScopes.find(Dest);
698 
699     if (I == BlockScopes.end())
700       continue;
701 
702     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
703 
704     if (I->second == CleanupEntries.size()) {
705       // We don't need to do this branch fixup.
706       BranchFixups[i] = BranchFixups.back();
707       BranchFixups.pop_back();
708       i--;
709       e--;
710       continue;
711     }
712   }
713 
714   llvm::BasicBlock *SwitchBlock = 0;
715   llvm::BasicBlock *EndBlock = 0;
716   if (!BranchFixups.empty()) {
717     SwitchBlock = createBasicBlock("cleanup.switch");
718     EndBlock = createBasicBlock("cleanup.end");
719 
720     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
721 
722     Builder.SetInsertPoint(SwitchBlock);
723 
724     llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
725                                                 "cleanup.dst");
726     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
727 
728     // Create a switch instruction to determine where to jump next.
729     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
730                                                 BranchFixups.size());
731 
732     // Restore the current basic block (if any)
733     if (CurBB) {
734       Builder.SetInsertPoint(CurBB);
735 
736       // If we had a current basic block, we also need to emit an instruction
737       // to initialize the cleanup destination.
738       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
739                           DestCodePtr);
740     } else
741       Builder.ClearInsertionPoint();
742 
743     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
744       llvm::BranchInst *BI = BranchFixups[i];
745       llvm::BasicBlock *Dest = BI->getSuccessor(0);
746 
747       // Fixup the branch instruction to point to the cleanup block.
748       BI->setSuccessor(0, CleanupBlock);
749 
750       if (CleanupEntries.empty()) {
751         llvm::ConstantInt *ID;
752 
753         // Check if we already have a destination for this block.
754         if (Dest == SI->getDefaultDest())
755           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
756         else {
757           ID = SI->findCaseDest(Dest);
758           if (!ID) {
759             // No code found, get a new unique one by using the number of
760             // switch successors.
761             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
762                                         SI->getNumSuccessors());
763             SI->addCase(ID, Dest);
764           }
765         }
766 
767         // Store the jump destination before the branch instruction.
768         new llvm::StoreInst(ID, DestCodePtr, BI);
769       } else {
770         // We need to jump through another cleanup block. Create a pad block
771         // with a branch instruction that jumps to the final destination and
772         // add it as a branch fixup to the current cleanup scope.
773 
774         // Create the pad block.
775         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
776 
777         // Create a unique case ID.
778         llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
779                                                        SI->getNumSuccessors());
780 
781         // Store the jump destination before the branch instruction.
782         new llvm::StoreInst(ID, DestCodePtr, BI);
783 
784         // Add it as the destination.
785         SI->addCase(ID, CleanupPad);
786 
787         // Create the branch to the final destination.
788         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
789         CleanupPad->getInstList().push_back(BI);
790 
791         // And add it as a branch fixup.
792         CleanupEntries.back().BranchFixups.push_back(BI);
793       }
794     }
795   }
796 
797   // Remove all blocks from the block scope map.
798   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
799     assert(BlockScopes.count(Blocks[i]) &&
800            "Did not find block in scope map!");
801 
802     BlockScopes.erase(Blocks[i]);
803   }
804 
805   return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
806 }
807 
808 void CodeGenFunction::EmitCleanupBlock() {
809   CleanupBlockInfo Info = PopCleanupBlock();
810 
811   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
812   if (CurBB && !CurBB->getTerminator() &&
813       Info.CleanupBlock->getNumUses() == 0) {
814     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
815     delete Info.CleanupBlock;
816   } else
817     EmitBlock(Info.CleanupBlock);
818 
819   if (Info.SwitchBlock)
820     EmitBlock(Info.SwitchBlock);
821   if (Info.EndBlock)
822     EmitBlock(Info.EndBlock);
823 }
824 
825 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
826   assert(!CleanupEntries.empty() &&
827          "Trying to add branch fixup without cleanup block!");
828 
829   // FIXME: We could be more clever here and check if there's already a branch
830   // fixup for this destination and recycle it.
831   CleanupEntries.back().BranchFixups.push_back(BI);
832 }
833 
834 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
835   if (!HaveInsertPoint())
836     return;
837 
838   llvm::BranchInst* BI = Builder.CreateBr(Dest);
839 
840   Builder.ClearInsertionPoint();
841 
842   // The stack is empty, no need to do any cleanup.
843   if (CleanupEntries.empty())
844     return;
845 
846   if (!Dest->getParent()) {
847     // We are trying to branch to a block that hasn't been inserted yet.
848     AddBranchFixup(BI);
849     return;
850   }
851 
852   BlockScopeMap::iterator I = BlockScopes.find(Dest);
853   if (I == BlockScopes.end()) {
854     // We are trying to jump to a block that is outside of any cleanup scope.
855     AddBranchFixup(BI);
856     return;
857   }
858 
859   assert(I->second < CleanupEntries.size() &&
860          "Trying to branch into cleanup region");
861 
862   if (I->second == CleanupEntries.size() - 1) {
863     // We have a branch to a block in the same scope.
864     return;
865   }
866 
867   AddBranchFixup(BI);
868 }
869