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 "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGException.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
32   : CGM(cgm), Target(CGM.getContext().Target),
33     Builder(cgm.getModule().getContext()),
34     BlockInfo(0), BlockPointer(0),
35     NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
36     ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
37     SwitchInsn(0), CaseRangeBlock(0),
38     DidCallStackSave(false), UnreachableBlock(0),
39     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
40     OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
41     TrapBB(0) {
42 
43   // Get some frequently used types.
44   LLVMPointerWidth = Target.getPointerWidth(0);
45   llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
46   IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
47   Int32Ty  = llvm::Type::getInt32Ty(LLVMContext);
48   Int64Ty  = llvm::Type::getInt64Ty(LLVMContext);
49   Int8PtrTy = cgm.Int8PtrTy;
50 
51   Exceptions = getContext().getLangOptions().Exceptions;
52   CatchUndefined = getContext().getLangOptions().CatchUndefined;
53   CGM.getCXXABI().getMangleContext().startNewFunction();
54 }
55 
56 ASTContext &CodeGenFunction::getContext() const {
57   return CGM.getContext();
58 }
59 
60 
61 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
62   return CGM.getTypes().ConvertTypeForMem(T);
63 }
64 
65 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
66   return CGM.getTypes().ConvertType(T);
67 }
68 
69 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
70   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
71     T->isObjCObjectType();
72 }
73 
74 void CodeGenFunction::EmitReturnBlock() {
75   // For cleanliness, we try to avoid emitting the return block for
76   // simple cases.
77   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
78 
79   if (CurBB) {
80     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
81 
82     // We have a valid insert point, reuse it if it is empty or there are no
83     // explicit jumps to the return block.
84     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
85       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
86       delete ReturnBlock.getBlock();
87     } else
88       EmitBlock(ReturnBlock.getBlock());
89     return;
90   }
91 
92   // Otherwise, if the return block is the target of a single direct
93   // branch then we can just put the code in that block instead. This
94   // cleans up functions which started with a unified return block.
95   if (ReturnBlock.getBlock()->hasOneUse()) {
96     llvm::BranchInst *BI =
97       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
98     if (BI && BI->isUnconditional() &&
99         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
100       // Reset insertion point and delete the branch.
101       Builder.SetInsertPoint(BI->getParent());
102       BI->eraseFromParent();
103       delete ReturnBlock.getBlock();
104       return;
105     }
106   }
107 
108   // FIXME: We are at an unreachable point, there is no reason to emit the block
109   // unless it has uses. However, we still need a place to put the debug
110   // region.end for now.
111 
112   EmitBlock(ReturnBlock.getBlock());
113 }
114 
115 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
116   if (!BB) return;
117   if (!BB->use_empty())
118     return CGF.CurFn->getBasicBlockList().push_back(BB);
119   delete BB;
120 }
121 
122 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
123   assert(BreakContinueStack.empty() &&
124          "mismatched push/pop in break/continue stack!");
125 
126   // Emit function epilog (to return).
127   EmitReturnBlock();
128 
129   EmitFunctionInstrumentation("__cyg_profile_func_exit");
130 
131   // Emit debug descriptor for function end.
132   if (CGDebugInfo *DI = getDebugInfo()) {
133     DI->setLocation(EndLoc);
134     DI->EmitFunctionEnd(Builder);
135   }
136 
137   EmitFunctionEpilog(*CurFnInfo);
138   EmitEndEHSpec(CurCodeDecl);
139 
140   assert(EHStack.empty() &&
141          "did not remove all scopes from cleanup stack!");
142 
143   // If someone did an indirect goto, emit the indirect goto block at the end of
144   // the function.
145   if (IndirectBranch) {
146     EmitBlock(IndirectBranch->getParent());
147     Builder.ClearInsertionPoint();
148   }
149 
150   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
151   llvm::Instruction *Ptr = AllocaInsertPt;
152   AllocaInsertPt = 0;
153   Ptr->eraseFromParent();
154 
155   // If someone took the address of a label but never did an indirect goto, we
156   // made a zero entry PHI node, which is illegal, zap it now.
157   if (IndirectBranch) {
158     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
159     if (PN->getNumIncomingValues() == 0) {
160       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
161       PN->eraseFromParent();
162     }
163   }
164 
165   EmitIfUsed(*this, RethrowBlock.getBlock());
166   EmitIfUsed(*this, TerminateLandingPad);
167   EmitIfUsed(*this, TerminateHandler);
168   EmitIfUsed(*this, UnreachableBlock);
169 
170   if (CGM.getCodeGenOpts().EmitDeclMetadata)
171     EmitDeclMetadata();
172 }
173 
174 /// ShouldInstrumentFunction - Return true if the current function should be
175 /// instrumented with __cyg_profile_func_* calls
176 bool CodeGenFunction::ShouldInstrumentFunction() {
177   if (!CGM.getCodeGenOpts().InstrumentFunctions)
178     return false;
179   if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
180     return false;
181   return true;
182 }
183 
184 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
185 /// instrumentation function with the current function and the call site, if
186 /// function instrumentation is enabled.
187 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
188   if (!ShouldInstrumentFunction())
189     return;
190 
191   const llvm::PointerType *PointerTy;
192   const llvm::FunctionType *FunctionTy;
193   std::vector<const llvm::Type*> ProfileFuncArgs;
194 
195   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
196   PointerTy = Int8PtrTy;
197   ProfileFuncArgs.push_back(PointerTy);
198   ProfileFuncArgs.push_back(PointerTy);
199   FunctionTy = llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
200                                        ProfileFuncArgs, false);
201 
202   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
203   llvm::CallInst *CallSite = Builder.CreateCall(
204     CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
205     llvm::ConstantInt::get(Int32Ty, 0),
206     "callsite");
207 
208   Builder.CreateCall2(F,
209                       llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
210                       CallSite);
211 }
212 
213 void CodeGenFunction::EmitMCountInstrumentation() {
214   llvm::FunctionType *FTy =
215     llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
216 
217   llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
218                                                        Target.getMCountName());
219   Builder.CreateCall(MCountFn);
220 }
221 
222 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
223                                     llvm::Function *Fn,
224                                     const FunctionArgList &Args,
225                                     SourceLocation StartLoc) {
226   const Decl *D = GD.getDecl();
227 
228   DidCallStackSave = false;
229   CurCodeDecl = CurFuncDecl = D;
230   FnRetTy = RetTy;
231   CurFn = Fn;
232   assert(CurFn->isDeclaration() && "Function already has body?");
233 
234   // Pass inline keyword to optimizer if it appears explicitly on any
235   // declaration.
236   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
237     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
238            RE = FD->redecls_end(); RI != RE; ++RI)
239       if (RI->isInlineSpecified()) {
240         Fn->addFnAttr(llvm::Attribute::InlineHint);
241         break;
242       }
243 
244   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
245 
246   // Create a marker to make it easy to insert allocas into the entryblock
247   // later.  Don't create this with the builder, because we don't want it
248   // folded.
249   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
250   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
251   if (Builder.isNamePreserving())
252     AllocaInsertPt->setName("allocapt");
253 
254   ReturnBlock = getJumpDestInCurrentScope("return");
255 
256   Builder.SetInsertPoint(EntryBB);
257 
258   // Emit subprogram debug descriptor.
259   if (CGDebugInfo *DI = getDebugInfo()) {
260     // FIXME: what is going on here and why does it ignore all these
261     // interesting type properties?
262     QualType FnType =
263       getContext().getFunctionType(RetTy, 0, 0,
264                                    FunctionProtoType::ExtProtoInfo());
265 
266     DI->setLocation(StartLoc);
267     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
268   }
269 
270   EmitFunctionInstrumentation("__cyg_profile_func_enter");
271 
272   if (CGM.getCodeGenOpts().InstrumentForProfiling)
273     EmitMCountInstrumentation();
274 
275   // FIXME: Leaked.
276   // CC info is ignored, hopefully?
277   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
278                                               FunctionType::ExtInfo());
279 
280   if (RetTy->isVoidType()) {
281     // Void type; nothing to return.
282     ReturnValue = 0;
283   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
284              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
285     // Indirect aggregate return; emit returned value directly into sret slot.
286     // This reduces code size, and affects correctness in C++.
287     ReturnValue = CurFn->arg_begin();
288   } else {
289     ReturnValue = CreateIRTemp(RetTy, "retval");
290   }
291 
292   EmitStartEHSpec(CurCodeDecl);
293   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
294 
295   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
296     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
297 
298   // If any of the arguments have a variably modified type, make sure to
299   // emit the type size.
300   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
301        i != e; ++i) {
302     QualType Ty = i->second;
303 
304     if (Ty->isVariablyModifiedType())
305       EmitVLASize(Ty);
306   }
307 }
308 
309 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
310   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
311   assert(FD->getBody());
312   EmitStmt(FD->getBody());
313 }
314 
315 /// Tries to mark the given function nounwind based on the
316 /// non-existence of any throwing calls within it.  We believe this is
317 /// lightweight enough to do at -O0.
318 static void TryMarkNoThrow(llvm::Function *F) {
319   // LLVM treats 'nounwind' on a function as part of the type, so we
320   // can't do this on functions that can be overwritten.
321   if (F->mayBeOverridden()) return;
322 
323   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
324     for (llvm::BasicBlock::iterator
325            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
326       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
327         if (!Call->doesNotThrow())
328           return;
329   F->setDoesNotThrow(true);
330 }
331 
332 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
333   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
334 
335   // Check if we should generate debug info for this function.
336   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
337     DebugInfo = CGM.getDebugInfo();
338 
339   FunctionArgList Args;
340   QualType ResTy = FD->getResultType();
341 
342   CurGD = GD;
343   if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
344     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
345 
346   if (FD->getNumParams()) {
347     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
348     assert(FProto && "Function def must have prototype!");
349 
350     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
351       Args.push_back(std::make_pair(FD->getParamDecl(i),
352                                     FProto->getArgType(i)));
353   }
354 
355   SourceRange BodyRange;
356   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
357 
358   // Emit the standard function prologue.
359   StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
360 
361   // Generate the body of the function.
362   if (isa<CXXDestructorDecl>(FD))
363     EmitDestructorBody(Args);
364   else if (isa<CXXConstructorDecl>(FD))
365     EmitConstructorBody(Args);
366   else
367     EmitFunctionBody(Args);
368 
369   // Emit the standard function epilogue.
370   FinishFunction(BodyRange.getEnd());
371 
372   // If we haven't marked the function nothrow through other means, do
373   // a quick pass now to see if we can.
374   if (!CurFn->doesNotThrow())
375     TryMarkNoThrow(CurFn);
376 }
377 
378 /// ContainsLabel - Return true if the statement contains a label in it.  If
379 /// this statement is not executed normally, it not containing a label means
380 /// that we can just remove the code.
381 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
382   // Null statement, not a label!
383   if (S == 0) return false;
384 
385   // If this is a label, we have to emit the code, consider something like:
386   // if (0) {  ...  foo:  bar(); }  goto foo;
387   if (isa<LabelStmt>(S))
388     return true;
389 
390   // If this is a case/default statement, and we haven't seen a switch, we have
391   // to emit the code.
392   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
393     return true;
394 
395   // If this is a switch statement, we want to ignore cases below it.
396   if (isa<SwitchStmt>(S))
397     IgnoreCaseStmts = true;
398 
399   // Scan subexpressions for verboten labels.
400   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
401        I != E; ++I)
402     if (ContainsLabel(*I, IgnoreCaseStmts))
403       return true;
404 
405   return false;
406 }
407 
408 
409 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
410 /// a constant, or if it does but contains a label, return 0.  If it constant
411 /// folds to 'true' and does not contain a label, return 1, if it constant folds
412 /// to 'false' and does not contain a label, return -1.
413 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
414   // FIXME: Rename and handle conversion of other evaluatable things
415   // to bool.
416   Expr::EvalResult Result;
417   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
418       Result.HasSideEffects)
419     return 0;  // Not foldable, not integer or not fully evaluatable.
420 
421   if (CodeGenFunction::ContainsLabel(Cond))
422     return 0;  // Contains a label.
423 
424   return Result.Val.getInt().getBoolValue() ? 1 : -1;
425 }
426 
427 
428 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
429 /// statement) to the specified blocks.  Based on the condition, this might try
430 /// to simplify the codegen of the conditional based on the branch.
431 ///
432 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
433                                            llvm::BasicBlock *TrueBlock,
434                                            llvm::BasicBlock *FalseBlock) {
435   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
436     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
437 
438   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
439     // Handle X && Y in a condition.
440     if (CondBOp->getOpcode() == BO_LAnd) {
441       // If we have "1 && X", simplify the code.  "0 && X" would have constant
442       // folded if the case was simple enough.
443       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
444         // br(1 && X) -> br(X).
445         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
446       }
447 
448       // If we have "X && 1", simplify the code to use an uncond branch.
449       // "X && 0" would have been constant folded to 0.
450       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
451         // br(X && 1) -> br(X).
452         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
453       }
454 
455       // Emit the LHS as a conditional.  If the LHS conditional is false, we
456       // want to jump to the FalseBlock.
457       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
458 
459       ConditionalEvaluation eval(*this);
460       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
461       EmitBlock(LHSTrue);
462 
463       // Any temporaries created here are conditional.
464       eval.begin(*this);
465       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
466       eval.end(*this);
467 
468       return;
469     } else if (CondBOp->getOpcode() == BO_LOr) {
470       // If we have "0 || X", simplify the code.  "1 || X" would have constant
471       // folded if the case was simple enough.
472       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
473         // br(0 || X) -> br(X).
474         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
475       }
476 
477       // If we have "X || 0", simplify the code to use an uncond branch.
478       // "X || 1" would have been constant folded to 1.
479       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
480         // br(X || 0) -> br(X).
481         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
482       }
483 
484       // Emit the LHS as a conditional.  If the LHS conditional is true, we
485       // want to jump to the TrueBlock.
486       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
487 
488       ConditionalEvaluation eval(*this);
489       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
490       EmitBlock(LHSFalse);
491 
492       // Any temporaries created here are conditional.
493       eval.begin(*this);
494       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
495       eval.end(*this);
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() == UO_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 
516       ConditionalEvaluation cond(*this);
517       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
518 
519       cond.begin(*this);
520       EmitBlock(LHSBlock);
521       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
522       cond.end(*this);
523 
524       cond.begin(*this);
525       EmitBlock(RHSBlock);
526       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
527       cond.end(*this);
528 
529       return;
530     }
531   }
532 
533   // Emit the code with the fully general case.
534   llvm::Value *CondV = EvaluateExprAsBool(Cond);
535   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
536 }
537 
538 /// ErrorUnsupported - Print out an error that codegen doesn't support the
539 /// specified stmt yet.
540 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
541                                        bool OmitOnError) {
542   CGM.ErrorUnsupported(S, Type, OmitOnError);
543 }
544 
545 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
546 /// variable-length array whose elements have a non-zero bit-pattern.
547 ///
548 /// \param src - a char* pointing to the bit-pattern for a single
549 /// base element of the array
550 /// \param sizeInChars - the total size of the VLA, in chars
551 /// \param align - the total alignment of the VLA
552 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
553                                llvm::Value *dest, llvm::Value *src,
554                                llvm::Value *sizeInChars) {
555   std::pair<CharUnits,CharUnits> baseSizeAndAlign
556     = CGF.getContext().getTypeInfoInChars(baseType);
557 
558   CGBuilderTy &Builder = CGF.Builder;
559 
560   llvm::Value *baseSizeInChars
561     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
562 
563   const llvm::Type *i8p = Builder.getInt8PtrTy();
564 
565   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
566   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
567 
568   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
569   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
570   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
571 
572   // Make a loop over the VLA.  C99 guarantees that the VLA element
573   // count must be nonzero.
574   CGF.EmitBlock(loopBB);
575 
576   llvm::PHINode *cur = Builder.CreatePHI(i8p, "vla.cur");
577   cur->reserveOperandSpace(2);
578   cur->addIncoming(begin, originBB);
579 
580   // memcpy the individual element bit-pattern.
581   Builder.CreateMemCpy(cur, src, baseSizeInChars,
582                        baseSizeAndAlign.second.getQuantity(),
583                        /*volatile*/ false);
584 
585   // Go to the next element.
586   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
587 
588   // Leave if that's the end of the VLA.
589   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
590   Builder.CreateCondBr(done, contBB, loopBB);
591   cur->addIncoming(next, loopBB);
592 
593   CGF.EmitBlock(contBB);
594 }
595 
596 void
597 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
598   // Ignore empty classes in C++.
599   if (getContext().getLangOptions().CPlusPlus) {
600     if (const RecordType *RT = Ty->getAs<RecordType>()) {
601       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
602         return;
603     }
604   }
605 
606   // Cast the dest ptr to the appropriate i8 pointer type.
607   unsigned DestAS =
608     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
609   const llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
610   if (DestPtr->getType() != BP)
611     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
612 
613   // Get size and alignment info for this aggregate.
614   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
615   uint64_t Size = TypeInfo.first / 8;
616   unsigned Align = TypeInfo.second / 8;
617 
618   llvm::Value *SizeVal;
619   const VariableArrayType *vla;
620 
621   // Don't bother emitting a zero-byte memset.
622   if (Size == 0) {
623     // But note that getTypeInfo returns 0 for a VLA.
624     if (const VariableArrayType *vlaType =
625           dyn_cast_or_null<VariableArrayType>(
626                                           getContext().getAsArrayType(Ty))) {
627       SizeVal = GetVLASize(vlaType);
628       vla = vlaType;
629     } else {
630       return;
631     }
632   } else {
633     SizeVal = llvm::ConstantInt::get(IntPtrTy, Size);
634     vla = 0;
635   }
636 
637   // If the type contains a pointer to data member we can't memset it to zero.
638   // Instead, create a null constant and copy it to the destination.
639   // TODO: there are other patterns besides zero that we can usefully memset,
640   // like -1, which happens to be the pattern used by member-pointers.
641   if (!CGM.getTypes().isZeroInitializable(Ty)) {
642     // For a VLA, emit a single element, then splat that over the VLA.
643     if (vla) Ty = getContext().getBaseElementType(vla);
644 
645     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
646 
647     llvm::GlobalVariable *NullVariable =
648       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
649                                /*isConstant=*/true,
650                                llvm::GlobalVariable::PrivateLinkage,
651                                NullConstant, llvm::Twine());
652     llvm::Value *SrcPtr =
653       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
654 
655     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
656 
657     // Get and call the appropriate llvm.memcpy overload.
658     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false);
659     return;
660   }
661 
662   // Otherwise, just memset the whole thing to zero.  This is legal
663   // because in LLVM, all default initializers (other than the ones we just
664   // handled above) are guaranteed to have a bit pattern of all zeros.
665   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false);
666 }
667 
668 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
669   // Make sure that there is a block for the indirect goto.
670   if (IndirectBranch == 0)
671     GetIndirectGotoBlock();
672 
673   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
674 
675   // Make sure the indirect branch includes all of the address-taken blocks.
676   IndirectBranch->addDestination(BB);
677   return llvm::BlockAddress::get(CurFn, BB);
678 }
679 
680 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
681   // If we already made the indirect branch for indirect goto, return its block.
682   if (IndirectBranch) return IndirectBranch->getParent();
683 
684   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
685 
686   // Create the PHI node that indirect gotos will add entries to.
687   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
688 
689   // Create the indirect branch instruction.
690   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
691   return IndirectBranch->getParent();
692 }
693 
694 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
695   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
696 
697   assert(SizeEntry && "Did not emit size for type");
698   return SizeEntry;
699 }
700 
701 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
702   assert(Ty->isVariablyModifiedType() &&
703          "Must pass variably modified type to EmitVLASizes!");
704 
705   EnsureInsertPoint();
706 
707   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
708     // unknown size indication requires no size computation.
709     if (!VAT->getSizeExpr())
710       return 0;
711     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
712 
713     if (!SizeEntry) {
714       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
715 
716       // Get the element size;
717       QualType ElemTy = VAT->getElementType();
718       llvm::Value *ElemSize;
719       if (ElemTy->isVariableArrayType())
720         ElemSize = EmitVLASize(ElemTy);
721       else
722         ElemSize = llvm::ConstantInt::get(SizeTy,
723             getContext().getTypeSizeInChars(ElemTy).getQuantity());
724 
725       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
726       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
727 
728       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
729     }
730 
731     return SizeEntry;
732   }
733 
734   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
735     EmitVLASize(AT->getElementType());
736     return 0;
737   }
738 
739   if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
740     EmitVLASize(PT->getInnerType());
741     return 0;
742   }
743 
744   const PointerType *PT = Ty->getAs<PointerType>();
745   assert(PT && "unknown VM type!");
746   EmitVLASize(PT->getPointeeType());
747   return 0;
748 }
749 
750 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
751   if (getContext().getBuiltinVaListType()->isArrayType())
752     return EmitScalarExpr(E);
753   return EmitLValue(E).getAddress();
754 }
755 
756 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
757                                               llvm::Constant *Init) {
758   assert (Init && "Invalid DeclRefExpr initializer!");
759   if (CGDebugInfo *Dbg = getDebugInfo())
760     Dbg->EmitGlobalVariable(E->getDecl(), Init);
761 }
762