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