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