1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This coordinates the per-function state used while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CGBlocks.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenPGO.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/ASTLambda.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/Decl.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/CodeGenOptions.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/CodeGen/CGFunctionInfo.h"
34 #include "clang/Frontend/FrontendDiagnostic.h"
35 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/FPEnv.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Operator.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
44 using namespace clang;
45 using namespace CodeGen;
46 
47 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
48 /// markers.
49 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
50                                       const LangOptions &LangOpts) {
51   if (CGOpts.DisableLifetimeMarkers)
52     return false;
53 
54   // Sanitizers may use markers.
55   if (CGOpts.SanitizeAddressUseAfterScope ||
56       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
57       LangOpts.Sanitize.has(SanitizerKind::Memory))
58     return true;
59 
60   // For now, only in optimized builds.
61   return CGOpts.OptimizationLevel != 0;
62 }
63 
64 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
65     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
66       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
67               CGBuilderInserterTy(this)),
68       SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
69       PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
70                     CGM.getCodeGenOpts(), CGM.getLangOpts())) {
71   if (!suppressNewContext)
72     CGM.getCXXABI().getMangleContext().startNewFunction();
73 
74   llvm::FastMathFlags FMF;
75   if (CGM.getLangOpts().FastMath)
76     FMF.setFast();
77   if (CGM.getLangOpts().FiniteMathOnly) {
78     FMF.setNoNaNs();
79     FMF.setNoInfs();
80   }
81   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
82     FMF.setNoNaNs();
83   }
84   if (CGM.getCodeGenOpts().NoSignedZeros) {
85     FMF.setNoSignedZeros();
86   }
87   if (CGM.getCodeGenOpts().ReciprocalMath) {
88     FMF.setAllowReciprocal();
89   }
90   if (CGM.getCodeGenOpts().Reassociate) {
91     FMF.setAllowReassoc();
92   }
93   Builder.setFastMathFlags(FMF);
94   SetFPModel();
95 }
96 
97 CodeGenFunction::~CodeGenFunction() {
98   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
99 
100   // If there are any unclaimed block infos, go ahead and destroy them
101   // now.  This can happen if IR-gen gets clever and skips evaluating
102   // something.
103   if (FirstBlockInfo)
104     destroyBlockInfos(FirstBlockInfo);
105 
106   if (getLangOpts().OpenMP && CurFn)
107     CGM.getOpenMPRuntime().functionFinished(*this);
108 
109   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
110   // outlining etc) at some point. Doing it once the function codegen is done
111   // seems to be a reasonable spot. We do it here, as opposed to the deletion
112   // time of the CodeGenModule, because we have to ensure the IR has not yet
113   // been "emitted" to the outside, thus, modifications are still sensible.
114   if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder())
115     OMPBuilder->finalize();
116 }
117 
118 // Map the LangOption for exception behavior into
119 // the corresponding enum in the IR.
120 llvm::fp::ExceptionBehavior
121 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
122 
123   switch (Kind) {
124   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
125   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
126   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
127   }
128   llvm_unreachable("Unsupported FP Exception Behavior");
129 }
130 
131 void CodeGenFunction::SetFPModel() {
132   llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
133   auto fpExceptionBehavior = ToConstrainedExceptMD(
134                                getLangOpts().getFPExceptionMode());
135 
136   Builder.setDefaultConstrainedRounding(RM);
137   Builder.setDefaultConstrainedExcept(fpExceptionBehavior);
138   Builder.setIsFPConstrained(fpExceptionBehavior != llvm::fp::ebIgnore ||
139                              RM != llvm::RoundingMode::NearestTiesToEven);
140 }
141 
142 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
143   LValueBaseInfo BaseInfo;
144   TBAAAccessInfo TBAAInfo;
145   CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
146   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
147                           TBAAInfo);
148 }
149 
150 /// Given a value of type T* that may not be to a complete object,
151 /// construct an l-value with the natural pointee alignment of T.
152 LValue
153 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
154   LValueBaseInfo BaseInfo;
155   TBAAAccessInfo TBAAInfo;
156   CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
157                                                 /* forPointeeType= */ true);
158   return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
159 }
160 
161 
162 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
163   return CGM.getTypes().ConvertTypeForMem(T);
164 }
165 
166 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
167   return CGM.getTypes().ConvertType(T);
168 }
169 
170 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
171   type = type.getCanonicalType();
172   while (true) {
173     switch (type->getTypeClass()) {
174 #define TYPE(name, parent)
175 #define ABSTRACT_TYPE(name, parent)
176 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
177 #define DEPENDENT_TYPE(name, parent) case Type::name:
178 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
179 #include "clang/AST/TypeNodes.inc"
180       llvm_unreachable("non-canonical or dependent type in IR-generation");
181 
182     case Type::Auto:
183     case Type::DeducedTemplateSpecialization:
184       llvm_unreachable("undeduced type in IR-generation");
185 
186     // Various scalar types.
187     case Type::Builtin:
188     case Type::Pointer:
189     case Type::BlockPointer:
190     case Type::LValueReference:
191     case Type::RValueReference:
192     case Type::MemberPointer:
193     case Type::Vector:
194     case Type::ExtVector:
195     case Type::ConstantMatrix:
196     case Type::FunctionProto:
197     case Type::FunctionNoProto:
198     case Type::Enum:
199     case Type::ObjCObjectPointer:
200     case Type::Pipe:
201     case Type::ExtInt:
202       return TEK_Scalar;
203 
204     // Complexes.
205     case Type::Complex:
206       return TEK_Complex;
207 
208     // Arrays, records, and Objective-C objects.
209     case Type::ConstantArray:
210     case Type::IncompleteArray:
211     case Type::VariableArray:
212     case Type::Record:
213     case Type::ObjCObject:
214     case Type::ObjCInterface:
215       return TEK_Aggregate;
216 
217     // We operate on atomic values according to their underlying type.
218     case Type::Atomic:
219       type = cast<AtomicType>(type)->getValueType();
220       continue;
221     }
222     llvm_unreachable("unknown type kind!");
223   }
224 }
225 
226 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
227   // For cleanliness, we try to avoid emitting the return block for
228   // simple cases.
229   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
230 
231   if (CurBB) {
232     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
233 
234     // We have a valid insert point, reuse it if it is empty or there are no
235     // explicit jumps to the return block.
236     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
237       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
238       delete ReturnBlock.getBlock();
239       ReturnBlock = JumpDest();
240     } else
241       EmitBlock(ReturnBlock.getBlock());
242     return llvm::DebugLoc();
243   }
244 
245   // Otherwise, if the return block is the target of a single direct
246   // branch then we can just put the code in that block instead. This
247   // cleans up functions which started with a unified return block.
248   if (ReturnBlock.getBlock()->hasOneUse()) {
249     llvm::BranchInst *BI =
250       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
251     if (BI && BI->isUnconditional() &&
252         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
253       // Record/return the DebugLoc of the simple 'return' expression to be used
254       // later by the actual 'ret' instruction.
255       llvm::DebugLoc Loc = BI->getDebugLoc();
256       Builder.SetInsertPoint(BI->getParent());
257       BI->eraseFromParent();
258       delete ReturnBlock.getBlock();
259       ReturnBlock = JumpDest();
260       return Loc;
261     }
262   }
263 
264   // FIXME: We are at an unreachable point, there is no reason to emit the block
265   // unless it has uses. However, we still need a place to put the debug
266   // region.end for now.
267 
268   EmitBlock(ReturnBlock.getBlock());
269   return llvm::DebugLoc();
270 }
271 
272 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
273   if (!BB) return;
274   if (!BB->use_empty())
275     return CGF.CurFn->getBasicBlockList().push_back(BB);
276   delete BB;
277 }
278 
279 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
280   assert(BreakContinueStack.empty() &&
281          "mismatched push/pop in break/continue stack!");
282 
283   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
284     && NumSimpleReturnExprs == NumReturnExprs
285     && ReturnBlock.getBlock()->use_empty();
286   // Usually the return expression is evaluated before the cleanup
287   // code.  If the function contains only a simple return statement,
288   // such as a constant, the location before the cleanup code becomes
289   // the last useful breakpoint in the function, because the simple
290   // return expression will be evaluated after the cleanup code. To be
291   // safe, set the debug location for cleanup code to the location of
292   // the return statement.  Otherwise the cleanup code should be at the
293   // end of the function's lexical scope.
294   //
295   // If there are multiple branches to the return block, the branch
296   // instructions will get the location of the return statements and
297   // all will be fine.
298   if (CGDebugInfo *DI = getDebugInfo()) {
299     if (OnlySimpleReturnStmts)
300       DI->EmitLocation(Builder, LastStopPoint);
301     else
302       DI->EmitLocation(Builder, EndLoc);
303   }
304 
305   // Pop any cleanups that might have been associated with the
306   // parameters.  Do this in whatever block we're currently in; it's
307   // important to do this before we enter the return block or return
308   // edges will be *really* confused.
309   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
310   bool HasOnlyLifetimeMarkers =
311       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
312   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
313   if (HasCleanups) {
314     // Make sure the line table doesn't jump back into the body for
315     // the ret after it's been at EndLoc.
316     Optional<ApplyDebugLocation> AL;
317     if (CGDebugInfo *DI = getDebugInfo()) {
318       if (OnlySimpleReturnStmts)
319         DI->EmitLocation(Builder, EndLoc);
320       else
321         // We may not have a valid end location. Try to apply it anyway, and
322         // fall back to an artificial location if needed.
323         AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
324     }
325 
326     PopCleanupBlocks(PrologueCleanupDepth);
327   }
328 
329   // Emit function epilog (to return).
330   llvm::DebugLoc Loc = EmitReturnBlock();
331 
332   if (ShouldInstrumentFunction()) {
333     if (CGM.getCodeGenOpts().InstrumentFunctions)
334       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
335     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
336       CurFn->addFnAttr("instrument-function-exit-inlined",
337                        "__cyg_profile_func_exit");
338   }
339 
340   // Emit debug descriptor for function end.
341   if (CGDebugInfo *DI = getDebugInfo())
342     DI->EmitFunctionEnd(Builder, CurFn);
343 
344   // Reset the debug location to that of the simple 'return' expression, if any
345   // rather than that of the end of the function's scope '}'.
346   ApplyDebugLocation AL(*this, Loc);
347   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
348   EmitEndEHSpec(CurCodeDecl);
349 
350   assert(EHStack.empty() &&
351          "did not remove all scopes from cleanup stack!");
352 
353   // If someone did an indirect goto, emit the indirect goto block at the end of
354   // the function.
355   if (IndirectBranch) {
356     EmitBlock(IndirectBranch->getParent());
357     Builder.ClearInsertionPoint();
358   }
359 
360   // If some of our locals escaped, insert a call to llvm.localescape in the
361   // entry block.
362   if (!EscapedLocals.empty()) {
363     // Invert the map from local to index into a simple vector. There should be
364     // no holes.
365     SmallVector<llvm::Value *, 4> EscapeArgs;
366     EscapeArgs.resize(EscapedLocals.size());
367     for (auto &Pair : EscapedLocals)
368       EscapeArgs[Pair.second] = Pair.first;
369     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
370         &CGM.getModule(), llvm::Intrinsic::localescape);
371     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
372   }
373 
374   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
375   llvm::Instruction *Ptr = AllocaInsertPt;
376   AllocaInsertPt = nullptr;
377   Ptr->eraseFromParent();
378 
379   // If someone took the address of a label but never did an indirect goto, we
380   // made a zero entry PHI node, which is illegal, zap it now.
381   if (IndirectBranch) {
382     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
383     if (PN->getNumIncomingValues() == 0) {
384       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
385       PN->eraseFromParent();
386     }
387   }
388 
389   EmitIfUsed(*this, EHResumeBlock);
390   EmitIfUsed(*this, TerminateLandingPad);
391   EmitIfUsed(*this, TerminateHandler);
392   EmitIfUsed(*this, UnreachableBlock);
393 
394   for (const auto &FuncletAndParent : TerminateFunclets)
395     EmitIfUsed(*this, FuncletAndParent.second);
396 
397   if (CGM.getCodeGenOpts().EmitDeclMetadata)
398     EmitDeclMetadata();
399 
400   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
401            I = DeferredReplacements.begin(),
402            E = DeferredReplacements.end();
403        I != E; ++I) {
404     I->first->replaceAllUsesWith(I->second);
405     I->first->eraseFromParent();
406   }
407 
408   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
409   // PHIs if the current function is a coroutine. We don't do it for all
410   // functions as it may result in slight increase in numbers of instructions
411   // if compiled with no optimizations. We do it for coroutine as the lifetime
412   // of CleanupDestSlot alloca make correct coroutine frame building very
413   // difficult.
414   if (NormalCleanupDest.isValid() && isCoroutine()) {
415     llvm::DominatorTree DT(*CurFn);
416     llvm::PromoteMemToReg(
417         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
418     NormalCleanupDest = Address::invalid();
419   }
420 
421   // Scan function arguments for vector width.
422   for (llvm::Argument &A : CurFn->args())
423     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
424       LargestVectorWidth =
425           std::max((uint64_t)LargestVectorWidth,
426                    VT->getPrimitiveSizeInBits().getKnownMinSize());
427 
428   // Update vector width based on return type.
429   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
430     LargestVectorWidth =
431         std::max((uint64_t)LargestVectorWidth,
432                  VT->getPrimitiveSizeInBits().getKnownMinSize());
433 
434   // Add the required-vector-width attribute. This contains the max width from:
435   // 1. min-vector-width attribute used in the source program.
436   // 2. Any builtins used that have a vector width specified.
437   // 3. Values passed in and out of inline assembly.
438   // 4. Width of vector arguments and return types for this function.
439   // 5. Width of vector aguments and return types for functions called by this
440   //    function.
441   CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
442 
443   // If we generated an unreachable return block, delete it now.
444   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
445     Builder.ClearInsertionPoint();
446     ReturnBlock.getBlock()->eraseFromParent();
447   }
448   if (ReturnValue.isValid()) {
449     auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
450     if (RetAlloca && RetAlloca->use_empty()) {
451       RetAlloca->eraseFromParent();
452       ReturnValue = Address::invalid();
453     }
454   }
455 }
456 
457 /// ShouldInstrumentFunction - Return true if the current function should be
458 /// instrumented with __cyg_profile_func_* calls
459 bool CodeGenFunction::ShouldInstrumentFunction() {
460   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
461       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
462       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
463     return false;
464   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
465     return false;
466   return true;
467 }
468 
469 /// ShouldXRayInstrument - Return true if the current function should be
470 /// instrumented with XRay nop sleds.
471 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
472   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
473 }
474 
475 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
476 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
477 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
478   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
479          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
480           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
481               XRayInstrKind::Custom);
482 }
483 
484 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
485   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
486          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
487           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
488               XRayInstrKind::Typed);
489 }
490 
491 llvm::Constant *
492 CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
493                                             llvm::Constant *Addr) {
494   // Addresses stored in prologue data can't require run-time fixups and must
495   // be PC-relative. Run-time fixups are undesirable because they necessitate
496   // writable text segments, which are unsafe. And absolute addresses are
497   // undesirable because they break PIE mode.
498 
499   // Add a layer of indirection through a private global. Taking its address
500   // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
501   auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
502                                       /*isConstant=*/true,
503                                       llvm::GlobalValue::PrivateLinkage, Addr);
504 
505   // Create a PC-relative address.
506   auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
507   auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
508   auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
509   return (IntPtrTy == Int32Ty)
510              ? PCRelAsInt
511              : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
512 }
513 
514 llvm::Value *
515 CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
516                                           llvm::Value *EncodedAddr) {
517   // Reconstruct the address of the global.
518   auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
519   auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
520   auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
521   auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
522 
523   // Load the original pointer through the global.
524   return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
525                             "decoded_addr");
526 }
527 
528 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
529                                                llvm::Function *Fn)
530 {
531   if (!FD->hasAttr<OpenCLKernelAttr>())
532     return;
533 
534   llvm::LLVMContext &Context = getLLVMContext();
535 
536   CGM.GenOpenCLArgMetadata(Fn, FD, this);
537 
538   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
539     QualType HintQTy = A->getTypeHint();
540     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
541     bool IsSignedInteger =
542         HintQTy->isSignedIntegerType() ||
543         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
544     llvm::Metadata *AttrMDArgs[] = {
545         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
546             CGM.getTypes().ConvertType(A->getTypeHint()))),
547         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
548             llvm::IntegerType::get(Context, 32),
549             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
550     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
551   }
552 
553   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
554     llvm::Metadata *AttrMDArgs[] = {
555         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
556         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
557         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
558     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
559   }
560 
561   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
562     llvm::Metadata *AttrMDArgs[] = {
563         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
564         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
565         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
566     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
567   }
568 
569   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
570           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
571     llvm::Metadata *AttrMDArgs[] = {
572         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
573     Fn->setMetadata("intel_reqd_sub_group_size",
574                     llvm::MDNode::get(Context, AttrMDArgs));
575   }
576 }
577 
578 /// Determine whether the function F ends with a return stmt.
579 static bool endsWithReturn(const Decl* F) {
580   const Stmt *Body = nullptr;
581   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
582     Body = FD->getBody();
583   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
584     Body = OMD->getBody();
585 
586   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
587     auto LastStmt = CS->body_rbegin();
588     if (LastStmt != CS->body_rend())
589       return isa<ReturnStmt>(*LastStmt);
590   }
591   return false;
592 }
593 
594 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
595   if (SanOpts.has(SanitizerKind::Thread)) {
596     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
597     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
598   }
599 }
600 
601 /// Check if the return value of this function requires sanitization.
602 bool CodeGenFunction::requiresReturnValueCheck() const {
603   return requiresReturnValueNullabilityCheck() ||
604          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
605           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
606 }
607 
608 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
609   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
610   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
611       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
612       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
613     return false;
614 
615   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
616     return false;
617 
618   if (MD->getNumParams() == 2) {
619     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
620     if (!PT || !PT->isVoidPointerType() ||
621         !PT->getPointeeType().isConstQualified())
622       return false;
623   }
624 
625   return true;
626 }
627 
628 /// Return the UBSan prologue signature for \p FD if one is available.
629 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
630                                             const FunctionDecl *FD) {
631   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
632     if (!MD->isStatic())
633       return nullptr;
634   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
635 }
636 
637 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
638                                     llvm::Function *Fn,
639                                     const CGFunctionInfo &FnInfo,
640                                     const FunctionArgList &Args,
641                                     SourceLocation Loc,
642                                     SourceLocation StartLoc) {
643   assert(!CurFn &&
644          "Do not use a CodeGenFunction object for more than one function");
645 
646   const Decl *D = GD.getDecl();
647 
648   DidCallStackSave = false;
649   CurCodeDecl = D;
650   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
651     if (FD->usesSEHTry())
652       CurSEHParent = FD;
653   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
654   FnRetTy = RetTy;
655   CurFn = Fn;
656   CurFnInfo = &FnInfo;
657   assert(CurFn->isDeclaration() && "Function already has body?");
658 
659   // If this function has been blacklisted for any of the enabled sanitizers,
660   // disable the sanitizer for the function.
661   do {
662 #define SANITIZER(NAME, ID)                                                    \
663   if (SanOpts.empty())                                                         \
664     break;                                                                     \
665   if (SanOpts.has(SanitizerKind::ID))                                          \
666     if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc))                \
667       SanOpts.set(SanitizerKind::ID, false);
668 
669 #include "clang/Basic/Sanitizers.def"
670 #undef SANITIZER
671   } while (0);
672 
673   if (D) {
674     // Apply the no_sanitize* attributes to SanOpts.
675     for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
676       SanitizerMask mask = Attr->getMask();
677       SanOpts.Mask &= ~mask;
678       if (mask & SanitizerKind::Address)
679         SanOpts.set(SanitizerKind::KernelAddress, false);
680       if (mask & SanitizerKind::KernelAddress)
681         SanOpts.set(SanitizerKind::Address, false);
682       if (mask & SanitizerKind::HWAddress)
683         SanOpts.set(SanitizerKind::KernelHWAddress, false);
684       if (mask & SanitizerKind::KernelHWAddress)
685         SanOpts.set(SanitizerKind::HWAddress, false);
686     }
687   }
688 
689   // Apply sanitizer attributes to the function.
690   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
691     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
692   if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
693     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
694   if (SanOpts.has(SanitizerKind::MemTag))
695     Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
696   if (SanOpts.has(SanitizerKind::Thread))
697     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
698   if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
699     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
700   if (SanOpts.has(SanitizerKind::SafeStack))
701     Fn->addFnAttr(llvm::Attribute::SafeStack);
702   if (SanOpts.has(SanitizerKind::ShadowCallStack))
703     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
704 
705   // Apply fuzzing attribute to the function.
706   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
707     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
708 
709   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
710   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
711   if (SanOpts.has(SanitizerKind::Thread)) {
712     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
713       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
714       if (OMD->getMethodFamily() == OMF_dealloc ||
715           OMD->getMethodFamily() == OMF_initialize ||
716           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
717         markAsIgnoreThreadCheckingAtRuntime(Fn);
718       }
719     }
720   }
721 
722   // Ignore unrelated casts in STL allocate() since the allocator must cast
723   // from void* to T* before object initialization completes. Don't match on the
724   // namespace because not all allocators are in std::
725   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
726     if (matchesStlAllocatorFn(D, getContext()))
727       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
728   }
729 
730   // Ignore null checks in coroutine functions since the coroutines passes
731   // are not aware of how to move the extra UBSan instructions across the split
732   // coroutine boundaries.
733   if (D && SanOpts.has(SanitizerKind::Null))
734     if (const auto *FD = dyn_cast<FunctionDecl>(D))
735       if (FD->getBody() &&
736           FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
737         SanOpts.Mask &= ~SanitizerKind::Null;
738 
739   // Apply xray attributes to the function (as a string, for now)
740   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
741     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
742             XRayInstrKind::FunctionEntry) ||
743         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
744             XRayInstrKind::FunctionExit)) {
745       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
746         Fn->addFnAttr("function-instrument", "xray-always");
747       if (XRayAttr->neverXRayInstrument())
748         Fn->addFnAttr("function-instrument", "xray-never");
749       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
750         if (ShouldXRayInstrumentFunction())
751           Fn->addFnAttr("xray-log-args",
752                         llvm::utostr(LogArgs->getArgumentCount()));
753     }
754   } else {
755     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
756       Fn->addFnAttr(
757           "xray-instruction-threshold",
758           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
759   }
760 
761   if (ShouldXRayInstrumentFunction()) {
762     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
763       Fn->addFnAttr("xray-ignore-loops");
764 
765     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
766             XRayInstrKind::FunctionExit))
767       Fn->addFnAttr("xray-skip-exit");
768 
769     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
770             XRayInstrKind::FunctionEntry))
771       Fn->addFnAttr("xray-skip-entry");
772   }
773 
774   unsigned Count, Offset;
775   if (const auto *Attr =
776           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
777     Count = Attr->getCount();
778     Offset = Attr->getOffset();
779   } else {
780     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
781     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
782   }
783   if (Count && Offset <= Count) {
784     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
785     if (Offset)
786       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
787   }
788 
789   // Add no-jump-tables value.
790   Fn->addFnAttr("no-jump-tables",
791                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
792 
793   // Add no-inline-line-tables value.
794   if (CGM.getCodeGenOpts().NoInlineLineTables)
795     Fn->addFnAttr("no-inline-line-tables");
796 
797   // Add profile-sample-accurate value.
798   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
799     Fn->addFnAttr("profile-sample-accurate");
800 
801   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
802     Fn->addFnAttr("cfi-canonical-jump-table");
803 
804   if (getLangOpts().OpenCL) {
805     // Add metadata for a kernel function.
806     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
807       EmitOpenCLKernelMetadata(FD, Fn);
808   }
809 
810   // If we are checking function types, emit a function type signature as
811   // prologue data.
812   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
813     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
814       if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
815         // Remove any (C++17) exception specifications, to allow calling e.g. a
816         // noexcept function through a non-noexcept pointer.
817         auto ProtoTy =
818           getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
819                                                         EST_None);
820         llvm::Constant *FTRTTIConst =
821             CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
822         llvm::Constant *FTRTTIConstEncoded =
823             EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
824         llvm::Constant *PrologueStructElems[] = {PrologueSig,
825                                                  FTRTTIConstEncoded};
826         llvm::Constant *PrologueStructConst =
827             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
828         Fn->setPrologueData(PrologueStructConst);
829       }
830     }
831   }
832 
833   // If we're checking nullability, we need to know whether we can check the
834   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
835   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
836     auto Nullability = FnRetTy->getNullability(getContext());
837     if (Nullability && *Nullability == NullabilityKind::NonNull) {
838       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
839             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
840         RetValNullabilityPrecondition =
841             llvm::ConstantInt::getTrue(getLLVMContext());
842     }
843   }
844 
845   // If we're in C++ mode and the function name is "main", it is guaranteed
846   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
847   // used within a program").
848   //
849   // OpenCL C 2.0 v2.2-11 s6.9.i:
850   //     Recursion is not supported.
851   //
852   // SYCL v1.2.1 s3.10:
853   //     kernels cannot include RTTI information, exception classes,
854   //     recursive code, virtual functions or make use of C++ libraries that
855   //     are not compiled for the device.
856   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
857     if ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
858         getLangOpts().SYCLIsDevice ||
859         (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>()))
860       Fn->addFnAttr(llvm::Attribute::NoRecurse);
861   }
862 
863   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
864     Builder.setIsFPConstrained(FD->usesFPIntrin());
865     if (FD->usesFPIntrin())
866       Fn->addFnAttr(llvm::Attribute::StrictFP);
867   }
868 
869   // If a custom alignment is used, force realigning to this alignment on
870   // any main function which certainly will need it.
871   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
872     if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
873         CGM.getCodeGenOpts().StackAlignment)
874       Fn->addFnAttr("stackrealign");
875 
876   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
877 
878   // Create a marker to make it easy to insert allocas into the entryblock
879   // later.  Don't create this with the builder, because we don't want it
880   // folded.
881   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
882   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
883 
884   ReturnBlock = getJumpDestInCurrentScope("return");
885 
886   Builder.SetInsertPoint(EntryBB);
887 
888   // If we're checking the return value, allocate space for a pointer to a
889   // precise source location of the checked return statement.
890   if (requiresReturnValueCheck()) {
891     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
892     InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
893   }
894 
895   // Emit subprogram debug descriptor.
896   if (CGDebugInfo *DI = getDebugInfo()) {
897     // Reconstruct the type from the argument list so that implicit parameters,
898     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
899     // convention.
900     CallingConv CC = CallingConv::CC_C;
901     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
902       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
903         CC = SrcFnTy->getCallConv();
904     SmallVector<QualType, 16> ArgTypes;
905     for (const VarDecl *VD : Args)
906       ArgTypes.push_back(VD->getType());
907     QualType FnType = getContext().getFunctionType(
908         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
909     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
910                           Builder);
911   }
912 
913   if (ShouldInstrumentFunction()) {
914     if (CGM.getCodeGenOpts().InstrumentFunctions)
915       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
916     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
917       CurFn->addFnAttr("instrument-function-entry-inlined",
918                        "__cyg_profile_func_enter");
919     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
920       CurFn->addFnAttr("instrument-function-entry-inlined",
921                        "__cyg_profile_func_enter_bare");
922   }
923 
924   // Since emitting the mcount call here impacts optimizations such as function
925   // inlining, we just add an attribute to insert a mcount call in backend.
926   // The attribute "counting-function" is set to mcount function name which is
927   // architecture dependent.
928   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
929     // Calls to fentry/mcount should not be generated if function has
930     // the no_instrument_function attribute.
931     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
932       if (CGM.getCodeGenOpts().CallFEntry)
933         Fn->addFnAttr("fentry-call", "true");
934       else {
935         Fn->addFnAttr("instrument-function-entry-inlined",
936                       getTarget().getMCountName());
937       }
938       if (CGM.getCodeGenOpts().MNopMCount) {
939         if (!CGM.getCodeGenOpts().CallFEntry)
940           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
941             << "-mnop-mcount" << "-mfentry";
942         Fn->addFnAttr("mnop-mcount");
943       }
944 
945       if (CGM.getCodeGenOpts().RecordMCount) {
946         if (!CGM.getCodeGenOpts().CallFEntry)
947           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
948             << "-mrecord-mcount" << "-mfentry";
949         Fn->addFnAttr("mrecord-mcount");
950       }
951     }
952   }
953 
954   if (CGM.getCodeGenOpts().PackedStack) {
955     if (getContext().getTargetInfo().getTriple().getArch() !=
956         llvm::Triple::systemz)
957       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
958         << "-mpacked-stack";
959     Fn->addFnAttr("packed-stack");
960   }
961 
962   if (RetTy->isVoidType()) {
963     // Void type; nothing to return.
964     ReturnValue = Address::invalid();
965 
966     // Count the implicit return.
967     if (!endsWithReturn(D))
968       ++NumReturnExprs;
969   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
970     // Indirect return; emit returned value directly into sret slot.
971     // This reduces code size, and affects correctness in C++.
972     auto AI = CurFn->arg_begin();
973     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
974       ++AI;
975     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
976     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
977       ReturnValuePointer =
978           CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
979       Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
980                               ReturnValue.getPointer(), Int8PtrTy),
981                           ReturnValuePointer);
982     }
983   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
984              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
985     // Load the sret pointer from the argument struct and return into that.
986     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
987     llvm::Function::arg_iterator EI = CurFn->arg_end();
988     --EI;
989     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
990     ReturnValuePointer = Address(Addr, getPointerAlign());
991     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
992     ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
993   } else {
994     ReturnValue = CreateIRTemp(RetTy, "retval");
995 
996     // Tell the epilog emitter to autorelease the result.  We do this
997     // now so that various specialized functions can suppress it
998     // during their IR-generation.
999     if (getLangOpts().ObjCAutoRefCount &&
1000         !CurFnInfo->isReturnsRetained() &&
1001         RetTy->isObjCRetainableType())
1002       AutoreleaseResult = true;
1003   }
1004 
1005   EmitStartEHSpec(CurCodeDecl);
1006 
1007   PrologueCleanupDepth = EHStack.stable_begin();
1008 
1009   // Emit OpenMP specific initialization of the device functions.
1010   if (getLangOpts().OpenMP && CurCodeDecl)
1011     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1012 
1013   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1014 
1015   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1016     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1017     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1018     if (MD->getParent()->isLambda() &&
1019         MD->getOverloadedOperator() == OO_Call) {
1020       // We're in a lambda; figure out the captures.
1021       MD->getParent()->getCaptureFields(LambdaCaptureFields,
1022                                         LambdaThisCaptureField);
1023       if (LambdaThisCaptureField) {
1024         // If the lambda captures the object referred to by '*this' - either by
1025         // value or by reference, make sure CXXThisValue points to the correct
1026         // object.
1027 
1028         // Get the lvalue for the field (which is a copy of the enclosing object
1029         // or contains the address of the enclosing object).
1030         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1031         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1032           // If the enclosing object was captured by value, just use its address.
1033           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1034         } else {
1035           // Load the lvalue pointed to by the field, since '*this' was captured
1036           // by reference.
1037           CXXThisValue =
1038               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1039         }
1040       }
1041       for (auto *FD : MD->getParent()->fields()) {
1042         if (FD->hasCapturedVLAType()) {
1043           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1044                                            SourceLocation()).getScalarVal();
1045           auto VAT = FD->getCapturedVLAType();
1046           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1047         }
1048       }
1049     } else {
1050       // Not in a lambda; just use 'this' from the method.
1051       // FIXME: Should we generate a new load for each use of 'this'?  The
1052       // fast register allocator would be happier...
1053       CXXThisValue = CXXABIThisValue;
1054     }
1055 
1056     // Check the 'this' pointer once per function, if it's available.
1057     if (CXXABIThisValue) {
1058       SanitizerSet SkippedChecks;
1059       SkippedChecks.set(SanitizerKind::ObjectSize, true);
1060       QualType ThisTy = MD->getThisType();
1061 
1062       // If this is the call operator of a lambda with no capture-default, it
1063       // may have a static invoker function, which may call this operator with
1064       // a null 'this' pointer.
1065       if (isLambdaCallOperator(MD) &&
1066           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
1067         SkippedChecks.set(SanitizerKind::Null, true);
1068 
1069       EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
1070                                                 : TCK_MemberCall,
1071                     Loc, CXXABIThisValue, ThisTy,
1072                     getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
1073                     SkippedChecks);
1074     }
1075   }
1076 
1077   // If any of the arguments have a variably modified type, make sure to
1078   // emit the type size.
1079   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1080        i != e; ++i) {
1081     const VarDecl *VD = *i;
1082 
1083     // Dig out the type as written from ParmVarDecls; it's unclear whether
1084     // the standard (C99 6.9.1p10) requires this, but we're following the
1085     // precedent set by gcc.
1086     QualType Ty;
1087     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1088       Ty = PVD->getOriginalType();
1089     else
1090       Ty = VD->getType();
1091 
1092     if (Ty->isVariablyModifiedType())
1093       EmitVariablyModifiedType(Ty);
1094   }
1095   // Emit a location at the end of the prologue.
1096   if (CGDebugInfo *DI = getDebugInfo())
1097     DI->EmitLocation(Builder, StartLoc);
1098 
1099   // TODO: Do we need to handle this in two places like we do with
1100   // target-features/target-cpu?
1101   if (CurFuncDecl)
1102     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1103       LargestVectorWidth = VecWidth->getVectorWidth();
1104 }
1105 
1106 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1107   incrementProfileCounter(Body);
1108   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1109     EmitCompoundStmtWithoutScope(*S);
1110   else
1111     EmitStmt(Body);
1112 }
1113 
1114 /// When instrumenting to collect profile data, the counts for some blocks
1115 /// such as switch cases need to not include the fall-through counts, so
1116 /// emit a branch around the instrumentation code. When not instrumenting,
1117 /// this just calls EmitBlock().
1118 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1119                                                const Stmt *S) {
1120   llvm::BasicBlock *SkipCountBB = nullptr;
1121   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1122     // When instrumenting for profiling, the fallthrough to certain
1123     // statements needs to skip over the instrumentation code so that we
1124     // get an accurate count.
1125     SkipCountBB = createBasicBlock("skipcount");
1126     EmitBranch(SkipCountBB);
1127   }
1128   EmitBlock(BB);
1129   uint64_t CurrentCount = getCurrentProfileCount();
1130   incrementProfileCounter(S);
1131   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1132   if (SkipCountBB)
1133     EmitBlock(SkipCountBB);
1134 }
1135 
1136 /// Tries to mark the given function nounwind based on the
1137 /// non-existence of any throwing calls within it.  We believe this is
1138 /// lightweight enough to do at -O0.
1139 static void TryMarkNoThrow(llvm::Function *F) {
1140   // LLVM treats 'nounwind' on a function as part of the type, so we
1141   // can't do this on functions that can be overwritten.
1142   if (F->isInterposable()) return;
1143 
1144   for (llvm::BasicBlock &BB : *F)
1145     for (llvm::Instruction &I : BB)
1146       if (I.mayThrow())
1147         return;
1148 
1149   F->setDoesNotThrow();
1150 }
1151 
1152 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1153                                                FunctionArgList &Args) {
1154   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1155   QualType ResTy = FD->getReturnType();
1156 
1157   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1158   if (MD && MD->isInstance()) {
1159     if (CGM.getCXXABI().HasThisReturn(GD))
1160       ResTy = MD->getThisType();
1161     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1162       ResTy = CGM.getContext().VoidPtrTy;
1163     CGM.getCXXABI().buildThisParam(*this, Args);
1164   }
1165 
1166   // The base version of an inheriting constructor whose constructed base is a
1167   // virtual base is not passed any arguments (because it doesn't actually call
1168   // the inherited constructor).
1169   bool PassedParams = true;
1170   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1171     if (auto Inherited = CD->getInheritedConstructor())
1172       PassedParams =
1173           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1174 
1175   if (PassedParams) {
1176     for (auto *Param : FD->parameters()) {
1177       Args.push_back(Param);
1178       if (!Param->hasAttr<PassObjectSizeAttr>())
1179         continue;
1180 
1181       auto *Implicit = ImplicitParamDecl::Create(
1182           getContext(), Param->getDeclContext(), Param->getLocation(),
1183           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1184       SizeArguments[Param] = Implicit;
1185       Args.push_back(Implicit);
1186     }
1187   }
1188 
1189   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1190     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1191 
1192   return ResTy;
1193 }
1194 
1195 static bool
1196 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
1197                                              const ASTContext &Context) {
1198   QualType T = FD->getReturnType();
1199   // Avoid the optimization for functions that return a record type with a
1200   // trivial destructor or another trivially copyable type.
1201   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
1202     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1203       return !ClassDecl->hasTrivialDestructor();
1204   }
1205   return !T.isTriviallyCopyableType(Context);
1206 }
1207 
1208 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1209                                    const CGFunctionInfo &FnInfo) {
1210   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1211   CurGD = GD;
1212 
1213   FunctionArgList Args;
1214   QualType ResTy = BuildFunctionArgList(GD, Args);
1215 
1216   // Check if we should generate debug info for this function.
1217   if (FD->hasAttr<NoDebugAttr>())
1218     DebugInfo = nullptr; // disable debug info indefinitely for this function
1219 
1220   // The function might not have a body if we're generating thunks for a
1221   // function declaration.
1222   SourceRange BodyRange;
1223   if (Stmt *Body = FD->getBody())
1224     BodyRange = Body->getSourceRange();
1225   else
1226     BodyRange = FD->getLocation();
1227   CurEHLocation = BodyRange.getEnd();
1228 
1229   // Use the location of the start of the function to determine where
1230   // the function definition is located. By default use the location
1231   // of the declaration as the location for the subprogram. A function
1232   // may lack a declaration in the source code if it is created by code
1233   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1234   SourceLocation Loc = FD->getLocation();
1235 
1236   // If this is a function specialization then use the pattern body
1237   // as the location for the function.
1238   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1239     if (SpecDecl->hasBody(SpecDecl))
1240       Loc = SpecDecl->getLocation();
1241 
1242   Stmt *Body = FD->getBody();
1243 
1244   // Initialize helper which will detect jumps which can cause invalid lifetime
1245   // markers.
1246   if (Body && ShouldEmitLifetimeMarkers)
1247     Bypasses.Init(Body);
1248 
1249   // Emit the standard function prologue.
1250   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1251 
1252   // Generate the body of the function.
1253   PGO.assignRegionCounters(GD, CurFn);
1254   if (isa<CXXDestructorDecl>(FD))
1255     EmitDestructorBody(Args);
1256   else if (isa<CXXConstructorDecl>(FD))
1257     EmitConstructorBody(Args);
1258   else if (getLangOpts().CUDA &&
1259            !getLangOpts().CUDAIsDevice &&
1260            FD->hasAttr<CUDAGlobalAttr>())
1261     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1262   else if (isa<CXXMethodDecl>(FD) &&
1263            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1264     // The lambda static invoker function is special, because it forwards or
1265     // clones the body of the function call operator (but is actually static).
1266     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1267   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1268              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1269               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1270     // Implicit copy-assignment gets the same special treatment as implicit
1271     // copy-constructors.
1272     emitImplicitAssignmentOperatorBody(Args);
1273   } else if (Body) {
1274     EmitFunctionBody(Body);
1275   } else
1276     llvm_unreachable("no definition for emitted function");
1277 
1278   // C++11 [stmt.return]p2:
1279   //   Flowing off the end of a function [...] results in undefined behavior in
1280   //   a value-returning function.
1281   // C11 6.9.1p12:
1282   //   If the '}' that terminates a function is reached, and the value of the
1283   //   function call is used by the caller, the behavior is undefined.
1284   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1285       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1286     bool ShouldEmitUnreachable =
1287         CGM.getCodeGenOpts().StrictReturn ||
1288         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
1289     if (SanOpts.has(SanitizerKind::Return)) {
1290       SanitizerScope SanScope(this);
1291       llvm::Value *IsFalse = Builder.getFalse();
1292       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1293                 SanitizerHandler::MissingReturn,
1294                 EmitCheckSourceLocation(FD->getLocation()), None);
1295     } else if (ShouldEmitUnreachable) {
1296       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1297         EmitTrapCall(llvm::Intrinsic::trap);
1298     }
1299     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1300       Builder.CreateUnreachable();
1301       Builder.ClearInsertionPoint();
1302     }
1303   }
1304 
1305   // Emit the standard function epilogue.
1306   FinishFunction(BodyRange.getEnd());
1307 
1308   // If we haven't marked the function nothrow through other means, do
1309   // a quick pass now to see if we can.
1310   if (!CurFn->doesNotThrow())
1311     TryMarkNoThrow(CurFn);
1312 }
1313 
1314 /// ContainsLabel - Return true if the statement contains a label in it.  If
1315 /// this statement is not executed normally, it not containing a label means
1316 /// that we can just remove the code.
1317 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1318   // Null statement, not a label!
1319   if (!S) return false;
1320 
1321   // If this is a label, we have to emit the code, consider something like:
1322   // if (0) {  ...  foo:  bar(); }  goto foo;
1323   //
1324   // TODO: If anyone cared, we could track __label__'s, since we know that you
1325   // can't jump to one from outside their declared region.
1326   if (isa<LabelStmt>(S))
1327     return true;
1328 
1329   // If this is a case/default statement, and we haven't seen a switch, we have
1330   // to emit the code.
1331   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1332     return true;
1333 
1334   // If this is a switch statement, we want to ignore cases below it.
1335   if (isa<SwitchStmt>(S))
1336     IgnoreCaseStmts = true;
1337 
1338   // Scan subexpressions for verboten labels.
1339   for (const Stmt *SubStmt : S->children())
1340     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1341       return true;
1342 
1343   return false;
1344 }
1345 
1346 /// containsBreak - Return true if the statement contains a break out of it.
1347 /// If the statement (recursively) contains a switch or loop with a break
1348 /// inside of it, this is fine.
1349 bool CodeGenFunction::containsBreak(const Stmt *S) {
1350   // Null statement, not a label!
1351   if (!S) return false;
1352 
1353   // If this is a switch or loop that defines its own break scope, then we can
1354   // include it and anything inside of it.
1355   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1356       isa<ForStmt>(S))
1357     return false;
1358 
1359   if (isa<BreakStmt>(S))
1360     return true;
1361 
1362   // Scan subexpressions for verboten breaks.
1363   for (const Stmt *SubStmt : S->children())
1364     if (containsBreak(SubStmt))
1365       return true;
1366 
1367   return false;
1368 }
1369 
1370 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1371   if (!S) return false;
1372 
1373   // Some statement kinds add a scope and thus never add a decl to the current
1374   // scope. Note, this list is longer than the list of statements that might
1375   // have an unscoped decl nested within them, but this way is conservatively
1376   // correct even if more statement kinds are added.
1377   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1378       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1379       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1380       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1381     return false;
1382 
1383   if (isa<DeclStmt>(S))
1384     return true;
1385 
1386   for (const Stmt *SubStmt : S->children())
1387     if (mightAddDeclToScope(SubStmt))
1388       return true;
1389 
1390   return false;
1391 }
1392 
1393 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1394 /// to a constant, or if it does but contains a label, return false.  If it
1395 /// constant folds return true and set the boolean result in Result.
1396 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1397                                                    bool &ResultBool,
1398                                                    bool AllowLabels) {
1399   llvm::APSInt ResultInt;
1400   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1401     return false;
1402 
1403   ResultBool = ResultInt.getBoolValue();
1404   return true;
1405 }
1406 
1407 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1408 /// to a constant, or if it does but contains a label, return false.  If it
1409 /// constant folds return true and set the folded value.
1410 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1411                                                    llvm::APSInt &ResultInt,
1412                                                    bool AllowLabels) {
1413   // FIXME: Rename and handle conversion of other evaluatable things
1414   // to bool.
1415   Expr::EvalResult Result;
1416   if (!Cond->EvaluateAsInt(Result, getContext()))
1417     return false;  // Not foldable, not integer or not fully evaluatable.
1418 
1419   llvm::APSInt Int = Result.Val.getInt();
1420   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1421     return false;  // Contains a label.
1422 
1423   ResultInt = Int;
1424   return true;
1425 }
1426 
1427 
1428 
1429 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1430 /// statement) to the specified blocks.  Based on the condition, this might try
1431 /// to simplify the codegen of the conditional based on the branch.
1432 ///
1433 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1434                                            llvm::BasicBlock *TrueBlock,
1435                                            llvm::BasicBlock *FalseBlock,
1436                                            uint64_t TrueCount) {
1437   Cond = Cond->IgnoreParens();
1438 
1439   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1440 
1441     // Handle X && Y in a condition.
1442     if (CondBOp->getOpcode() == BO_LAnd) {
1443       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1444       // folded if the case was simple enough.
1445       bool ConstantBool = false;
1446       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1447           ConstantBool) {
1448         // br(1 && X) -> br(X).
1449         incrementProfileCounter(CondBOp);
1450         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1451                                     TrueCount);
1452       }
1453 
1454       // If we have "X && 1", simplify the code to use an uncond branch.
1455       // "X && 0" would have been constant folded to 0.
1456       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1457           ConstantBool) {
1458         // br(X && 1) -> br(X).
1459         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1460                                     TrueCount);
1461       }
1462 
1463       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1464       // want to jump to the FalseBlock.
1465       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1466       // The counter tells us how often we evaluate RHS, and all of TrueCount
1467       // can be propagated to that branch.
1468       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1469 
1470       ConditionalEvaluation eval(*this);
1471       {
1472         ApplyDebugLocation DL(*this, Cond);
1473         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1474         EmitBlock(LHSTrue);
1475       }
1476 
1477       incrementProfileCounter(CondBOp);
1478       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1479 
1480       // Any temporaries created here are conditional.
1481       eval.begin(*this);
1482       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1483       eval.end(*this);
1484 
1485       return;
1486     }
1487 
1488     if (CondBOp->getOpcode() == BO_LOr) {
1489       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1490       // folded if the case was simple enough.
1491       bool ConstantBool = false;
1492       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1493           !ConstantBool) {
1494         // br(0 || X) -> br(X).
1495         incrementProfileCounter(CondBOp);
1496         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1497                                     TrueCount);
1498       }
1499 
1500       // If we have "X || 0", simplify the code to use an uncond branch.
1501       // "X || 1" would have been constant folded to 1.
1502       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1503           !ConstantBool) {
1504         // br(X || 0) -> br(X).
1505         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1506                                     TrueCount);
1507       }
1508 
1509       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1510       // want to jump to the TrueBlock.
1511       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1512       // We have the count for entry to the RHS and for the whole expression
1513       // being true, so we can divy up True count between the short circuit and
1514       // the RHS.
1515       uint64_t LHSCount =
1516           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1517       uint64_t RHSCount = TrueCount - LHSCount;
1518 
1519       ConditionalEvaluation eval(*this);
1520       {
1521         ApplyDebugLocation DL(*this, Cond);
1522         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1523         EmitBlock(LHSFalse);
1524       }
1525 
1526       incrementProfileCounter(CondBOp);
1527       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1528 
1529       // Any temporaries created here are conditional.
1530       eval.begin(*this);
1531       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1532 
1533       eval.end(*this);
1534 
1535       return;
1536     }
1537   }
1538 
1539   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1540     // br(!x, t, f) -> br(x, f, t)
1541     if (CondUOp->getOpcode() == UO_LNot) {
1542       // Negate the count.
1543       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1544       // Negate the condition and swap the destination blocks.
1545       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1546                                   FalseCount);
1547     }
1548   }
1549 
1550   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1551     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1552     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1553     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1554 
1555     ConditionalEvaluation cond(*this);
1556     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1557                          getProfileCount(CondOp));
1558 
1559     // When computing PGO branch weights, we only know the overall count for
1560     // the true block. This code is essentially doing tail duplication of the
1561     // naive code-gen, introducing new edges for which counts are not
1562     // available. Divide the counts proportionally between the LHS and RHS of
1563     // the conditional operator.
1564     uint64_t LHSScaledTrueCount = 0;
1565     if (TrueCount) {
1566       double LHSRatio =
1567           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1568       LHSScaledTrueCount = TrueCount * LHSRatio;
1569     }
1570 
1571     cond.begin(*this);
1572     EmitBlock(LHSBlock);
1573     incrementProfileCounter(CondOp);
1574     {
1575       ApplyDebugLocation DL(*this, Cond);
1576       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1577                            LHSScaledTrueCount);
1578     }
1579     cond.end(*this);
1580 
1581     cond.begin(*this);
1582     EmitBlock(RHSBlock);
1583     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1584                          TrueCount - LHSScaledTrueCount);
1585     cond.end(*this);
1586 
1587     return;
1588   }
1589 
1590   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1591     // Conditional operator handling can give us a throw expression as a
1592     // condition for a case like:
1593     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1594     // Fold this to:
1595     //   br(c, throw x, br(y, t, f))
1596     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1597     return;
1598   }
1599 
1600   // If the branch has a condition wrapped by __builtin_unpredictable,
1601   // create metadata that specifies that the branch is unpredictable.
1602   // Don't bother if not optimizing because that metadata would not be used.
1603   llvm::MDNode *Unpredictable = nullptr;
1604   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1605   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1606     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1607     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1608       llvm::MDBuilder MDHelper(getLLVMContext());
1609       Unpredictable = MDHelper.createUnpredictable();
1610     }
1611   }
1612 
1613   // Create branch weights based on the number of times we get here and the
1614   // number of times the condition should be true.
1615   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1616   llvm::MDNode *Weights =
1617       createProfileWeights(TrueCount, CurrentCount - TrueCount);
1618 
1619   // Emit the code with the fully general case.
1620   llvm::Value *CondV;
1621   {
1622     ApplyDebugLocation DL(*this, Cond);
1623     CondV = EvaluateExprAsBool(Cond);
1624   }
1625   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1626 }
1627 
1628 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1629 /// specified stmt yet.
1630 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1631   CGM.ErrorUnsupported(S, Type);
1632 }
1633 
1634 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1635 /// variable-length array whose elements have a non-zero bit-pattern.
1636 ///
1637 /// \param baseType the inner-most element type of the array
1638 /// \param src - a char* pointing to the bit-pattern for a single
1639 /// base element of the array
1640 /// \param sizeInChars - the total size of the VLA, in chars
1641 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1642                                Address dest, Address src,
1643                                llvm::Value *sizeInChars) {
1644   CGBuilderTy &Builder = CGF.Builder;
1645 
1646   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1647   llvm::Value *baseSizeInChars
1648     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1649 
1650   Address begin =
1651     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1652   llvm::Value *end =
1653     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1654 
1655   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1656   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1657   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1658 
1659   // Make a loop over the VLA.  C99 guarantees that the VLA element
1660   // count must be nonzero.
1661   CGF.EmitBlock(loopBB);
1662 
1663   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1664   cur->addIncoming(begin.getPointer(), originBB);
1665 
1666   CharUnits curAlign =
1667     dest.getAlignment().alignmentOfArrayElement(baseSize);
1668 
1669   // memcpy the individual element bit-pattern.
1670   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1671                        /*volatile*/ false);
1672 
1673   // Go to the next element.
1674   llvm::Value *next =
1675     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1676 
1677   // Leave if that's the end of the VLA.
1678   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1679   Builder.CreateCondBr(done, contBB, loopBB);
1680   cur->addIncoming(next, loopBB);
1681 
1682   CGF.EmitBlock(contBB);
1683 }
1684 
1685 void
1686 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1687   // Ignore empty classes in C++.
1688   if (getLangOpts().CPlusPlus) {
1689     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1690       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1691         return;
1692     }
1693   }
1694 
1695   // Cast the dest ptr to the appropriate i8 pointer type.
1696   if (DestPtr.getElementType() != Int8Ty)
1697     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1698 
1699   // Get size and alignment info for this aggregate.
1700   CharUnits size = getContext().getTypeSizeInChars(Ty);
1701 
1702   llvm::Value *SizeVal;
1703   const VariableArrayType *vla;
1704 
1705   // Don't bother emitting a zero-byte memset.
1706   if (size.isZero()) {
1707     // But note that getTypeInfo returns 0 for a VLA.
1708     if (const VariableArrayType *vlaType =
1709           dyn_cast_or_null<VariableArrayType>(
1710                                           getContext().getAsArrayType(Ty))) {
1711       auto VlaSize = getVLASize(vlaType);
1712       SizeVal = VlaSize.NumElts;
1713       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1714       if (!eltSize.isOne())
1715         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1716       vla = vlaType;
1717     } else {
1718       return;
1719     }
1720   } else {
1721     SizeVal = CGM.getSize(size);
1722     vla = nullptr;
1723   }
1724 
1725   // If the type contains a pointer to data member we can't memset it to zero.
1726   // Instead, create a null constant and copy it to the destination.
1727   // TODO: there are other patterns besides zero that we can usefully memset,
1728   // like -1, which happens to be the pattern used by member-pointers.
1729   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1730     // For a VLA, emit a single element, then splat that over the VLA.
1731     if (vla) Ty = getContext().getBaseElementType(vla);
1732 
1733     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1734 
1735     llvm::GlobalVariable *NullVariable =
1736       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1737                                /*isConstant=*/true,
1738                                llvm::GlobalVariable::PrivateLinkage,
1739                                NullConstant, Twine());
1740     CharUnits NullAlign = DestPtr.getAlignment();
1741     NullVariable->setAlignment(NullAlign.getAsAlign());
1742     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1743                    NullAlign);
1744 
1745     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1746 
1747     // Get and call the appropriate llvm.memcpy overload.
1748     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1749     return;
1750   }
1751 
1752   // Otherwise, just memset the whole thing to zero.  This is legal
1753   // because in LLVM, all default initializers (other than the ones we just
1754   // handled above) are guaranteed to have a bit pattern of all zeros.
1755   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1756 }
1757 
1758 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1759   // Make sure that there is a block for the indirect goto.
1760   if (!IndirectBranch)
1761     GetIndirectGotoBlock();
1762 
1763   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1764 
1765   // Make sure the indirect branch includes all of the address-taken blocks.
1766   IndirectBranch->addDestination(BB);
1767   return llvm::BlockAddress::get(CurFn, BB);
1768 }
1769 
1770 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1771   // If we already made the indirect branch for indirect goto, return its block.
1772   if (IndirectBranch) return IndirectBranch->getParent();
1773 
1774   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1775 
1776   // Create the PHI node that indirect gotos will add entries to.
1777   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1778                                               "indirect.goto.dest");
1779 
1780   // Create the indirect branch instruction.
1781   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1782   return IndirectBranch->getParent();
1783 }
1784 
1785 /// Computes the length of an array in elements, as well as the base
1786 /// element type and a properly-typed first element pointer.
1787 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1788                                               QualType &baseType,
1789                                               Address &addr) {
1790   const ArrayType *arrayType = origArrayType;
1791 
1792   // If it's a VLA, we have to load the stored size.  Note that
1793   // this is the size of the VLA in bytes, not its size in elements.
1794   llvm::Value *numVLAElements = nullptr;
1795   if (isa<VariableArrayType>(arrayType)) {
1796     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
1797 
1798     // Walk into all VLAs.  This doesn't require changes to addr,
1799     // which has type T* where T is the first non-VLA element type.
1800     do {
1801       QualType elementType = arrayType->getElementType();
1802       arrayType = getContext().getAsArrayType(elementType);
1803 
1804       // If we only have VLA components, 'addr' requires no adjustment.
1805       if (!arrayType) {
1806         baseType = elementType;
1807         return numVLAElements;
1808       }
1809     } while (isa<VariableArrayType>(arrayType));
1810 
1811     // We get out here only if we find a constant array type
1812     // inside the VLA.
1813   }
1814 
1815   // We have some number of constant-length arrays, so addr should
1816   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1817   // down to the first element of addr.
1818   SmallVector<llvm::Value*, 8> gepIndices;
1819 
1820   // GEP down to the array type.
1821   llvm::ConstantInt *zero = Builder.getInt32(0);
1822   gepIndices.push_back(zero);
1823 
1824   uint64_t countFromCLAs = 1;
1825   QualType eltType;
1826 
1827   llvm::ArrayType *llvmArrayType =
1828     dyn_cast<llvm::ArrayType>(addr.getElementType());
1829   while (llvmArrayType) {
1830     assert(isa<ConstantArrayType>(arrayType));
1831     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1832              == llvmArrayType->getNumElements());
1833 
1834     gepIndices.push_back(zero);
1835     countFromCLAs *= llvmArrayType->getNumElements();
1836     eltType = arrayType->getElementType();
1837 
1838     llvmArrayType =
1839       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1840     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1841     assert((!llvmArrayType || arrayType) &&
1842            "LLVM and Clang types are out-of-synch");
1843   }
1844 
1845   if (arrayType) {
1846     // From this point onwards, the Clang array type has been emitted
1847     // as some other type (probably a packed struct). Compute the array
1848     // size, and just emit the 'begin' expression as a bitcast.
1849     while (arrayType) {
1850       countFromCLAs *=
1851           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1852       eltType = arrayType->getElementType();
1853       arrayType = getContext().getAsArrayType(eltType);
1854     }
1855 
1856     llvm::Type *baseType = ConvertType(eltType);
1857     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1858   } else {
1859     // Create the actual GEP.
1860     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1861                                              gepIndices, "array.begin"),
1862                    addr.getAlignment());
1863   }
1864 
1865   baseType = eltType;
1866 
1867   llvm::Value *numElements
1868     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1869 
1870   // If we had any VLA dimensions, factor them in.
1871   if (numVLAElements)
1872     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1873 
1874   return numElements;
1875 }
1876 
1877 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
1878   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1879   assert(vla && "type was not a variable array type!");
1880   return getVLASize(vla);
1881 }
1882 
1883 CodeGenFunction::VlaSizePair
1884 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1885   // The number of elements so far; always size_t.
1886   llvm::Value *numElements = nullptr;
1887 
1888   QualType elementType;
1889   do {
1890     elementType = type->getElementType();
1891     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1892     assert(vlaSize && "no size for VLA!");
1893     assert(vlaSize->getType() == SizeTy);
1894 
1895     if (!numElements) {
1896       numElements = vlaSize;
1897     } else {
1898       // It's undefined behavior if this wraps around, so mark it that way.
1899       // FIXME: Teach -fsanitize=undefined to trap this.
1900       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1901     }
1902   } while ((type = getContext().getAsVariableArrayType(elementType)));
1903 
1904   return { numElements, elementType };
1905 }
1906 
1907 CodeGenFunction::VlaSizePair
1908 CodeGenFunction::getVLAElements1D(QualType type) {
1909   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1910   assert(vla && "type was not a variable array type!");
1911   return getVLAElements1D(vla);
1912 }
1913 
1914 CodeGenFunction::VlaSizePair
1915 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
1916   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
1917   assert(VlaSize && "no size for VLA!");
1918   assert(VlaSize->getType() == SizeTy);
1919   return { VlaSize, Vla->getElementType() };
1920 }
1921 
1922 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1923   assert(type->isVariablyModifiedType() &&
1924          "Must pass variably modified type to EmitVLASizes!");
1925 
1926   EnsureInsertPoint();
1927 
1928   // We're going to walk down into the type and look for VLA
1929   // expressions.
1930   do {
1931     assert(type->isVariablyModifiedType());
1932 
1933     const Type *ty = type.getTypePtr();
1934     switch (ty->getTypeClass()) {
1935 
1936 #define TYPE(Class, Base)
1937 #define ABSTRACT_TYPE(Class, Base)
1938 #define NON_CANONICAL_TYPE(Class, Base)
1939 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1940 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1941 #include "clang/AST/TypeNodes.inc"
1942       llvm_unreachable("unexpected dependent type!");
1943 
1944     // These types are never variably-modified.
1945     case Type::Builtin:
1946     case Type::Complex:
1947     case Type::Vector:
1948     case Type::ExtVector:
1949     case Type::ConstantMatrix:
1950     case Type::Record:
1951     case Type::Enum:
1952     case Type::Elaborated:
1953     case Type::TemplateSpecialization:
1954     case Type::ObjCTypeParam:
1955     case Type::ObjCObject:
1956     case Type::ObjCInterface:
1957     case Type::ObjCObjectPointer:
1958     case Type::ExtInt:
1959       llvm_unreachable("type class is never variably-modified!");
1960 
1961     case Type::Adjusted:
1962       type = cast<AdjustedType>(ty)->getAdjustedType();
1963       break;
1964 
1965     case Type::Decayed:
1966       type = cast<DecayedType>(ty)->getPointeeType();
1967       break;
1968 
1969     case Type::Pointer:
1970       type = cast<PointerType>(ty)->getPointeeType();
1971       break;
1972 
1973     case Type::BlockPointer:
1974       type = cast<BlockPointerType>(ty)->getPointeeType();
1975       break;
1976 
1977     case Type::LValueReference:
1978     case Type::RValueReference:
1979       type = cast<ReferenceType>(ty)->getPointeeType();
1980       break;
1981 
1982     case Type::MemberPointer:
1983       type = cast<MemberPointerType>(ty)->getPointeeType();
1984       break;
1985 
1986     case Type::ConstantArray:
1987     case Type::IncompleteArray:
1988       // Losing element qualification here is fine.
1989       type = cast<ArrayType>(ty)->getElementType();
1990       break;
1991 
1992     case Type::VariableArray: {
1993       // Losing element qualification here is fine.
1994       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1995 
1996       // Unknown size indication requires no size computation.
1997       // Otherwise, evaluate and record it.
1998       if (const Expr *size = vat->getSizeExpr()) {
1999         // It's possible that we might have emitted this already,
2000         // e.g. with a typedef and a pointer to it.
2001         llvm::Value *&entry = VLASizeMap[size];
2002         if (!entry) {
2003           llvm::Value *Size = EmitScalarExpr(size);
2004 
2005           // C11 6.7.6.2p5:
2006           //   If the size is an expression that is not an integer constant
2007           //   expression [...] each time it is evaluated it shall have a value
2008           //   greater than zero.
2009           if (SanOpts.has(SanitizerKind::VLABound) &&
2010               size->getType()->isSignedIntegerType()) {
2011             SanitizerScope SanScope(this);
2012             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
2013             llvm::Constant *StaticArgs[] = {
2014                 EmitCheckSourceLocation(size->getBeginLoc()),
2015                 EmitCheckTypeDescriptor(size->getType())};
2016             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
2017                                      SanitizerKind::VLABound),
2018                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2019           }
2020 
2021           // Always zexting here would be wrong if it weren't
2022           // undefined behavior to have a negative bound.
2023           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
2024         }
2025       }
2026       type = vat->getElementType();
2027       break;
2028     }
2029 
2030     case Type::FunctionProto:
2031     case Type::FunctionNoProto:
2032       type = cast<FunctionType>(ty)->getReturnType();
2033       break;
2034 
2035     case Type::Paren:
2036     case Type::TypeOf:
2037     case Type::UnaryTransform:
2038     case Type::Attributed:
2039     case Type::SubstTemplateTypeParm:
2040     case Type::PackExpansion:
2041     case Type::MacroQualified:
2042       // Keep walking after single level desugaring.
2043       type = type.getSingleStepDesugaredType(getContext());
2044       break;
2045 
2046     case Type::Typedef:
2047     case Type::Decltype:
2048     case Type::Auto:
2049     case Type::DeducedTemplateSpecialization:
2050       // Stop walking: nothing to do.
2051       return;
2052 
2053     case Type::TypeOfExpr:
2054       // Stop walking: emit typeof expression.
2055       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2056       return;
2057 
2058     case Type::Atomic:
2059       type = cast<AtomicType>(ty)->getValueType();
2060       break;
2061 
2062     case Type::Pipe:
2063       type = cast<PipeType>(ty)->getElementType();
2064       break;
2065     }
2066   } while (type->isVariablyModifiedType());
2067 }
2068 
2069 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2070   if (getContext().getBuiltinVaListType()->isArrayType())
2071     return EmitPointerWithAlignment(E);
2072   return EmitLValue(E).getAddress(*this);
2073 }
2074 
2075 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2076   return EmitLValue(E).getAddress(*this);
2077 }
2078 
2079 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2080                                               const APValue &Init) {
2081   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2082   if (CGDebugInfo *Dbg = getDebugInfo())
2083     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2084       Dbg->EmitGlobalVariable(E->getDecl(), Init);
2085 }
2086 
2087 CodeGenFunction::PeepholeProtection
2088 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2089   // At the moment, the only aggressive peephole we do in IR gen
2090   // is trunc(zext) folding, but if we add more, we can easily
2091   // extend this protection.
2092 
2093   if (!rvalue.isScalar()) return PeepholeProtection();
2094   llvm::Value *value = rvalue.getScalarVal();
2095   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2096 
2097   // Just make an extra bitcast.
2098   assert(HaveInsertPoint());
2099   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2100                                                   Builder.GetInsertBlock());
2101 
2102   PeepholeProtection protection;
2103   protection.Inst = inst;
2104   return protection;
2105 }
2106 
2107 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2108   if (!protection.Inst) return;
2109 
2110   // In theory, we could try to duplicate the peepholes now, but whatever.
2111   protection.Inst->eraseFromParent();
2112 }
2113 
2114 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2115                                               QualType Ty, SourceLocation Loc,
2116                                               SourceLocation AssumptionLoc,
2117                                               llvm::Value *Alignment,
2118                                               llvm::Value *OffsetValue) {
2119   llvm::Value *TheCheck;
2120   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2121       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
2122   if (SanOpts.has(SanitizerKind::Alignment)) {
2123     emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2124                                  OffsetValue, TheCheck, Assumption);
2125   }
2126 }
2127 
2128 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2129                                               const Expr *E,
2130                                               SourceLocation AssumptionLoc,
2131                                               llvm::Value *Alignment,
2132                                               llvm::Value *OffsetValue) {
2133   if (auto *CE = dyn_cast<CastExpr>(E))
2134     E = CE->getSubExprAsWritten();
2135   QualType Ty = E->getType();
2136   SourceLocation Loc = E->getExprLoc();
2137 
2138   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2139                           OffsetValue);
2140 }
2141 
2142 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2143                                                  llvm::Value *AnnotatedVal,
2144                                                  StringRef AnnotationStr,
2145                                                  SourceLocation Location) {
2146   llvm::Value *Args[4] = {
2147     AnnotatedVal,
2148     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2149     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2150     CGM.EmitAnnotationLineNo(Location)
2151   };
2152   return Builder.CreateCall(AnnotationFn, Args);
2153 }
2154 
2155 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2156   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2157   // FIXME We create a new bitcast for every annotation because that's what
2158   // llvm-gcc was doing.
2159   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2160     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2161                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2162                        I->getAnnotation(), D->getLocation());
2163 }
2164 
2165 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2166                                               Address Addr) {
2167   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2168   llvm::Value *V = Addr.getPointer();
2169   llvm::Type *VTy = V->getType();
2170   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2171                                     CGM.Int8PtrTy);
2172 
2173   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2174     // FIXME Always emit the cast inst so we can differentiate between
2175     // annotation on the first field of a struct and annotation on the struct
2176     // itself.
2177     if (VTy != CGM.Int8PtrTy)
2178       V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
2179     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
2180     V = Builder.CreateBitCast(V, VTy);
2181   }
2182 
2183   return Address(V, Addr.getAlignment());
2184 }
2185 
2186 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2187 
2188 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2189     : CGF(CGF) {
2190   assert(!CGF->IsSanitizerScope);
2191   CGF->IsSanitizerScope = true;
2192 }
2193 
2194 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2195   CGF->IsSanitizerScope = false;
2196 }
2197 
2198 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2199                                    const llvm::Twine &Name,
2200                                    llvm::BasicBlock *BB,
2201                                    llvm::BasicBlock::iterator InsertPt) const {
2202   LoopStack.InsertHelper(I);
2203   if (IsSanitizerScope)
2204     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2205 }
2206 
2207 void CGBuilderInserter::InsertHelper(
2208     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2209     llvm::BasicBlock::iterator InsertPt) const {
2210   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2211   if (CGF)
2212     CGF->InsertHelper(I, Name, BB, InsertPt);
2213 }
2214 
2215 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
2216                                 CodeGenModule &CGM, const FunctionDecl *FD,
2217                                 std::string &FirstMissing) {
2218   // If there aren't any required features listed then go ahead and return.
2219   if (ReqFeatures.empty())
2220     return false;
2221 
2222   // Now build up the set of caller features and verify that all the required
2223   // features are there.
2224   llvm::StringMap<bool> CallerFeatureMap;
2225   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2226 
2227   // If we have at least one of the features in the feature list return
2228   // true, otherwise return false.
2229   return std::all_of(
2230       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2231         SmallVector<StringRef, 1> OrFeatures;
2232         Feature.split(OrFeatures, '|');
2233         return llvm::any_of(OrFeatures, [&](StringRef Feature) {
2234           if (!CallerFeatureMap.lookup(Feature)) {
2235             FirstMissing = Feature.str();
2236             return false;
2237           }
2238           return true;
2239         });
2240       });
2241 }
2242 
2243 // Emits an error if we don't have a valid set of target features for the
2244 // called function.
2245 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2246                                           const FunctionDecl *TargetDecl) {
2247   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2248 }
2249 
2250 // Emits an error if we don't have a valid set of target features for the
2251 // called function.
2252 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2253                                           const FunctionDecl *TargetDecl) {
2254   // Early exit if this is an indirect call.
2255   if (!TargetDecl)
2256     return;
2257 
2258   // Get the current enclosing function if it exists. If it doesn't
2259   // we can't check the target features anyhow.
2260   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2261   if (!FD)
2262     return;
2263 
2264   // Grab the required features for the call. For a builtin this is listed in
2265   // the td file with the default cpu, for an always_inline function this is any
2266   // listed cpu and any listed features.
2267   unsigned BuiltinID = TargetDecl->getBuiltinID();
2268   std::string MissingFeature;
2269   if (BuiltinID) {
2270     SmallVector<StringRef, 1> ReqFeatures;
2271     const char *FeatureList =
2272         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2273     // Return if the builtin doesn't have any required features.
2274     if (!FeatureList || StringRef(FeatureList) == "")
2275       return;
2276     StringRef(FeatureList).split(ReqFeatures, ',');
2277     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2278       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2279           << TargetDecl->getDeclName()
2280           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2281 
2282   } else if (!TargetDecl->isMultiVersion() &&
2283              TargetDecl->hasAttr<TargetAttr>()) {
2284     // Get the required features for the callee.
2285 
2286     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2287     ParsedTargetAttr ParsedAttr =
2288         CGM.getContext().filterFunctionTargetAttrs(TD);
2289 
2290     SmallVector<StringRef, 1> ReqFeatures;
2291     llvm::StringMap<bool> CalleeFeatureMap;
2292     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2293 
2294     for (const auto &F : ParsedAttr.Features) {
2295       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2296         ReqFeatures.push_back(StringRef(F).substr(1));
2297     }
2298 
2299     for (const auto &F : CalleeFeatureMap) {
2300       // Only positive features are "required".
2301       if (F.getValue())
2302         ReqFeatures.push_back(F.getKey());
2303     }
2304     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2305       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2306           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2307   }
2308 }
2309 
2310 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2311   if (!CGM.getCodeGenOpts().SanitizeStats)
2312     return;
2313 
2314   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2315   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2316   CGM.getSanStats().create(IRB, SSK);
2317 }
2318 
2319 llvm::Value *
2320 CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2321   llvm::Value *Condition = nullptr;
2322 
2323   if (!RO.Conditions.Architecture.empty())
2324     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2325 
2326   if (!RO.Conditions.Features.empty()) {
2327     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2328     Condition =
2329         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2330   }
2331   return Condition;
2332 }
2333 
2334 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2335                                              llvm::Function *Resolver,
2336                                              CGBuilderTy &Builder,
2337                                              llvm::Function *FuncToReturn,
2338                                              bool SupportsIFunc) {
2339   if (SupportsIFunc) {
2340     Builder.CreateRet(FuncToReturn);
2341     return;
2342   }
2343 
2344   llvm::SmallVector<llvm::Value *, 10> Args;
2345   llvm::for_each(Resolver->args(),
2346                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2347 
2348   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2349   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2350 
2351   if (Resolver->getReturnType()->isVoidTy())
2352     Builder.CreateRetVoid();
2353   else
2354     Builder.CreateRet(Result);
2355 }
2356 
2357 void CodeGenFunction::EmitMultiVersionResolver(
2358     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2359   assert(getContext().getTargetInfo().getTriple().isX86() &&
2360          "Only implemented for x86 targets");
2361 
2362   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2363 
2364   // Main function's basic block.
2365   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2366   Builder.SetInsertPoint(CurBlock);
2367   EmitX86CpuInit();
2368 
2369   for (const MultiVersionResolverOption &RO : Options) {
2370     Builder.SetInsertPoint(CurBlock);
2371     llvm::Value *Condition = FormResolverCondition(RO);
2372 
2373     // The 'default' or 'generic' case.
2374     if (!Condition) {
2375       assert(&RO == Options.end() - 1 &&
2376              "Default or Generic case must be last");
2377       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2378                                        SupportsIFunc);
2379       return;
2380     }
2381 
2382     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2383     CGBuilderTy RetBuilder(*this, RetBlock);
2384     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2385                                      SupportsIFunc);
2386     CurBlock = createBasicBlock("resolver_else", Resolver);
2387     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2388   }
2389 
2390   // If no generic/default, emit an unreachable.
2391   Builder.SetInsertPoint(CurBlock);
2392   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2393   TrapCall->setDoesNotReturn();
2394   TrapCall->setDoesNotThrow();
2395   Builder.CreateUnreachable();
2396   Builder.ClearInsertionPoint();
2397 }
2398 
2399 // Loc - where the diagnostic will point, where in the source code this
2400 //  alignment has failed.
2401 // SecondaryLoc - if present (will be present if sufficiently different from
2402 //  Loc), the diagnostic will additionally point a "Note:" to this location.
2403 //  It should be the location where the __attribute__((assume_aligned))
2404 //  was written e.g.
2405 void CodeGenFunction::emitAlignmentAssumptionCheck(
2406     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2407     SourceLocation SecondaryLoc, llvm::Value *Alignment,
2408     llvm::Value *OffsetValue, llvm::Value *TheCheck,
2409     llvm::Instruction *Assumption) {
2410   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2411          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2412              llvm::Intrinsic::getDeclaration(
2413                  Builder.GetInsertBlock()->getParent()->getParent(),
2414                  llvm::Intrinsic::assume) &&
2415          "Assumption should be a call to llvm.assume().");
2416   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2417          "Assumption should be the last instruction of the basic block, "
2418          "since the basic block is still being generated.");
2419 
2420   if (!SanOpts.has(SanitizerKind::Alignment))
2421     return;
2422 
2423   // Don't check pointers to volatile data. The behavior here is implementation-
2424   // defined.
2425   if (Ty->getPointeeType().isVolatileQualified())
2426     return;
2427 
2428   // We need to temorairly remove the assumption so we can insert the
2429   // sanitizer check before it, else the check will be dropped by optimizations.
2430   Assumption->removeFromParent();
2431 
2432   {
2433     SanitizerScope SanScope(this);
2434 
2435     if (!OffsetValue)
2436       OffsetValue = Builder.getInt1(0); // no offset.
2437 
2438     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2439                                     EmitCheckSourceLocation(SecondaryLoc),
2440                                     EmitCheckTypeDescriptor(Ty)};
2441     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2442                                   EmitCheckValue(Alignment),
2443                                   EmitCheckValue(OffsetValue)};
2444     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2445               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2446   }
2447 
2448   // We are now in the (new, empty) "cont" basic block.
2449   // Reintroduce the assumption.
2450   Builder.Insert(Assumption);
2451   // FIXME: Assumption still has it's original basic block as it's Parent.
2452 }
2453 
2454 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2455   if (CGDebugInfo *DI = getDebugInfo())
2456     return DI->SourceLocToDebugLoc(Location);
2457 
2458   return llvm::DebugLoc();
2459 }
2460