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 "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CodeGenModule.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/OpenCL.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Operator.h"
31 using namespace clang;
32 using namespace CodeGen;
33 
34 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
35     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
36       Builder(cgm.getModule().getContext()), CapturedStmtInfo(0),
37       SanitizePerformTypeCheck(CGM.getSanOpts().Null |
38                                CGM.getSanOpts().Alignment |
39                                CGM.getSanOpts().ObjectSize |
40                                CGM.getSanOpts().Vptr),
41       SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(0),
42       BlockPointer(0), LambdaThisCaptureField(0), NormalCleanupDest(0),
43       NextCleanupDestIndex(1), FirstBlockInfo(0), EHResumeBlock(0),
44       ExceptionSlot(0), EHSelectorSlot(0), DebugInfo(CGM.getModuleDebugInfo()),
45       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(0),
46       SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), NumReturnExprs(0),
47       NumSimpleReturnExprs(0), CXXABIThisDecl(0), CXXABIThisValue(0),
48       CXXThisValue(0), CXXDefaultInitExprThis(0),
49       CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0),
50       OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0),
51       TerminateHandler(0), TrapBB(0) {
52   if (!suppressNewContext)
53     CGM.getCXXABI().getMangleContext().startNewFunction();
54 
55   llvm::FastMathFlags FMF;
56   if (CGM.getLangOpts().FastMath)
57     FMF.setUnsafeAlgebra();
58   if (CGM.getLangOpts().FiniteMathOnly) {
59     FMF.setNoNaNs();
60     FMF.setNoInfs();
61   }
62   Builder.SetFastMathFlags(FMF);
63 }
64 
65 CodeGenFunction::~CodeGenFunction() {
66   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
67 
68   // If there are any unclaimed block infos, go ahead and destroy them
69   // now.  This can happen if IR-gen gets clever and skips evaluating
70   // something.
71   if (FirstBlockInfo)
72     destroyBlockInfos(FirstBlockInfo);
73 }
74 
75 
76 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
77   return CGM.getTypes().ConvertTypeForMem(T);
78 }
79 
80 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
81   return CGM.getTypes().ConvertType(T);
82 }
83 
84 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
85   type = type.getCanonicalType();
86   while (true) {
87     switch (type->getTypeClass()) {
88 #define TYPE(name, parent)
89 #define ABSTRACT_TYPE(name, parent)
90 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
91 #define DEPENDENT_TYPE(name, parent) case Type::name:
92 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
93 #include "clang/AST/TypeNodes.def"
94       llvm_unreachable("non-canonical or dependent type in IR-generation");
95 
96     case Type::Auto:
97       llvm_unreachable("undeduced auto type in IR-generation");
98 
99     // Various scalar types.
100     case Type::Builtin:
101     case Type::Pointer:
102     case Type::BlockPointer:
103     case Type::LValueReference:
104     case Type::RValueReference:
105     case Type::MemberPointer:
106     case Type::Vector:
107     case Type::ExtVector:
108     case Type::FunctionProto:
109     case Type::FunctionNoProto:
110     case Type::Enum:
111     case Type::ObjCObjectPointer:
112       return TEK_Scalar;
113 
114     // Complexes.
115     case Type::Complex:
116       return TEK_Complex;
117 
118     // Arrays, records, and Objective-C objects.
119     case Type::ConstantArray:
120     case Type::IncompleteArray:
121     case Type::VariableArray:
122     case Type::Record:
123     case Type::ObjCObject:
124     case Type::ObjCInterface:
125       return TEK_Aggregate;
126 
127     // We operate on atomic values according to their underlying type.
128     case Type::Atomic:
129       type = cast<AtomicType>(type)->getValueType();
130       continue;
131     }
132     llvm_unreachable("unknown type kind!");
133   }
134 }
135 
136 void CodeGenFunction::EmitReturnBlock() {
137   // For cleanliness, we try to avoid emitting the return block for
138   // simple cases.
139   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
140 
141   if (CurBB) {
142     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
143 
144     // We have a valid insert point, reuse it if it is empty or there are no
145     // explicit jumps to the return block.
146     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
147       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
148       delete ReturnBlock.getBlock();
149     } else
150       EmitBlock(ReturnBlock.getBlock());
151     return;
152   }
153 
154   // Otherwise, if the return block is the target of a single direct
155   // branch then we can just put the code in that block instead. This
156   // cleans up functions which started with a unified return block.
157   if (ReturnBlock.getBlock()->hasOneUse()) {
158     llvm::BranchInst *BI =
159       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
160     if (BI && BI->isUnconditional() &&
161         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
162       // Reset insertion point, including debug location, and delete the
163       // branch.  This is really subtle and only works because the next change
164       // in location will hit the caching in CGDebugInfo::EmitLocation and not
165       // override this.
166       Builder.SetCurrentDebugLocation(BI->getDebugLoc());
167       Builder.SetInsertPoint(BI->getParent());
168       BI->eraseFromParent();
169       delete ReturnBlock.getBlock();
170       return;
171     }
172   }
173 
174   // FIXME: We are at an unreachable point, there is no reason to emit the block
175   // unless it has uses. However, we still need a place to put the debug
176   // region.end for now.
177 
178   EmitBlock(ReturnBlock.getBlock());
179 }
180 
181 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
182   if (!BB) return;
183   if (!BB->use_empty())
184     return CGF.CurFn->getBasicBlockList().push_back(BB);
185   delete BB;
186 }
187 
188 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
189   assert(BreakContinueStack.empty() &&
190          "mismatched push/pop in break/continue stack!");
191 
192   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
193     && NumSimpleReturnExprs == NumReturnExprs
194     && ReturnBlock.getBlock()->use_empty();
195   // Usually the return expression is evaluated before the cleanup
196   // code.  If the function contains only a simple return statement,
197   // such as a constant, the location before the cleanup code becomes
198   // the last useful breakpoint in the function, because the simple
199   // return expression will be evaluated after the cleanup code. To be
200   // safe, set the debug location for cleanup code to the location of
201   // the return statement.  Otherwise the cleanup code should be at the
202   // end of the function's lexical scope.
203   //
204   // If there are multiple branches to the return block, the branch
205   // instructions will get the location of the return statements and
206   // all will be fine.
207   if (CGDebugInfo *DI = getDebugInfo()) {
208     if (OnlySimpleReturnStmts)
209       DI->EmitLocation(Builder, LastStopPoint);
210     else
211       DI->EmitLocation(Builder, EndLoc);
212   }
213 
214   // Pop any cleanups that might have been associated with the
215   // parameters.  Do this in whatever block we're currently in; it's
216   // important to do this before we enter the return block or return
217   // edges will be *really* confused.
218   bool EmitRetDbgLoc = true;
219   if (EHStack.stable_begin() != PrologueCleanupDepth) {
220     PopCleanupBlocks(PrologueCleanupDepth);
221 
222     // Make sure the line table doesn't jump back into the body for
223     // the ret after it's been at EndLoc.
224     EmitRetDbgLoc = false;
225 
226     if (CGDebugInfo *DI = getDebugInfo())
227       if (OnlySimpleReturnStmts)
228         DI->EmitLocation(Builder, EndLoc);
229   }
230 
231   // Emit function epilog (to return).
232   EmitReturnBlock();
233 
234   if (ShouldInstrumentFunction())
235     EmitFunctionInstrumentation("__cyg_profile_func_exit");
236 
237   // Emit debug descriptor for function end.
238   if (CGDebugInfo *DI = getDebugInfo()) {
239     DI->EmitFunctionEnd(Builder);
240   }
241 
242   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
243   EmitEndEHSpec(CurCodeDecl);
244 
245   assert(EHStack.empty() &&
246          "did not remove all scopes from cleanup stack!");
247 
248   // If someone did an indirect goto, emit the indirect goto block at the end of
249   // the function.
250   if (IndirectBranch) {
251     EmitBlock(IndirectBranch->getParent());
252     Builder.ClearInsertionPoint();
253   }
254 
255   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
256   llvm::Instruction *Ptr = AllocaInsertPt;
257   AllocaInsertPt = 0;
258   Ptr->eraseFromParent();
259 
260   // If someone took the address of a label but never did an indirect goto, we
261   // made a zero entry PHI node, which is illegal, zap it now.
262   if (IndirectBranch) {
263     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
264     if (PN->getNumIncomingValues() == 0) {
265       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
266       PN->eraseFromParent();
267     }
268   }
269 
270   EmitIfUsed(*this, EHResumeBlock);
271   EmitIfUsed(*this, TerminateLandingPad);
272   EmitIfUsed(*this, TerminateHandler);
273   EmitIfUsed(*this, UnreachableBlock);
274 
275   if (CGM.getCodeGenOpts().EmitDeclMetadata)
276     EmitDeclMetadata();
277 }
278 
279 /// ShouldInstrumentFunction - Return true if the current function should be
280 /// instrumented with __cyg_profile_func_* calls
281 bool CodeGenFunction::ShouldInstrumentFunction() {
282   if (!CGM.getCodeGenOpts().InstrumentFunctions)
283     return false;
284   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
285     return false;
286   return true;
287 }
288 
289 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
290 /// instrumentation function with the current function and the call site, if
291 /// function instrumentation is enabled.
292 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
293   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
294   llvm::PointerType *PointerTy = Int8PtrTy;
295   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
296   llvm::FunctionType *FunctionTy =
297     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
298 
299   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
300   llvm::CallInst *CallSite = Builder.CreateCall(
301     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
302     llvm::ConstantInt::get(Int32Ty, 0),
303     "callsite");
304 
305   llvm::Value *args[] = {
306     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
307     CallSite
308   };
309 
310   EmitNounwindRuntimeCall(F, args);
311 }
312 
313 void CodeGenFunction::EmitMCountInstrumentation() {
314   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
315 
316   llvm::Constant *MCountFn =
317     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
318   EmitNounwindRuntimeCall(MCountFn);
319 }
320 
321 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
322 // information in the program executable. The argument information stored
323 // includes the argument name, its type, the address and access qualifiers used.
324 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
325                                  CodeGenModule &CGM,llvm::LLVMContext &Context,
326                                  SmallVector <llvm::Value*, 5> &kernelMDArgs,
327                                  CGBuilderTy& Builder, ASTContext &ASTCtx) {
328   // Create MDNodes that represent the kernel arg metadata.
329   // Each MDNode is a list in the form of "key", N number of values which is
330   // the same number of values as their are kernel arguments.
331 
332   // MDNode for the kernel argument address space qualifiers.
333   SmallVector<llvm::Value*, 8> addressQuals;
334   addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
335 
336   // MDNode for the kernel argument access qualifiers (images only).
337   SmallVector<llvm::Value*, 8> accessQuals;
338   accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
339 
340   // MDNode for the kernel argument type names.
341   SmallVector<llvm::Value*, 8> argTypeNames;
342   argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
343 
344   // MDNode for the kernel argument type qualifiers.
345   SmallVector<llvm::Value*, 8> argTypeQuals;
346   argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
347 
348   // MDNode for the kernel argument names.
349   SmallVector<llvm::Value*, 8> argNames;
350   argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
351 
352   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
353     const ParmVarDecl *parm = FD->getParamDecl(i);
354     QualType ty = parm->getType();
355     std::string typeQuals;
356 
357     if (ty->isPointerType()) {
358       QualType pointeeTy = ty->getPointeeType();
359 
360       // Get address qualifier.
361       addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
362         pointeeTy.getAddressSpace())));
363 
364       // Get argument type name.
365       std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*";
366 
367       // Turn "unsigned type" to "utype"
368       std::string::size_type pos = typeName.find("unsigned");
369       if (pos != std::string::npos)
370         typeName.erase(pos+1, 8);
371 
372       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
373 
374       // Get argument type qualifiers:
375       if (ty.isRestrictQualified())
376         typeQuals = "restrict";
377       if (pointeeTy.isConstQualified() ||
378           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
379         typeQuals += typeQuals.empty() ? "const" : " const";
380       if (pointeeTy.isVolatileQualified())
381         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
382     } else {
383       addressQuals.push_back(Builder.getInt32(0));
384 
385       // Get argument type name.
386       std::string typeName = ty.getUnqualifiedType().getAsString();
387 
388       // Turn "unsigned type" to "utype"
389       std::string::size_type pos = typeName.find("unsigned");
390       if (pos != std::string::npos)
391         typeName.erase(pos+1, 8);
392 
393       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
394 
395       // Get argument type qualifiers:
396       if (ty.isConstQualified())
397         typeQuals = "const";
398       if (ty.isVolatileQualified())
399         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
400     }
401 
402     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
403 
404     // Get image access qualifier:
405     if (ty->isImageType()) {
406       if (parm->hasAttr<OpenCLImageAccessAttr>() &&
407           parm->getAttr<OpenCLImageAccessAttr>()->getAccess() == CLIA_write_only)
408         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
409       else
410         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
411     } else
412       accessQuals.push_back(llvm::MDString::get(Context, "none"));
413 
414     // Get argument name.
415     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
416   }
417 
418   kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
419   kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
420   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
421   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
422   kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
423 }
424 
425 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
426                                                llvm::Function *Fn)
427 {
428   if (!FD->hasAttr<OpenCLKernelAttr>())
429     return;
430 
431   llvm::LLVMContext &Context = getLLVMContext();
432 
433   SmallVector <llvm::Value*, 5> kernelMDArgs;
434   kernelMDArgs.push_back(Fn);
435 
436   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
437     GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
438                          Builder, getContext());
439 
440   if (FD->hasAttr<VecTypeHintAttr>()) {
441     VecTypeHintAttr *attr = FD->getAttr<VecTypeHintAttr>();
442     QualType hintQTy = attr->getTypeHint();
443     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
444     bool isSignedInteger =
445         hintQTy->isSignedIntegerType() ||
446         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
447     llvm::Value *attrMDArgs[] = {
448       llvm::MDString::get(Context, "vec_type_hint"),
449       llvm::UndefValue::get(CGM.getTypes().ConvertType(attr->getTypeHint())),
450       llvm::ConstantInt::get(
451           llvm::IntegerType::get(Context, 32),
452           llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
453     };
454     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
455   }
456 
457   if (FD->hasAttr<WorkGroupSizeHintAttr>()) {
458     WorkGroupSizeHintAttr *attr = FD->getAttr<WorkGroupSizeHintAttr>();
459     llvm::Value *attrMDArgs[] = {
460       llvm::MDString::get(Context, "work_group_size_hint"),
461       Builder.getInt32(attr->getXDim()),
462       Builder.getInt32(attr->getYDim()),
463       Builder.getInt32(attr->getZDim())
464     };
465     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
466   }
467 
468   if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
469     ReqdWorkGroupSizeAttr *attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
470     llvm::Value *attrMDArgs[] = {
471       llvm::MDString::get(Context, "reqd_work_group_size"),
472       Builder.getInt32(attr->getXDim()),
473       Builder.getInt32(attr->getYDim()),
474       Builder.getInt32(attr->getZDim())
475     };
476     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
477   }
478 
479   llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
480   llvm::NamedMDNode *OpenCLKernelMetadata =
481     CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
482   OpenCLKernelMetadata->addOperand(kernelMDNode);
483 }
484 
485 void CodeGenFunction::StartFunction(GlobalDecl GD,
486                                     QualType RetTy,
487                                     llvm::Function *Fn,
488                                     const CGFunctionInfo &FnInfo,
489                                     const FunctionArgList &Args,
490                                     SourceLocation StartLoc) {
491   const Decl *D = GD.getDecl();
492 
493   DidCallStackSave = false;
494   CurCodeDecl = D;
495   CurFuncDecl = (D ? D->getNonClosureContext() : 0);
496   FnRetTy = RetTy;
497   CurFn = Fn;
498   CurFnInfo = &FnInfo;
499   assert(CurFn->isDeclaration() && "Function already has body?");
500 
501   if (CGM.getSanitizerBlacklist().isIn(*Fn)) {
502     SanOpts = &SanitizerOptions::Disabled;
503     SanitizePerformTypeCheck = false;
504   }
505 
506   // Pass inline keyword to optimizer if it appears explicitly on any
507   // declaration.
508   if (!CGM.getCodeGenOpts().NoInline)
509     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
510       for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
511              RE = FD->redecls_end(); RI != RE; ++RI)
512         if (RI->isInlineSpecified()) {
513           Fn->addFnAttr(llvm::Attribute::InlineHint);
514           break;
515         }
516 
517   if (getLangOpts().OpenCL) {
518     // Add metadata for a kernel function.
519     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
520       EmitOpenCLKernelMetadata(FD, Fn);
521   }
522 
523   // If we are checking function types, emit a function type signature as
524   // prefix data.
525   if (getLangOpts().CPlusPlus && SanOpts->Function) {
526     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
527       if (llvm::Constant *PrefixSig =
528               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
529         llvm::Constant *FTRTTIConst =
530             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
531         llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
532         llvm::Constant *PrefixStructConst =
533             llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
534         Fn->setPrefixData(PrefixStructConst);
535       }
536     }
537   }
538 
539   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
540 
541   // Create a marker to make it easy to insert allocas into the entryblock
542   // later.  Don't create this with the builder, because we don't want it
543   // folded.
544   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
545   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
546   if (Builder.isNamePreserving())
547     AllocaInsertPt->setName("allocapt");
548 
549   ReturnBlock = getJumpDestInCurrentScope("return");
550 
551   Builder.SetInsertPoint(EntryBB);
552 
553   // Emit subprogram debug descriptor.
554   if (CGDebugInfo *DI = getDebugInfo()) {
555     SmallVector<QualType, 16> ArgTypes;
556     for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
557 	 i != e; ++i) {
558       ArgTypes.push_back((*i)->getType());
559     }
560 
561     QualType FnType =
562       getContext().getFunctionType(RetTy, ArgTypes,
563                                    FunctionProtoType::ExtProtoInfo());
564 
565     DI->setLocation(StartLoc);
566     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
567   }
568 
569   if (ShouldInstrumentFunction())
570     EmitFunctionInstrumentation("__cyg_profile_func_enter");
571 
572   if (CGM.getCodeGenOpts().InstrumentForProfiling)
573     EmitMCountInstrumentation();
574 
575   if (RetTy->isVoidType()) {
576     // Void type; nothing to return.
577     ReturnValue = 0;
578   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
579              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
580     // Indirect aggregate return; emit returned value directly into sret slot.
581     // This reduces code size, and affects correctness in C++.
582     ReturnValue = CurFn->arg_begin();
583   } else {
584     ReturnValue = CreateIRTemp(RetTy, "retval");
585 
586     // Tell the epilog emitter to autorelease the result.  We do this
587     // now so that various specialized functions can suppress it
588     // during their IR-generation.
589     if (getLangOpts().ObjCAutoRefCount &&
590         !CurFnInfo->isReturnsRetained() &&
591         RetTy->isObjCRetainableType())
592       AutoreleaseResult = true;
593   }
594 
595   EmitStartEHSpec(CurCodeDecl);
596 
597   PrologueCleanupDepth = EHStack.stable_begin();
598   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
599 
600   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
601     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
602     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
603     if (MD->getParent()->isLambda() &&
604         MD->getOverloadedOperator() == OO_Call) {
605       // We're in a lambda; figure out the captures.
606       MD->getParent()->getCaptureFields(LambdaCaptureFields,
607                                         LambdaThisCaptureField);
608       if (LambdaThisCaptureField) {
609         // If this lambda captures this, load it.
610         LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
611         CXXThisValue = EmitLoadOfLValue(ThisLValue,
612                                         SourceLocation()).getScalarVal();
613       }
614     } else {
615       // Not in a lambda; just use 'this' from the method.
616       // FIXME: Should we generate a new load for each use of 'this'?  The
617       // fast register allocator would be happier...
618       CXXThisValue = CXXABIThisValue;
619     }
620   }
621 
622   // If any of the arguments have a variably modified type, make sure to
623   // emit the type size.
624   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
625        i != e; ++i) {
626     const VarDecl *VD = *i;
627 
628     // Dig out the type as written from ParmVarDecls; it's unclear whether
629     // the standard (C99 6.9.1p10) requires this, but we're following the
630     // precedent set by gcc.
631     QualType Ty;
632     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
633       Ty = PVD->getOriginalType();
634     else
635       Ty = VD->getType();
636 
637     if (Ty->isVariablyModifiedType())
638       EmitVariablyModifiedType(Ty);
639   }
640   // Emit a location at the end of the prologue.
641   if (CGDebugInfo *DI = getDebugInfo())
642     DI->EmitLocation(Builder, StartLoc);
643 }
644 
645 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
646   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
647   assert(FD->getBody());
648   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody()))
649     EmitCompoundStmtWithoutScope(*S);
650   else
651     EmitStmt(FD->getBody());
652 }
653 
654 /// Tries to mark the given function nounwind based on the
655 /// non-existence of any throwing calls within it.  We believe this is
656 /// lightweight enough to do at -O0.
657 static void TryMarkNoThrow(llvm::Function *F) {
658   // LLVM treats 'nounwind' on a function as part of the type, so we
659   // can't do this on functions that can be overwritten.
660   if (F->mayBeOverridden()) return;
661 
662   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
663     for (llvm::BasicBlock::iterator
664            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
665       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
666         if (!Call->doesNotThrow())
667           return;
668       } else if (isa<llvm::ResumeInst>(&*BI)) {
669         return;
670       }
671   F->setDoesNotThrow();
672 }
673 
674 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
675                                    const CGFunctionInfo &FnInfo) {
676   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
677 
678   // Check if we should generate debug info for this function.
679   if (FD->hasAttr<NoDebugAttr>())
680     DebugInfo = NULL; // disable debug info indefinitely for this function
681 
682   FunctionArgList Args;
683   QualType ResTy = FD->getResultType();
684 
685   CurGD = GD;
686   const CXXMethodDecl *MD;
687   if ((MD = dyn_cast<CXXMethodDecl>(FD)) && MD->isInstance()) {
688     if (CGM.getCXXABI().HasThisReturn(GD))
689       ResTy = MD->getThisType(getContext());
690     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
691   }
692 
693   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
694     Args.push_back(FD->getParamDecl(i));
695 
696   SourceRange BodyRange;
697   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
698   CurEHLocation = BodyRange.getEnd();
699 
700   // Emit the standard function prologue.
701   StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
702 
703   // Generate the body of the function.
704   if (isa<CXXDestructorDecl>(FD))
705     EmitDestructorBody(Args);
706   else if (isa<CXXConstructorDecl>(FD))
707     EmitConstructorBody(Args);
708   else if (getLangOpts().CUDA &&
709            !CGM.getCodeGenOpts().CUDAIsDevice &&
710            FD->hasAttr<CUDAGlobalAttr>())
711     CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
712   else if (isa<CXXConversionDecl>(FD) &&
713            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
714     // The lambda conversion to block pointer is special; the semantics can't be
715     // expressed in the AST, so IRGen needs to special-case it.
716     EmitLambdaToBlockPointerBody(Args);
717   } else if (isa<CXXMethodDecl>(FD) &&
718              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
719     // The lambda static invoker function is special, because it forwards or
720     // clones the body of the function call operator (but is actually static).
721     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
722   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
723              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
724               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
725     // Implicit copy-assignment gets the same special treatment as implicit
726     // copy-constructors.
727     emitImplicitAssignmentOperatorBody(Args);
728   }
729   else
730     EmitFunctionBody(Args);
731 
732   // C++11 [stmt.return]p2:
733   //   Flowing off the end of a function [...] results in undefined behavior in
734   //   a value-returning function.
735   // C11 6.9.1p12:
736   //   If the '}' that terminates a function is reached, and the value of the
737   //   function call is used by the caller, the behavior is undefined.
738   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() &&
739       !FD->getResultType()->isVoidType() && Builder.GetInsertBlock()) {
740     if (SanOpts->Return)
741       EmitCheck(Builder.getFalse(), "missing_return",
742                 EmitCheckSourceLocation(FD->getLocation()),
743                 ArrayRef<llvm::Value *>(), CRK_Unrecoverable);
744     else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
745       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
746     Builder.CreateUnreachable();
747     Builder.ClearInsertionPoint();
748   }
749 
750   // Emit the standard function epilogue.
751   FinishFunction(BodyRange.getEnd());
752 
753   // If we haven't marked the function nothrow through other means, do
754   // a quick pass now to see if we can.
755   if (!CurFn->doesNotThrow())
756     TryMarkNoThrow(CurFn);
757 }
758 
759 /// ContainsLabel - Return true if the statement contains a label in it.  If
760 /// this statement is not executed normally, it not containing a label means
761 /// that we can just remove the code.
762 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
763   // Null statement, not a label!
764   if (S == 0) return false;
765 
766   // If this is a label, we have to emit the code, consider something like:
767   // if (0) {  ...  foo:  bar(); }  goto foo;
768   //
769   // TODO: If anyone cared, we could track __label__'s, since we know that you
770   // can't jump to one from outside their declared region.
771   if (isa<LabelStmt>(S))
772     return true;
773 
774   // If this is a case/default statement, and we haven't seen a switch, we have
775   // to emit the code.
776   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
777     return true;
778 
779   // If this is a switch statement, we want to ignore cases below it.
780   if (isa<SwitchStmt>(S))
781     IgnoreCaseStmts = true;
782 
783   // Scan subexpressions for verboten labels.
784   for (Stmt::const_child_range I = S->children(); I; ++I)
785     if (ContainsLabel(*I, IgnoreCaseStmts))
786       return true;
787 
788   return false;
789 }
790 
791 /// containsBreak - Return true if the statement contains a break out of it.
792 /// If the statement (recursively) contains a switch or loop with a break
793 /// inside of it, this is fine.
794 bool CodeGenFunction::containsBreak(const Stmt *S) {
795   // Null statement, not a label!
796   if (S == 0) return false;
797 
798   // If this is a switch or loop that defines its own break scope, then we can
799   // include it and anything inside of it.
800   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
801       isa<ForStmt>(S))
802     return false;
803 
804   if (isa<BreakStmt>(S))
805     return true;
806 
807   // Scan subexpressions for verboten breaks.
808   for (Stmt::const_child_range I = S->children(); I; ++I)
809     if (containsBreak(*I))
810       return true;
811 
812   return false;
813 }
814 
815 
816 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
817 /// to a constant, or if it does but contains a label, return false.  If it
818 /// constant folds return true and set the boolean result in Result.
819 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
820                                                    bool &ResultBool) {
821   llvm::APSInt ResultInt;
822   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
823     return false;
824 
825   ResultBool = ResultInt.getBoolValue();
826   return true;
827 }
828 
829 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
830 /// to a constant, or if it does but contains a label, return false.  If it
831 /// constant folds return true and set the folded value.
832 bool CodeGenFunction::
833 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
834   // FIXME: Rename and handle conversion of other evaluatable things
835   // to bool.
836   llvm::APSInt Int;
837   if (!Cond->EvaluateAsInt(Int, getContext()))
838     return false;  // Not foldable, not integer or not fully evaluatable.
839 
840   if (CodeGenFunction::ContainsLabel(Cond))
841     return false;  // Contains a label.
842 
843   ResultInt = Int;
844   return true;
845 }
846 
847 
848 
849 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
850 /// statement) to the specified blocks.  Based on the condition, this might try
851 /// to simplify the codegen of the conditional based on the branch.
852 ///
853 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
854                                            llvm::BasicBlock *TrueBlock,
855                                            llvm::BasicBlock *FalseBlock) {
856   Cond = Cond->IgnoreParens();
857 
858   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
859     // Handle X && Y in a condition.
860     if (CondBOp->getOpcode() == BO_LAnd) {
861       // If we have "1 && X", simplify the code.  "0 && X" would have constant
862       // folded if the case was simple enough.
863       bool ConstantBool = false;
864       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
865           ConstantBool) {
866         // br(1 && X) -> br(X).
867         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
868       }
869 
870       // If we have "X && 1", simplify the code to use an uncond branch.
871       // "X && 0" would have been constant folded to 0.
872       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
873           ConstantBool) {
874         // br(X && 1) -> br(X).
875         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
876       }
877 
878       // Emit the LHS as a conditional.  If the LHS conditional is false, we
879       // want to jump to the FalseBlock.
880       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
881 
882       ConditionalEvaluation eval(*this);
883       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
884       EmitBlock(LHSTrue);
885 
886       // Any temporaries created here are conditional.
887       eval.begin(*this);
888       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
889       eval.end(*this);
890 
891       return;
892     }
893 
894     if (CondBOp->getOpcode() == BO_LOr) {
895       // If we have "0 || X", simplify the code.  "1 || X" would have constant
896       // folded if the case was simple enough.
897       bool ConstantBool = false;
898       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
899           !ConstantBool) {
900         // br(0 || X) -> br(X).
901         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
902       }
903 
904       // If we have "X || 0", simplify the code to use an uncond branch.
905       // "X || 1" would have been constant folded to 1.
906       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
907           !ConstantBool) {
908         // br(X || 0) -> br(X).
909         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
910       }
911 
912       // Emit the LHS as a conditional.  If the LHS conditional is true, we
913       // want to jump to the TrueBlock.
914       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
915 
916       ConditionalEvaluation eval(*this);
917       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
918       EmitBlock(LHSFalse);
919 
920       // Any temporaries created here are conditional.
921       eval.begin(*this);
922       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
923       eval.end(*this);
924 
925       return;
926     }
927   }
928 
929   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
930     // br(!x, t, f) -> br(x, f, t)
931     if (CondUOp->getOpcode() == UO_LNot)
932       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
933   }
934 
935   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
936     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
937     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
938     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
939 
940     ConditionalEvaluation cond(*this);
941     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
942 
943     cond.begin(*this);
944     EmitBlock(LHSBlock);
945     EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
946     cond.end(*this);
947 
948     cond.begin(*this);
949     EmitBlock(RHSBlock);
950     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
951     cond.end(*this);
952 
953     return;
954   }
955 
956   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
957     // Conditional operator handling can give us a throw expression as a
958     // condition for a case like:
959     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
960     // Fold this to:
961     //   br(c, throw x, br(y, t, f))
962     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
963     return;
964   }
965 
966   // Emit the code with the fully general case.
967   llvm::Value *CondV = EvaluateExprAsBool(Cond);
968   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
969 }
970 
971 /// ErrorUnsupported - Print out an error that codegen doesn't support the
972 /// specified stmt yet.
973 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
974   CGM.ErrorUnsupported(S, Type);
975 }
976 
977 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
978 /// variable-length array whose elements have a non-zero bit-pattern.
979 ///
980 /// \param baseType the inner-most element type of the array
981 /// \param src - a char* pointing to the bit-pattern for a single
982 /// base element of the array
983 /// \param sizeInChars - the total size of the VLA, in chars
984 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
985                                llvm::Value *dest, llvm::Value *src,
986                                llvm::Value *sizeInChars) {
987   std::pair<CharUnits,CharUnits> baseSizeAndAlign
988     = CGF.getContext().getTypeInfoInChars(baseType);
989 
990   CGBuilderTy &Builder = CGF.Builder;
991 
992   llvm::Value *baseSizeInChars
993     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
994 
995   llvm::Type *i8p = Builder.getInt8PtrTy();
996 
997   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
998   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
999 
1000   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1001   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1002   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1003 
1004   // Make a loop over the VLA.  C99 guarantees that the VLA element
1005   // count must be nonzero.
1006   CGF.EmitBlock(loopBB);
1007 
1008   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1009   cur->addIncoming(begin, originBB);
1010 
1011   // memcpy the individual element bit-pattern.
1012   Builder.CreateMemCpy(cur, src, baseSizeInChars,
1013                        baseSizeAndAlign.second.getQuantity(),
1014                        /*volatile*/ false);
1015 
1016   // Go to the next element.
1017   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1018 
1019   // Leave if that's the end of the VLA.
1020   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1021   Builder.CreateCondBr(done, contBB, loopBB);
1022   cur->addIncoming(next, loopBB);
1023 
1024   CGF.EmitBlock(contBB);
1025 }
1026 
1027 void
1028 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1029   // Ignore empty classes in C++.
1030   if (getLangOpts().CPlusPlus) {
1031     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1032       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1033         return;
1034     }
1035   }
1036 
1037   // Cast the dest ptr to the appropriate i8 pointer type.
1038   unsigned DestAS =
1039     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1040   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1041   if (DestPtr->getType() != BP)
1042     DestPtr = Builder.CreateBitCast(DestPtr, BP);
1043 
1044   // Get size and alignment info for this aggregate.
1045   std::pair<CharUnits, CharUnits> TypeInfo =
1046     getContext().getTypeInfoInChars(Ty);
1047   CharUnits Size = TypeInfo.first;
1048   CharUnits Align = TypeInfo.second;
1049 
1050   llvm::Value *SizeVal;
1051   const VariableArrayType *vla;
1052 
1053   // Don't bother emitting a zero-byte memset.
1054   if (Size.isZero()) {
1055     // But note that getTypeInfo returns 0 for a VLA.
1056     if (const VariableArrayType *vlaType =
1057           dyn_cast_or_null<VariableArrayType>(
1058                                           getContext().getAsArrayType(Ty))) {
1059       QualType eltType;
1060       llvm::Value *numElts;
1061       llvm::tie(numElts, eltType) = getVLASize(vlaType);
1062 
1063       SizeVal = numElts;
1064       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1065       if (!eltSize.isOne())
1066         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1067       vla = vlaType;
1068     } else {
1069       return;
1070     }
1071   } else {
1072     SizeVal = CGM.getSize(Size);
1073     vla = 0;
1074   }
1075 
1076   // If the type contains a pointer to data member we can't memset it to zero.
1077   // Instead, create a null constant and copy it to the destination.
1078   // TODO: there are other patterns besides zero that we can usefully memset,
1079   // like -1, which happens to be the pattern used by member-pointers.
1080   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1081     // For a VLA, emit a single element, then splat that over the VLA.
1082     if (vla) Ty = getContext().getBaseElementType(vla);
1083 
1084     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1085 
1086     llvm::GlobalVariable *NullVariable =
1087       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1088                                /*isConstant=*/true,
1089                                llvm::GlobalVariable::PrivateLinkage,
1090                                NullConstant, Twine());
1091     llvm::Value *SrcPtr =
1092       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1093 
1094     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1095 
1096     // Get and call the appropriate llvm.memcpy overload.
1097     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1098     return;
1099   }
1100 
1101   // Otherwise, just memset the whole thing to zero.  This is legal
1102   // because in LLVM, all default initializers (other than the ones we just
1103   // handled above) are guaranteed to have a bit pattern of all zeros.
1104   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1105                        Align.getQuantity(), false);
1106 }
1107 
1108 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1109   // Make sure that there is a block for the indirect goto.
1110   if (IndirectBranch == 0)
1111     GetIndirectGotoBlock();
1112 
1113   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1114 
1115   // Make sure the indirect branch includes all of the address-taken blocks.
1116   IndirectBranch->addDestination(BB);
1117   return llvm::BlockAddress::get(CurFn, BB);
1118 }
1119 
1120 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1121   // If we already made the indirect branch for indirect goto, return its block.
1122   if (IndirectBranch) return IndirectBranch->getParent();
1123 
1124   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1125 
1126   // Create the PHI node that indirect gotos will add entries to.
1127   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1128                                               "indirect.goto.dest");
1129 
1130   // Create the indirect branch instruction.
1131   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1132   return IndirectBranch->getParent();
1133 }
1134 
1135 /// Computes the length of an array in elements, as well as the base
1136 /// element type and a properly-typed first element pointer.
1137 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1138                                               QualType &baseType,
1139                                               llvm::Value *&addr) {
1140   const ArrayType *arrayType = origArrayType;
1141 
1142   // If it's a VLA, we have to load the stored size.  Note that
1143   // this is the size of the VLA in bytes, not its size in elements.
1144   llvm::Value *numVLAElements = 0;
1145   if (isa<VariableArrayType>(arrayType)) {
1146     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1147 
1148     // Walk into all VLAs.  This doesn't require changes to addr,
1149     // which has type T* where T is the first non-VLA element type.
1150     do {
1151       QualType elementType = arrayType->getElementType();
1152       arrayType = getContext().getAsArrayType(elementType);
1153 
1154       // If we only have VLA components, 'addr' requires no adjustment.
1155       if (!arrayType) {
1156         baseType = elementType;
1157         return numVLAElements;
1158       }
1159     } while (isa<VariableArrayType>(arrayType));
1160 
1161     // We get out here only if we find a constant array type
1162     // inside the VLA.
1163   }
1164 
1165   // We have some number of constant-length arrays, so addr should
1166   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1167   // down to the first element of addr.
1168   SmallVector<llvm::Value*, 8> gepIndices;
1169 
1170   // GEP down to the array type.
1171   llvm::ConstantInt *zero = Builder.getInt32(0);
1172   gepIndices.push_back(zero);
1173 
1174   uint64_t countFromCLAs = 1;
1175   QualType eltType;
1176 
1177   llvm::ArrayType *llvmArrayType =
1178     dyn_cast<llvm::ArrayType>(
1179       cast<llvm::PointerType>(addr->getType())->getElementType());
1180   while (llvmArrayType) {
1181     assert(isa<ConstantArrayType>(arrayType));
1182     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1183              == llvmArrayType->getNumElements());
1184 
1185     gepIndices.push_back(zero);
1186     countFromCLAs *= llvmArrayType->getNumElements();
1187     eltType = arrayType->getElementType();
1188 
1189     llvmArrayType =
1190       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1191     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1192     assert((!llvmArrayType || arrayType) &&
1193            "LLVM and Clang types are out-of-synch");
1194   }
1195 
1196   if (arrayType) {
1197     // From this point onwards, the Clang array type has been emitted
1198     // as some other type (probably a packed struct). Compute the array
1199     // size, and just emit the 'begin' expression as a bitcast.
1200     while (arrayType) {
1201       countFromCLAs *=
1202           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1203       eltType = arrayType->getElementType();
1204       arrayType = getContext().getAsArrayType(eltType);
1205     }
1206 
1207     unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1208     llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1209     addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1210   } else {
1211     // Create the actual GEP.
1212     addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1213   }
1214 
1215   baseType = eltType;
1216 
1217   llvm::Value *numElements
1218     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1219 
1220   // If we had any VLA dimensions, factor them in.
1221   if (numVLAElements)
1222     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1223 
1224   return numElements;
1225 }
1226 
1227 std::pair<llvm::Value*, QualType>
1228 CodeGenFunction::getVLASize(QualType type) {
1229   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1230   assert(vla && "type was not a variable array type!");
1231   return getVLASize(vla);
1232 }
1233 
1234 std::pair<llvm::Value*, QualType>
1235 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1236   // The number of elements so far; always size_t.
1237   llvm::Value *numElements = 0;
1238 
1239   QualType elementType;
1240   do {
1241     elementType = type->getElementType();
1242     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1243     assert(vlaSize && "no size for VLA!");
1244     assert(vlaSize->getType() == SizeTy);
1245 
1246     if (!numElements) {
1247       numElements = vlaSize;
1248     } else {
1249       // It's undefined behavior if this wraps around, so mark it that way.
1250       // FIXME: Teach -fcatch-undefined-behavior to trap this.
1251       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1252     }
1253   } while ((type = getContext().getAsVariableArrayType(elementType)));
1254 
1255   return std::pair<llvm::Value*,QualType>(numElements, elementType);
1256 }
1257 
1258 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1259   assert(type->isVariablyModifiedType() &&
1260          "Must pass variably modified type to EmitVLASizes!");
1261 
1262   EnsureInsertPoint();
1263 
1264   // We're going to walk down into the type and look for VLA
1265   // expressions.
1266   do {
1267     assert(type->isVariablyModifiedType());
1268 
1269     const Type *ty = type.getTypePtr();
1270     switch (ty->getTypeClass()) {
1271 
1272 #define TYPE(Class, Base)
1273 #define ABSTRACT_TYPE(Class, Base)
1274 #define NON_CANONICAL_TYPE(Class, Base)
1275 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1276 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1277 #include "clang/AST/TypeNodes.def"
1278       llvm_unreachable("unexpected dependent type!");
1279 
1280     // These types are never variably-modified.
1281     case Type::Builtin:
1282     case Type::Complex:
1283     case Type::Vector:
1284     case Type::ExtVector:
1285     case Type::Record:
1286     case Type::Enum:
1287     case Type::Elaborated:
1288     case Type::TemplateSpecialization:
1289     case Type::ObjCObject:
1290     case Type::ObjCInterface:
1291     case Type::ObjCObjectPointer:
1292       llvm_unreachable("type class is never variably-modified!");
1293 
1294     case Type::Decayed:
1295       type = cast<DecayedType>(ty)->getPointeeType();
1296       break;
1297 
1298     case Type::Pointer:
1299       type = cast<PointerType>(ty)->getPointeeType();
1300       break;
1301 
1302     case Type::BlockPointer:
1303       type = cast<BlockPointerType>(ty)->getPointeeType();
1304       break;
1305 
1306     case Type::LValueReference:
1307     case Type::RValueReference:
1308       type = cast<ReferenceType>(ty)->getPointeeType();
1309       break;
1310 
1311     case Type::MemberPointer:
1312       type = cast<MemberPointerType>(ty)->getPointeeType();
1313       break;
1314 
1315     case Type::ConstantArray:
1316     case Type::IncompleteArray:
1317       // Losing element qualification here is fine.
1318       type = cast<ArrayType>(ty)->getElementType();
1319       break;
1320 
1321     case Type::VariableArray: {
1322       // Losing element qualification here is fine.
1323       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1324 
1325       // Unknown size indication requires no size computation.
1326       // Otherwise, evaluate and record it.
1327       if (const Expr *size = vat->getSizeExpr()) {
1328         // It's possible that we might have emitted this already,
1329         // e.g. with a typedef and a pointer to it.
1330         llvm::Value *&entry = VLASizeMap[size];
1331         if (!entry) {
1332           llvm::Value *Size = EmitScalarExpr(size);
1333 
1334           // C11 6.7.6.2p5:
1335           //   If the size is an expression that is not an integer constant
1336           //   expression [...] each time it is evaluated it shall have a value
1337           //   greater than zero.
1338           if (SanOpts->VLABound &&
1339               size->getType()->isSignedIntegerType()) {
1340             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1341             llvm::Constant *StaticArgs[] = {
1342               EmitCheckSourceLocation(size->getLocStart()),
1343               EmitCheckTypeDescriptor(size->getType())
1344             };
1345             EmitCheck(Builder.CreateICmpSGT(Size, Zero),
1346                       "vla_bound_not_positive", StaticArgs, Size,
1347                       CRK_Recoverable);
1348           }
1349 
1350           // Always zexting here would be wrong if it weren't
1351           // undefined behavior to have a negative bound.
1352           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1353         }
1354       }
1355       type = vat->getElementType();
1356       break;
1357     }
1358 
1359     case Type::FunctionProto:
1360     case Type::FunctionNoProto:
1361       type = cast<FunctionType>(ty)->getResultType();
1362       break;
1363 
1364     case Type::Paren:
1365     case Type::TypeOf:
1366     case Type::UnaryTransform:
1367     case Type::Attributed:
1368     case Type::SubstTemplateTypeParm:
1369     case Type::PackExpansion:
1370       // Keep walking after single level desugaring.
1371       type = type.getSingleStepDesugaredType(getContext());
1372       break;
1373 
1374     case Type::Typedef:
1375     case Type::Decltype:
1376     case Type::Auto:
1377       // Stop walking: nothing to do.
1378       return;
1379 
1380     case Type::TypeOfExpr:
1381       // Stop walking: emit typeof expression.
1382       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1383       return;
1384 
1385     case Type::Atomic:
1386       type = cast<AtomicType>(ty)->getValueType();
1387       break;
1388     }
1389   } while (type->isVariablyModifiedType());
1390 }
1391 
1392 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
1393   if (getContext().getBuiltinVaListType()->isArrayType())
1394     return EmitScalarExpr(E);
1395   return EmitLValue(E).getAddress();
1396 }
1397 
1398 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1399                                               llvm::Constant *Init) {
1400   assert (Init && "Invalid DeclRefExpr initializer!");
1401   if (CGDebugInfo *Dbg = getDebugInfo())
1402     if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1403       Dbg->EmitGlobalVariable(E->getDecl(), Init);
1404 }
1405 
1406 CodeGenFunction::PeepholeProtection
1407 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1408   // At the moment, the only aggressive peephole we do in IR gen
1409   // is trunc(zext) folding, but if we add more, we can easily
1410   // extend this protection.
1411 
1412   if (!rvalue.isScalar()) return PeepholeProtection();
1413   llvm::Value *value = rvalue.getScalarVal();
1414   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1415 
1416   // Just make an extra bitcast.
1417   assert(HaveInsertPoint());
1418   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1419                                                   Builder.GetInsertBlock());
1420 
1421   PeepholeProtection protection;
1422   protection.Inst = inst;
1423   return protection;
1424 }
1425 
1426 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1427   if (!protection.Inst) return;
1428 
1429   // In theory, we could try to duplicate the peepholes now, but whatever.
1430   protection.Inst->eraseFromParent();
1431 }
1432 
1433 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1434                                                  llvm::Value *AnnotatedVal,
1435                                                  StringRef AnnotationStr,
1436                                                  SourceLocation Location) {
1437   llvm::Value *Args[4] = {
1438     AnnotatedVal,
1439     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1440     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1441     CGM.EmitAnnotationLineNo(Location)
1442   };
1443   return Builder.CreateCall(AnnotationFn, Args);
1444 }
1445 
1446 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1447   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1448   // FIXME We create a new bitcast for every annotation because that's what
1449   // llvm-gcc was doing.
1450   for (specific_attr_iterator<AnnotateAttr>
1451        ai = D->specific_attr_begin<AnnotateAttr>(),
1452        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1453     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1454                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1455                        (*ai)->getAnnotation(), D->getLocation());
1456 }
1457 
1458 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1459                                                    llvm::Value *V) {
1460   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1461   llvm::Type *VTy = V->getType();
1462   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1463                                     CGM.Int8PtrTy);
1464 
1465   for (specific_attr_iterator<AnnotateAttr>
1466        ai = D->specific_attr_begin<AnnotateAttr>(),
1467        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
1468     // FIXME Always emit the cast inst so we can differentiate between
1469     // annotation on the first field of a struct and annotation on the struct
1470     // itself.
1471     if (VTy != CGM.Int8PtrTy)
1472       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1473     V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
1474     V = Builder.CreateBitCast(V, VTy);
1475   }
1476 
1477   return V;
1478 }
1479 
1480 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1481