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