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