xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 9ad72df55cb74b29193270c28f6974d2af8e0b71)
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 "CGHLSLRuntime.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/ASTLambda.h"
26 #include "clang/AST/Attr.h"
27 #include "clang/AST/Decl.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/StmtObjC.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CodeGenOptions.h"
34 #include "clang/Basic/TargetBuiltins.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/CodeGen/CGFunctionInfo.h"
37 #include "clang/Frontend/FrontendDiagnostic.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/FPEnv.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/MDBuilder.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/Support/CRC.h"
48 #include "llvm/Support/xxhash.h"
49 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
50 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
51 #include <optional>
52 
53 using namespace clang;
54 using namespace CodeGen;
55 
56 namespace llvm {
57 extern cl::opt<bool> EnableSingleByteCoverage;
58 } // namespace llvm
59 
60 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
61 /// markers.
62 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
63                                       const LangOptions &LangOpts) {
64   if (CGOpts.DisableLifetimeMarkers)
65     return false;
66 
67   // Sanitizers may use markers.
68   if (CGOpts.SanitizeAddressUseAfterScope ||
69       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
70       LangOpts.Sanitize.has(SanitizerKind::Memory))
71     return true;
72 
73   // For now, only in optimized builds.
74   return CGOpts.OptimizationLevel != 0;
75 }
76 
77 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
78     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
79       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
80               CGBuilderInserterTy(this)),
81       SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
82       DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
83       ShouldEmitLifetimeMarkers(
84           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
85   if (!suppressNewContext)
86     CGM.getCXXABI().getMangleContext().startNewFunction();
87   EHStack.setCGF(this);
88 
89   SetFastMathFlags(CurFPFeatures);
90 }
91 
92 CodeGenFunction::~CodeGenFunction() {
93   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
94   assert(DeferredDeactivationCleanupStack.empty() &&
95          "missed to deactivate a cleanup");
96 
97   if (getLangOpts().OpenMP && CurFn)
98     CGM.getOpenMPRuntime().functionFinished(*this);
99 
100   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
101   // outlining etc) at some point. Doing it once the function codegen is done
102   // seems to be a reasonable spot. We do it here, as opposed to the deletion
103   // time of the CodeGenModule, because we have to ensure the IR has not yet
104   // been "emitted" to the outside, thus, modifications are still sensible.
105   if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
106     CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
107 }
108 
109 // Map the LangOption for exception behavior into
110 // the corresponding enum in the IR.
111 llvm::fp::ExceptionBehavior
112 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
113 
114   switch (Kind) {
115   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
116   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
117   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
118   default:
119     llvm_unreachable("Unsupported FP Exception Behavior");
120   }
121 }
122 
123 void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
124   llvm::FastMathFlags FMF;
125   FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
126   FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
127   FMF.setNoInfs(FPFeatures.getNoHonorInfs());
128   FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
129   FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
130   FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
131   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
132   Builder.setFastMathFlags(FMF);
133 }
134 
135 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
136                                                   const Expr *E)
137     : CGF(CGF) {
138   ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
139 }
140 
141 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
142                                                   FPOptions FPFeatures)
143     : CGF(CGF) {
144   ConstructorHelper(FPFeatures);
145 }
146 
147 void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
148   OldFPFeatures = CGF.CurFPFeatures;
149   CGF.CurFPFeatures = FPFeatures;
150 
151   OldExcept = CGF.Builder.getDefaultConstrainedExcept();
152   OldRounding = CGF.Builder.getDefaultConstrainedRounding();
153 
154   if (OldFPFeatures == FPFeatures)
155     return;
156 
157   FMFGuard.emplace(CGF.Builder);
158 
159   llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
160   CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
161   auto NewExceptionBehavior =
162       ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
163           FPFeatures.getExceptionMode()));
164   CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
165 
166   CGF.SetFastMathFlags(FPFeatures);
167 
168   assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
169           isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
170           isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
171           (NewExceptionBehavior == llvm::fp::ebIgnore &&
172            NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
173          "FPConstrained should be enabled on entire function");
174 
175   auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
176     auto OldValue =
177         CGF.CurFn->getFnAttribute(Name).getValueAsBool();
178     auto NewValue = OldValue & Value;
179     if (OldValue != NewValue)
180       CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
181   };
182   mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
183   mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
184   mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
185   mergeFnAttrValue(
186       "unsafe-fp-math",
187       FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
188           FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
189           FPFeatures.allowFPContractAcrossStatement());
190 }
191 
192 CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
193   CGF.CurFPFeatures = OldFPFeatures;
194   CGF.Builder.setDefaultConstrainedExcept(OldExcept);
195   CGF.Builder.setDefaultConstrainedRounding(OldRounding);
196 }
197 
198 static LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T,
199                                          bool ForPointeeType,
200                                          CodeGenFunction &CGF) {
201   LValueBaseInfo BaseInfo;
202   TBAAAccessInfo TBAAInfo;
203   CharUnits Alignment =
204       CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
205   Address Addr = Address(V, CGF.ConvertTypeForMem(T), Alignment);
206   return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
207 }
208 
209 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
210   return ::MakeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false, *this);
211 }
212 
213 LValue
214 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
215   return ::MakeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true, *this);
216 }
217 
218 LValue CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value *V,
219                                                       QualType T) {
220   return ::MakeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false, *this);
221 }
222 
223 LValue CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V,
224                                                              QualType T) {
225   return ::MakeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true, *this);
226 }
227 
228 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
229   return CGM.getTypes().ConvertTypeForMem(T);
230 }
231 
232 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
233   return CGM.getTypes().ConvertType(T);
234 }
235 
236 llvm::Type *CodeGenFunction::convertTypeForLoadStore(QualType ASTTy,
237                                                      llvm::Type *LLVMTy) {
238   return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
239 }
240 
241 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
242   type = type.getCanonicalType();
243   while (true) {
244     switch (type->getTypeClass()) {
245 #define TYPE(name, parent)
246 #define ABSTRACT_TYPE(name, parent)
247 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
248 #define DEPENDENT_TYPE(name, parent) case Type::name:
249 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
250 #include "clang/AST/TypeNodes.inc"
251       llvm_unreachable("non-canonical or dependent type in IR-generation");
252 
253     case Type::Auto:
254     case Type::DeducedTemplateSpecialization:
255       llvm_unreachable("undeduced type in IR-generation");
256 
257     // Various scalar types.
258     case Type::Builtin:
259     case Type::Pointer:
260     case Type::BlockPointer:
261     case Type::LValueReference:
262     case Type::RValueReference:
263     case Type::MemberPointer:
264     case Type::Vector:
265     case Type::ExtVector:
266     case Type::ConstantMatrix:
267     case Type::FunctionProto:
268     case Type::FunctionNoProto:
269     case Type::Enum:
270     case Type::ObjCObjectPointer:
271     case Type::Pipe:
272     case Type::BitInt:
273       return TEK_Scalar;
274 
275     // Complexes.
276     case Type::Complex:
277       return TEK_Complex;
278 
279     // Arrays, records, and Objective-C objects.
280     case Type::ConstantArray:
281     case Type::IncompleteArray:
282     case Type::VariableArray:
283     case Type::Record:
284     case Type::ObjCObject:
285     case Type::ObjCInterface:
286     case Type::ArrayParameter:
287       return TEK_Aggregate;
288 
289     // We operate on atomic values according to their underlying type.
290     case Type::Atomic:
291       type = cast<AtomicType>(type)->getValueType();
292       continue;
293     }
294     llvm_unreachable("unknown type kind!");
295   }
296 }
297 
298 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
299   // For cleanliness, we try to avoid emitting the return block for
300   // simple cases.
301   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
302 
303   if (CurBB) {
304     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
305 
306     // We have a valid insert point, reuse it if it is empty or there are no
307     // explicit jumps to the return block.
308     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
309       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
310       delete ReturnBlock.getBlock();
311       ReturnBlock = JumpDest();
312     } else
313       EmitBlock(ReturnBlock.getBlock());
314     return llvm::DebugLoc();
315   }
316 
317   // Otherwise, if the return block is the target of a single direct
318   // branch then we can just put the code in that block instead. This
319   // cleans up functions which started with a unified return block.
320   if (ReturnBlock.getBlock()->hasOneUse()) {
321     llvm::BranchInst *BI =
322       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
323     if (BI && BI->isUnconditional() &&
324         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
325       // Record/return the DebugLoc of the simple 'return' expression to be used
326       // later by the actual 'ret' instruction.
327       llvm::DebugLoc Loc = BI->getDebugLoc();
328       Builder.SetInsertPoint(BI->getParent());
329       BI->eraseFromParent();
330       delete ReturnBlock.getBlock();
331       ReturnBlock = JumpDest();
332       return Loc;
333     }
334   }
335 
336   // FIXME: We are at an unreachable point, there is no reason to emit the block
337   // unless it has uses. However, we still need a place to put the debug
338   // region.end for now.
339 
340   EmitBlock(ReturnBlock.getBlock());
341   return llvm::DebugLoc();
342 }
343 
344 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
345   if (!BB) return;
346   if (!BB->use_empty()) {
347     CGF.CurFn->insert(CGF.CurFn->end(), BB);
348     return;
349   }
350   delete BB;
351 }
352 
353 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
354   assert(BreakContinueStack.empty() &&
355          "mismatched push/pop in break/continue stack!");
356   assert(LifetimeExtendedCleanupStack.empty() &&
357          "mismatched push/pop of cleanups in EHStack!");
358   assert(DeferredDeactivationCleanupStack.empty() &&
359          "mismatched activate/deactivate of cleanups!");
360 
361   if (CGM.shouldEmitConvergenceTokens()) {
362     ConvergenceTokenStack.pop_back();
363     assert(ConvergenceTokenStack.empty() &&
364            "mismatched push/pop in convergence stack!");
365   }
366 
367   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
368     && NumSimpleReturnExprs == NumReturnExprs
369     && ReturnBlock.getBlock()->use_empty();
370   // Usually the return expression is evaluated before the cleanup
371   // code.  If the function contains only a simple return statement,
372   // such as a constant, the location before the cleanup code becomes
373   // the last useful breakpoint in the function, because the simple
374   // return expression will be evaluated after the cleanup code. To be
375   // safe, set the debug location for cleanup code to the location of
376   // the return statement.  Otherwise the cleanup code should be at the
377   // end of the function's lexical scope.
378   //
379   // If there are multiple branches to the return block, the branch
380   // instructions will get the location of the return statements and
381   // all will be fine.
382   if (CGDebugInfo *DI = getDebugInfo()) {
383     if (OnlySimpleReturnStmts)
384       DI->EmitLocation(Builder, LastStopPoint);
385     else
386       DI->EmitLocation(Builder, EndLoc);
387   }
388 
389   // Pop any cleanups that might have been associated with the
390   // parameters.  Do this in whatever block we're currently in; it's
391   // important to do this before we enter the return block or return
392   // edges will be *really* confused.
393   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
394   bool HasOnlyLifetimeMarkers =
395       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
396   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
397 
398   std::optional<ApplyDebugLocation> OAL;
399   if (HasCleanups) {
400     // Make sure the line table doesn't jump back into the body for
401     // the ret after it's been at EndLoc.
402     if (CGDebugInfo *DI = getDebugInfo()) {
403       if (OnlySimpleReturnStmts)
404         DI->EmitLocation(Builder, EndLoc);
405       else
406         // We may not have a valid end location. Try to apply it anyway, and
407         // fall back to an artificial location if needed.
408         OAL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
409     }
410 
411     PopCleanupBlocks(PrologueCleanupDepth);
412   }
413 
414   // Emit function epilog (to return).
415   llvm::DebugLoc Loc = EmitReturnBlock();
416 
417   if (ShouldInstrumentFunction()) {
418     if (CGM.getCodeGenOpts().InstrumentFunctions)
419       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
420     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
421       CurFn->addFnAttr("instrument-function-exit-inlined",
422                        "__cyg_profile_func_exit");
423   }
424 
425   // Emit debug descriptor for function end.
426   if (CGDebugInfo *DI = getDebugInfo())
427     DI->EmitFunctionEnd(Builder, CurFn);
428 
429   // Reset the debug location to that of the simple 'return' expression, if any
430   // rather than that of the end of the function's scope '}'.
431   ApplyDebugLocation AL(*this, Loc);
432   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
433   EmitEndEHSpec(CurCodeDecl);
434 
435   assert(EHStack.empty() &&
436          "did not remove all scopes from cleanup stack!");
437 
438   // If someone did an indirect goto, emit the indirect goto block at the end of
439   // the function.
440   if (IndirectBranch) {
441     EmitBlock(IndirectBranch->getParent());
442     Builder.ClearInsertionPoint();
443   }
444 
445   // If some of our locals escaped, insert a call to llvm.localescape in the
446   // entry block.
447   if (!EscapedLocals.empty()) {
448     // Invert the map from local to index into a simple vector. There should be
449     // no holes.
450     SmallVector<llvm::Value *, 4> EscapeArgs;
451     EscapeArgs.resize(EscapedLocals.size());
452     for (auto &Pair : EscapedLocals)
453       EscapeArgs[Pair.second] = Pair.first;
454     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
455         &CGM.getModule(), llvm::Intrinsic::localescape);
456     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
457   }
458 
459   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
460   llvm::Instruction *Ptr = AllocaInsertPt;
461   AllocaInsertPt = nullptr;
462   Ptr->eraseFromParent();
463 
464   // PostAllocaInsertPt, if created, was lazily created when it was required,
465   // remove it now since it was just created for our own convenience.
466   if (PostAllocaInsertPt) {
467     llvm::Instruction *PostPtr = PostAllocaInsertPt;
468     PostAllocaInsertPt = nullptr;
469     PostPtr->eraseFromParent();
470   }
471 
472   // If someone took the address of a label but never did an indirect goto, we
473   // made a zero entry PHI node, which is illegal, zap it now.
474   if (IndirectBranch) {
475     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
476     if (PN->getNumIncomingValues() == 0) {
477       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
478       PN->eraseFromParent();
479     }
480   }
481 
482   EmitIfUsed(*this, EHResumeBlock);
483   EmitIfUsed(*this, TerminateLandingPad);
484   EmitIfUsed(*this, TerminateHandler);
485   EmitIfUsed(*this, UnreachableBlock);
486 
487   for (const auto &FuncletAndParent : TerminateFunclets)
488     EmitIfUsed(*this, FuncletAndParent.second);
489 
490   if (CGM.getCodeGenOpts().EmitDeclMetadata)
491     EmitDeclMetadata();
492 
493   for (const auto &R : DeferredReplacements) {
494     if (llvm::Value *Old = R.first) {
495       Old->replaceAllUsesWith(R.second);
496       cast<llvm::Instruction>(Old)->eraseFromParent();
497     }
498   }
499   DeferredReplacements.clear();
500 
501   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
502   // PHIs if the current function is a coroutine. We don't do it for all
503   // functions as it may result in slight increase in numbers of instructions
504   // if compiled with no optimizations. We do it for coroutine as the lifetime
505   // of CleanupDestSlot alloca make correct coroutine frame building very
506   // difficult.
507   if (NormalCleanupDest.isValid() && isCoroutine()) {
508     llvm::DominatorTree DT(*CurFn);
509     llvm::PromoteMemToReg(
510         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
511     NormalCleanupDest = Address::invalid();
512   }
513 
514   // Scan function arguments for vector width.
515   for (llvm::Argument &A : CurFn->args())
516     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
517       LargestVectorWidth =
518           std::max((uint64_t)LargestVectorWidth,
519                    VT->getPrimitiveSizeInBits().getKnownMinValue());
520 
521   // Update vector width based on return type.
522   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
523     LargestVectorWidth =
524         std::max((uint64_t)LargestVectorWidth,
525                  VT->getPrimitiveSizeInBits().getKnownMinValue());
526 
527   if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
528     LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
529 
530   // Add the min-legal-vector-width attribute. This contains the max width from:
531   // 1. min-vector-width attribute used in the source program.
532   // 2. Any builtins used that have a vector width specified.
533   // 3. Values passed in and out of inline assembly.
534   // 4. Width of vector arguments and return types for this function.
535   // 5. Width of vector arguments and return types for functions called by this
536   //    function.
537   if (getContext().getTargetInfo().getTriple().isX86())
538     CurFn->addFnAttr("min-legal-vector-width",
539                      llvm::utostr(LargestVectorWidth));
540 
541   // Add vscale_range attribute if appropriate.
542   std::optional<std::pair<unsigned, unsigned>> VScaleRange =
543       getContext().getTargetInfo().getVScaleRange(getLangOpts());
544   if (VScaleRange) {
545     CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
546         getLLVMContext(), VScaleRange->first, VScaleRange->second));
547   }
548 
549   // If we generated an unreachable return block, delete it now.
550   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
551     Builder.ClearInsertionPoint();
552     ReturnBlock.getBlock()->eraseFromParent();
553   }
554   if (ReturnValue.isValid()) {
555     auto *RetAlloca =
556         dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this));
557     if (RetAlloca && RetAlloca->use_empty()) {
558       RetAlloca->eraseFromParent();
559       ReturnValue = Address::invalid();
560     }
561   }
562 }
563 
564 /// ShouldInstrumentFunction - Return true if the current function should be
565 /// instrumented with __cyg_profile_func_* calls
566 bool CodeGenFunction::ShouldInstrumentFunction() {
567   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
568       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
569       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
570     return false;
571   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
572     return false;
573   return true;
574 }
575 
576 bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
577   if (!CurFuncDecl)
578     return false;
579   return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
580 }
581 
582 /// ShouldXRayInstrument - Return true if the current function should be
583 /// instrumented with XRay nop sleds.
584 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
585   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
586 }
587 
588 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
589 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
590 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
591   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
592          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
593           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
594               XRayInstrKind::Custom);
595 }
596 
597 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
598   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
599          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
600           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
601               XRayInstrKind::Typed);
602 }
603 
604 llvm::ConstantInt *
605 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
606   // Remove any (C++17) exception specifications, to allow calling e.g. a
607   // noexcept function through a non-noexcept pointer.
608   if (!Ty->isFunctionNoProtoType())
609     Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None);
610   std::string Mangled;
611   llvm::raw_string_ostream Out(Mangled);
612   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out, false);
613   return llvm::ConstantInt::get(
614       CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled)));
615 }
616 
617 void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
618                                          llvm::Function *Fn) {
619   if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
620     return;
621 
622   llvm::LLVMContext &Context = getLLVMContext();
623 
624   CGM.GenKernelArgMetadata(Fn, FD, this);
625 
626   if (!getLangOpts().OpenCL)
627     return;
628 
629   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
630     QualType HintQTy = A->getTypeHint();
631     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
632     bool IsSignedInteger =
633         HintQTy->isSignedIntegerType() ||
634         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
635     llvm::Metadata *AttrMDArgs[] = {
636         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
637             CGM.getTypes().ConvertType(A->getTypeHint()))),
638         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
639             llvm::IntegerType::get(Context, 32),
640             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
641     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
642   }
643 
644   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
645     llvm::Metadata *AttrMDArgs[] = {
646         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
647         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
648         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
649     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
650   }
651 
652   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
653     llvm::Metadata *AttrMDArgs[] = {
654         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
655         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
656         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
657     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
658   }
659 
660   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
661           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
662     llvm::Metadata *AttrMDArgs[] = {
663         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
664     Fn->setMetadata("intel_reqd_sub_group_size",
665                     llvm::MDNode::get(Context, AttrMDArgs));
666   }
667 }
668 
669 /// Determine whether the function F ends with a return stmt.
670 static bool endsWithReturn(const Decl* F) {
671   const Stmt *Body = nullptr;
672   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
673     Body = FD->getBody();
674   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
675     Body = OMD->getBody();
676 
677   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
678     auto LastStmt = CS->body_rbegin();
679     if (LastStmt != CS->body_rend())
680       return isa<ReturnStmt>(*LastStmt);
681   }
682   return false;
683 }
684 
685 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
686   if (SanOpts.has(SanitizerKind::Thread)) {
687     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
688     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
689   }
690 }
691 
692 /// Check if the return value of this function requires sanitization.
693 bool CodeGenFunction::requiresReturnValueCheck() const {
694   return requiresReturnValueNullabilityCheck() ||
695          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
696           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
697 }
698 
699 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
700   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
701   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
702       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
703       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
704     return false;
705 
706   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
707     return false;
708 
709   if (MD->getNumParams() == 2) {
710     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
711     if (!PT || !PT->isVoidPointerType() ||
712         !PT->getPointeeType().isConstQualified())
713       return false;
714   }
715 
716   return true;
717 }
718 
719 bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
720   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
721   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
722 }
723 
724 bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
725   return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
726          getTarget().getCXXABI().isMicrosoft() &&
727          llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
728            return isInAllocaArgument(CGM.getCXXABI(), P->getType());
729          });
730 }
731 
732 /// Return the UBSan prologue signature for \p FD if one is available.
733 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
734                                             const FunctionDecl *FD) {
735   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
736     if (!MD->isStatic())
737       return nullptr;
738   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
739 }
740 
741 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
742                                     llvm::Function *Fn,
743                                     const CGFunctionInfo &FnInfo,
744                                     const FunctionArgList &Args,
745                                     SourceLocation Loc,
746                                     SourceLocation StartLoc) {
747   assert(!CurFn &&
748          "Do not use a CodeGenFunction object for more than one function");
749 
750   const Decl *D = GD.getDecl();
751 
752   DidCallStackSave = false;
753   CurCodeDecl = D;
754   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
755   if (FD && FD->usesSEHTry())
756     CurSEHParent = GD;
757   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
758   FnRetTy = RetTy;
759   CurFn = Fn;
760   CurFnInfo = &FnInfo;
761   assert(CurFn->isDeclaration() && "Function already has body?");
762 
763   // If this function is ignored for any of the enabled sanitizers,
764   // disable the sanitizer for the function.
765   do {
766 #define SANITIZER(NAME, ID)                                                    \
767   if (SanOpts.empty())                                                         \
768     break;                                                                     \
769   if (SanOpts.has(SanitizerKind::ID))                                          \
770     if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc))                    \
771       SanOpts.set(SanitizerKind::ID, false);
772 
773 #include "clang/Basic/Sanitizers.def"
774 #undef SANITIZER
775   } while (false);
776 
777   if (D) {
778     const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
779     SanitizerMask no_sanitize_mask;
780     bool NoSanitizeCoverage = false;
781 
782     for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
783       no_sanitize_mask |= Attr->getMask();
784       // SanitizeCoverage is not handled by SanOpts.
785       if (Attr->hasCoverage())
786         NoSanitizeCoverage = true;
787     }
788 
789     // Apply the no_sanitize* attributes to SanOpts.
790     SanOpts.Mask &= ~no_sanitize_mask;
791     if (no_sanitize_mask & SanitizerKind::Address)
792       SanOpts.set(SanitizerKind::KernelAddress, false);
793     if (no_sanitize_mask & SanitizerKind::KernelAddress)
794       SanOpts.set(SanitizerKind::Address, false);
795     if (no_sanitize_mask & SanitizerKind::HWAddress)
796       SanOpts.set(SanitizerKind::KernelHWAddress, false);
797     if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
798       SanOpts.set(SanitizerKind::HWAddress, false);
799 
800     if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
801       Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
802 
803     if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
804       Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
805 
806     // Some passes need the non-negated no_sanitize attribute. Pass them on.
807     if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
808       if (no_sanitize_mask & SanitizerKind::Thread)
809         Fn->addFnAttr("no_sanitize_thread");
810     }
811   }
812 
813   if (ShouldSkipSanitizerInstrumentation()) {
814     CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
815   } else {
816     // Apply sanitizer attributes to the function.
817     if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
818       Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
819     if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
820                          SanitizerKind::KernelHWAddress))
821       Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
822     if (SanOpts.has(SanitizerKind::MemtagStack))
823       Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
824     if (SanOpts.has(SanitizerKind::Thread))
825       Fn->addFnAttr(llvm::Attribute::SanitizeThread);
826     if (SanOpts.has(SanitizerKind::NumericalStability))
827       Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
828     if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
829       Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
830   }
831   if (SanOpts.has(SanitizerKind::SafeStack))
832     Fn->addFnAttr(llvm::Attribute::SafeStack);
833   if (SanOpts.has(SanitizerKind::ShadowCallStack))
834     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
835 
836   // Apply fuzzing attribute to the function.
837   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
838     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
839 
840   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
841   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
842   if (SanOpts.has(SanitizerKind::Thread)) {
843     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
844       const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
845       if (OMD->getMethodFamily() == OMF_dealloc ||
846           OMD->getMethodFamily() == OMF_initialize ||
847           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
848         markAsIgnoreThreadCheckingAtRuntime(Fn);
849       }
850     }
851   }
852 
853   // Ignore unrelated casts in STL allocate() since the allocator must cast
854   // from void* to T* before object initialization completes. Don't match on the
855   // namespace because not all allocators are in std::
856   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
857     if (matchesStlAllocatorFn(D, getContext()))
858       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
859   }
860 
861   // Ignore null checks in coroutine functions since the coroutines passes
862   // are not aware of how to move the extra UBSan instructions across the split
863   // coroutine boundaries.
864   if (D && SanOpts.has(SanitizerKind::Null))
865     if (FD && FD->getBody() &&
866         FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
867       SanOpts.Mask &= ~SanitizerKind::Null;
868 
869   // Add pointer authentication attributes.
870   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
871   if (CodeGenOpts.PointerAuth.FunctionPointers)
872     Fn->addFnAttr("ptrauth-calls");
873 
874   // Apply xray attributes to the function (as a string, for now)
875   bool AlwaysXRayAttr = false;
876   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
877     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
878             XRayInstrKind::FunctionEntry) ||
879         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
880             XRayInstrKind::FunctionExit)) {
881       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
882         Fn->addFnAttr("function-instrument", "xray-always");
883         AlwaysXRayAttr = true;
884       }
885       if (XRayAttr->neverXRayInstrument())
886         Fn->addFnAttr("function-instrument", "xray-never");
887       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
888         if (ShouldXRayInstrumentFunction())
889           Fn->addFnAttr("xray-log-args",
890                         llvm::utostr(LogArgs->getArgumentCount()));
891     }
892   } else {
893     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
894       Fn->addFnAttr(
895           "xray-instruction-threshold",
896           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
897   }
898 
899   if (ShouldXRayInstrumentFunction()) {
900     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
901       Fn->addFnAttr("xray-ignore-loops");
902 
903     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
904             XRayInstrKind::FunctionExit))
905       Fn->addFnAttr("xray-skip-exit");
906 
907     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
908             XRayInstrKind::FunctionEntry))
909       Fn->addFnAttr("xray-skip-entry");
910 
911     auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
912     if (FuncGroups > 1) {
913       auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
914                                               CurFn->getName().bytes_end());
915       auto Group = crc32(FuncName) % FuncGroups;
916       if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
917           !AlwaysXRayAttr)
918         Fn->addFnAttr("function-instrument", "xray-never");
919     }
920   }
921 
922   if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) {
923     switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
924     case ProfileList::Skip:
925       Fn->addFnAttr(llvm::Attribute::SkipProfile);
926       break;
927     case ProfileList::Forbid:
928       Fn->addFnAttr(llvm::Attribute::NoProfile);
929       break;
930     case ProfileList::Allow:
931       break;
932     }
933   }
934 
935   unsigned Count, Offset;
936   if (const auto *Attr =
937           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
938     Count = Attr->getCount();
939     Offset = Attr->getOffset();
940   } else {
941     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
942     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
943   }
944   if (Count && Offset <= Count) {
945     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
946     if (Offset)
947       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
948   }
949   // Instruct that functions for COFF/CodeView targets should start with a
950   // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
951   // backends as they don't need it -- instructions on these architectures are
952   // always atomically patchable at runtime.
953   if (CGM.getCodeGenOpts().HotPatch &&
954       getContext().getTargetInfo().getTriple().isX86() &&
955       getContext().getTargetInfo().getTriple().getEnvironment() !=
956           llvm::Triple::CODE16)
957     Fn->addFnAttr("patchable-function", "prologue-short-redirect");
958 
959   // Add no-jump-tables value.
960   if (CGM.getCodeGenOpts().NoUseJumpTables)
961     Fn->addFnAttr("no-jump-tables", "true");
962 
963   // Add no-inline-line-tables value.
964   if (CGM.getCodeGenOpts().NoInlineLineTables)
965     Fn->addFnAttr("no-inline-line-tables");
966 
967   // Add profile-sample-accurate value.
968   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
969     Fn->addFnAttr("profile-sample-accurate");
970 
971   if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
972     Fn->addFnAttr("use-sample-profile");
973 
974   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
975     Fn->addFnAttr("cfi-canonical-jump-table");
976 
977   if (D && D->hasAttr<NoProfileFunctionAttr>())
978     Fn->addFnAttr(llvm::Attribute::NoProfile);
979 
980   if (D) {
981     // Function attributes take precedence over command line flags.
982     if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
983       switch (A->getThunkType()) {
984       case FunctionReturnThunksAttr::Kind::Keep:
985         break;
986       case FunctionReturnThunksAttr::Kind::Extern:
987         Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
988         break;
989       }
990     } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
991       Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
992   }
993 
994   if (FD && (getLangOpts().OpenCL ||
995              (getLangOpts().HIP && getLangOpts().CUDAIsDevice))) {
996     // Add metadata for a kernel function.
997     EmitKernelMetadata(FD, Fn);
998   }
999 
1000   if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1001     Fn->setMetadata("clspv_libclc_builtin",
1002                     llvm::MDNode::get(getLLVMContext(), {}));
1003   }
1004 
1005   // If we are checking function types, emit a function type signature as
1006   // prologue data.
1007   if (FD && SanOpts.has(SanitizerKind::Function)) {
1008     if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1009       llvm::LLVMContext &Ctx = Fn->getContext();
1010       llvm::MDBuilder MDB(Ctx);
1011       Fn->setMetadata(
1012           llvm::LLVMContext::MD_func_sanitize,
1013           MDB.createRTTIPointerPrologue(
1014               PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1015     }
1016   }
1017 
1018   // If we're checking nullability, we need to know whether we can check the
1019   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1020   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1021     auto Nullability = FnRetTy->getNullability();
1022     if (Nullability && *Nullability == NullabilityKind::NonNull &&
1023         !FnRetTy->isRecordType()) {
1024       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1025             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1026         RetValNullabilityPrecondition =
1027             llvm::ConstantInt::getTrue(getLLVMContext());
1028     }
1029   }
1030 
1031   // If we're in C++ mode and the function name is "main", it is guaranteed
1032   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1033   // used within a program").
1034   //
1035   // OpenCL C 2.0 v2.2-11 s6.9.i:
1036   //     Recursion is not supported.
1037   //
1038   // SYCL v1.2.1 s3.10:
1039   //     kernels cannot include RTTI information, exception classes,
1040   //     recursive code, virtual functions or make use of C++ libraries that
1041   //     are not compiled for the device.
1042   if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
1043              getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
1044              (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1045     Fn->addFnAttr(llvm::Attribute::NoRecurse);
1046 
1047   llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1048   llvm::fp::ExceptionBehavior FPExceptionBehavior =
1049       ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1050   Builder.setDefaultConstrainedRounding(RM);
1051   Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1052   if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1053       (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1054                RM != llvm::RoundingMode::NearestTiesToEven))) {
1055     Builder.setIsFPConstrained(true);
1056     Fn->addFnAttr(llvm::Attribute::StrictFP);
1057   }
1058 
1059   // If a custom alignment is used, force realigning to this alignment on
1060   // any main function which certainly will need it.
1061   if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1062              CGM.getCodeGenOpts().StackAlignment))
1063     Fn->addFnAttr("stackrealign");
1064 
1065   // "main" doesn't need to zero out call-used registers.
1066   if (FD && FD->isMain())
1067     Fn->removeFnAttr("zero-call-used-regs");
1068 
1069   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1070 
1071   // Create a marker to make it easy to insert allocas into the entryblock
1072   // later.  Don't create this with the builder, because we don't want it
1073   // folded.
1074   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
1075   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
1076 
1077   ReturnBlock = getJumpDestInCurrentScope("return");
1078 
1079   Builder.SetInsertPoint(EntryBB);
1080 
1081   // If we're checking the return value, allocate space for a pointer to a
1082   // precise source location of the checked return statement.
1083   if (requiresReturnValueCheck()) {
1084     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1085     Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1086                         ReturnLocation);
1087   }
1088 
1089   // Emit subprogram debug descriptor.
1090   if (CGDebugInfo *DI = getDebugInfo()) {
1091     // Reconstruct the type from the argument list so that implicit parameters,
1092     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1093     // convention.
1094     DI->emitFunctionStart(GD, Loc, StartLoc,
1095                           DI->getFunctionType(FD, RetTy, Args), CurFn,
1096                           CurFuncIsThunk);
1097   }
1098 
1099   if (ShouldInstrumentFunction()) {
1100     if (CGM.getCodeGenOpts().InstrumentFunctions)
1101       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1102     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1103       CurFn->addFnAttr("instrument-function-entry-inlined",
1104                        "__cyg_profile_func_enter");
1105     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1106       CurFn->addFnAttr("instrument-function-entry-inlined",
1107                        "__cyg_profile_func_enter_bare");
1108   }
1109 
1110   // Since emitting the mcount call here impacts optimizations such as function
1111   // inlining, we just add an attribute to insert a mcount call in backend.
1112   // The attribute "counting-function" is set to mcount function name which is
1113   // architecture dependent.
1114   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1115     // Calls to fentry/mcount should not be generated if function has
1116     // the no_instrument_function attribute.
1117     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1118       if (CGM.getCodeGenOpts().CallFEntry)
1119         Fn->addFnAttr("fentry-call", "true");
1120       else {
1121         Fn->addFnAttr("instrument-function-entry-inlined",
1122                       getTarget().getMCountName());
1123       }
1124       if (CGM.getCodeGenOpts().MNopMCount) {
1125         if (!CGM.getCodeGenOpts().CallFEntry)
1126           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1127             << "-mnop-mcount" << "-mfentry";
1128         Fn->addFnAttr("mnop-mcount");
1129       }
1130 
1131       if (CGM.getCodeGenOpts().RecordMCount) {
1132         if (!CGM.getCodeGenOpts().CallFEntry)
1133           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1134             << "-mrecord-mcount" << "-mfentry";
1135         Fn->addFnAttr("mrecord-mcount");
1136       }
1137     }
1138   }
1139 
1140   if (CGM.getCodeGenOpts().PackedStack) {
1141     if (getContext().getTargetInfo().getTriple().getArch() !=
1142         llvm::Triple::systemz)
1143       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1144         << "-mpacked-stack";
1145     Fn->addFnAttr("packed-stack");
1146   }
1147 
1148   if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1149       !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1150     Fn->addFnAttr("warn-stack-size",
1151                   std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1152 
1153   if (RetTy->isVoidType()) {
1154     // Void type; nothing to return.
1155     ReturnValue = Address::invalid();
1156 
1157     // Count the implicit return.
1158     if (!endsWithReturn(D))
1159       ++NumReturnExprs;
1160   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1161     // Indirect return; emit returned value directly into sret slot.
1162     // This reduces code size, and affects correctness in C++.
1163     auto AI = CurFn->arg_begin();
1164     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1165       ++AI;
1166     ReturnValue = makeNaturalAddressForPointer(
1167         &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1168         nullptr, nullptr, KnownNonNull);
1169     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1170       ReturnValuePointer =
1171           CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1172       Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1173                           ReturnValuePointer);
1174     }
1175   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1176              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1177     // Load the sret pointer from the argument struct and return into that.
1178     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1179     llvm::Function::arg_iterator EI = CurFn->arg_end();
1180     --EI;
1181     llvm::Value *Addr = Builder.CreateStructGEP(
1182         CurFnInfo->getArgStruct(), &*EI, Idx);
1183     llvm::Type *Ty =
1184         cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1185     ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1186     Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1187     ReturnValue = Address(Addr, ConvertType(RetTy),
1188                           CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1189   } else {
1190     ReturnValue = CreateIRTemp(RetTy, "retval");
1191 
1192     // Tell the epilog emitter to autorelease the result.  We do this
1193     // now so that various specialized functions can suppress it
1194     // during their IR-generation.
1195     if (getLangOpts().ObjCAutoRefCount &&
1196         !CurFnInfo->isReturnsRetained() &&
1197         RetTy->isObjCRetainableType())
1198       AutoreleaseResult = true;
1199   }
1200 
1201   EmitStartEHSpec(CurCodeDecl);
1202 
1203   PrologueCleanupDepth = EHStack.stable_begin();
1204 
1205   // Emit OpenMP specific initialization of the device functions.
1206   if (getLangOpts().OpenMP && CurCodeDecl)
1207     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1208 
1209   // Handle emitting HLSL entry functions.
1210   if (D && D->hasAttr<HLSLShaderAttr>())
1211     CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1212 
1213   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1214 
1215   if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1216       MD && !MD->isStatic()) {
1217     bool IsInLambda =
1218         MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1219     if (MD->isImplicitObjectMemberFunction())
1220       CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1221     if (IsInLambda) {
1222       // We're in a lambda; figure out the captures.
1223       MD->getParent()->getCaptureFields(LambdaCaptureFields,
1224                                         LambdaThisCaptureField);
1225       if (LambdaThisCaptureField) {
1226         // If the lambda captures the object referred to by '*this' - either by
1227         // value or by reference, make sure CXXThisValue points to the correct
1228         // object.
1229 
1230         // Get the lvalue for the field (which is a copy of the enclosing object
1231         // or contains the address of the enclosing object).
1232         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1233         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1234           // If the enclosing object was captured by value, just use its
1235           // address. Sign this pointer.
1236           CXXThisValue = ThisFieldLValue.getPointer(*this);
1237         } else {
1238           // Load the lvalue pointed to by the field, since '*this' was captured
1239           // by reference.
1240           CXXThisValue =
1241               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1242         }
1243       }
1244       for (auto *FD : MD->getParent()->fields()) {
1245         if (FD->hasCapturedVLAType()) {
1246           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1247                                            SourceLocation()).getScalarVal();
1248           auto VAT = FD->getCapturedVLAType();
1249           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1250         }
1251       }
1252     } else if (MD->isImplicitObjectMemberFunction()) {
1253       // Not in a lambda; just use 'this' from the method.
1254       // FIXME: Should we generate a new load for each use of 'this'?  The
1255       // fast register allocator would be happier...
1256       CXXThisValue = CXXABIThisValue;
1257     }
1258 
1259     // Check the 'this' pointer once per function, if it's available.
1260     if (CXXABIThisValue) {
1261       SanitizerSet SkippedChecks;
1262       SkippedChecks.set(SanitizerKind::ObjectSize, true);
1263       QualType ThisTy = MD->getThisType();
1264 
1265       // If this is the call operator of a lambda with no captures, it
1266       // may have a static invoker function, which may call this operator with
1267       // a null 'this' pointer.
1268       if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda())
1269         SkippedChecks.set(SanitizerKind::Null, true);
1270 
1271       EmitTypeCheck(
1272           isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1273           Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1274     }
1275   }
1276 
1277   // If any of the arguments have a variably modified type, make sure to
1278   // emit the type size, but only if the function is not naked. Naked functions
1279   // have no prolog to run this evaluation.
1280   if (!FD || !FD->hasAttr<NakedAttr>()) {
1281     for (const VarDecl *VD : Args) {
1282       // Dig out the type as written from ParmVarDecls; it's unclear whether
1283       // the standard (C99 6.9.1p10) requires this, but we're following the
1284       // precedent set by gcc.
1285       QualType Ty;
1286       if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1287         Ty = PVD->getOriginalType();
1288       else
1289         Ty = VD->getType();
1290 
1291       if (Ty->isVariablyModifiedType())
1292         EmitVariablyModifiedType(Ty);
1293     }
1294   }
1295   // Emit a location at the end of the prologue.
1296   if (CGDebugInfo *DI = getDebugInfo())
1297     DI->EmitLocation(Builder, StartLoc);
1298   // TODO: Do we need to handle this in two places like we do with
1299   // target-features/target-cpu?
1300   if (CurFuncDecl)
1301     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1302       LargestVectorWidth = VecWidth->getVectorWidth();
1303 
1304   if (CGM.shouldEmitConvergenceTokens())
1305     ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1306 }
1307 
1308 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1309   incrementProfileCounter(Body);
1310   maybeCreateMCDCCondBitmap();
1311   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1312     EmitCompoundStmtWithoutScope(*S);
1313   else
1314     EmitStmt(Body);
1315 }
1316 
1317 /// When instrumenting to collect profile data, the counts for some blocks
1318 /// such as switch cases need to not include the fall-through counts, so
1319 /// emit a branch around the instrumentation code. When not instrumenting,
1320 /// this just calls EmitBlock().
1321 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1322                                                const Stmt *S) {
1323   llvm::BasicBlock *SkipCountBB = nullptr;
1324   // Do not skip over the instrumentation when single byte coverage mode is
1325   // enabled.
1326   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1327       !llvm::EnableSingleByteCoverage) {
1328     // When instrumenting for profiling, the fallthrough to certain
1329     // statements needs to skip over the instrumentation code so that we
1330     // get an accurate count.
1331     SkipCountBB = createBasicBlock("skipcount");
1332     EmitBranch(SkipCountBB);
1333   }
1334   EmitBlock(BB);
1335   uint64_t CurrentCount = getCurrentProfileCount();
1336   incrementProfileCounter(S);
1337   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1338   if (SkipCountBB)
1339     EmitBlock(SkipCountBB);
1340 }
1341 
1342 /// Tries to mark the given function nounwind based on the
1343 /// non-existence of any throwing calls within it.  We believe this is
1344 /// lightweight enough to do at -O0.
1345 static void TryMarkNoThrow(llvm::Function *F) {
1346   // LLVM treats 'nounwind' on a function as part of the type, so we
1347   // can't do this on functions that can be overwritten.
1348   if (F->isInterposable()) return;
1349 
1350   for (llvm::BasicBlock &BB : *F)
1351     for (llvm::Instruction &I : BB)
1352       if (I.mayThrow())
1353         return;
1354 
1355   F->setDoesNotThrow();
1356 }
1357 
1358 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1359                                                FunctionArgList &Args) {
1360   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1361   QualType ResTy = FD->getReturnType();
1362 
1363   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1364   if (MD && MD->isImplicitObjectMemberFunction()) {
1365     if (CGM.getCXXABI().HasThisReturn(GD))
1366       ResTy = MD->getThisType();
1367     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1368       ResTy = CGM.getContext().VoidPtrTy;
1369     CGM.getCXXABI().buildThisParam(*this, Args);
1370   }
1371 
1372   // The base version of an inheriting constructor whose constructed base is a
1373   // virtual base is not passed any arguments (because it doesn't actually call
1374   // the inherited constructor).
1375   bool PassedParams = true;
1376   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1377     if (auto Inherited = CD->getInheritedConstructor())
1378       PassedParams =
1379           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1380 
1381   if (PassedParams) {
1382     for (auto *Param : FD->parameters()) {
1383       Args.push_back(Param);
1384       if (!Param->hasAttr<PassObjectSizeAttr>())
1385         continue;
1386 
1387       auto *Implicit = ImplicitParamDecl::Create(
1388           getContext(), Param->getDeclContext(), Param->getLocation(),
1389           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1390       SizeArguments[Param] = Implicit;
1391       Args.push_back(Implicit);
1392     }
1393   }
1394 
1395   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1396     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1397 
1398   return ResTy;
1399 }
1400 
1401 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1402                                    const CGFunctionInfo &FnInfo) {
1403   assert(Fn && "generating code for null Function");
1404   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1405   CurGD = GD;
1406 
1407   FunctionArgList Args;
1408   QualType ResTy = BuildFunctionArgList(GD, Args);
1409 
1410   CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1411 
1412   if (FD->isInlineBuiltinDeclaration()) {
1413     // When generating code for a builtin with an inline declaration, use a
1414     // mangled name to hold the actual body, while keeping an external
1415     // definition in case the function pointer is referenced somewhere.
1416     std::string FDInlineName = (Fn->getName() + ".inline").str();
1417     llvm::Module *M = Fn->getParent();
1418     llvm::Function *Clone = M->getFunction(FDInlineName);
1419     if (!Clone) {
1420       Clone = llvm::Function::Create(Fn->getFunctionType(),
1421                                      llvm::GlobalValue::InternalLinkage,
1422                                      Fn->getAddressSpace(), FDInlineName, M);
1423       Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1424     }
1425     Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1426     Fn = Clone;
1427   } else {
1428     // Detect the unusual situation where an inline version is shadowed by a
1429     // non-inline version. In that case we should pick the external one
1430     // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1431     // to detect that situation before we reach codegen, so do some late
1432     // replacement.
1433     for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1434          PD = PD->getPreviousDecl()) {
1435       if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1436         std::string FDInlineName = (Fn->getName() + ".inline").str();
1437         llvm::Module *M = Fn->getParent();
1438         if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1439           Clone->replaceAllUsesWith(Fn);
1440           Clone->eraseFromParent();
1441         }
1442         break;
1443       }
1444     }
1445   }
1446 
1447   // Check if we should generate debug info for this function.
1448   if (FD->hasAttr<NoDebugAttr>()) {
1449     // Clear non-distinct debug info that was possibly attached to the function
1450     // due to an earlier declaration without the nodebug attribute
1451     Fn->setSubprogram(nullptr);
1452     // Disable debug info indefinitely for this function
1453     DebugInfo = nullptr;
1454   }
1455 
1456   // The function might not have a body if we're generating thunks for a
1457   // function declaration.
1458   SourceRange BodyRange;
1459   if (Stmt *Body = FD->getBody())
1460     BodyRange = Body->getSourceRange();
1461   else
1462     BodyRange = FD->getLocation();
1463   CurEHLocation = BodyRange.getEnd();
1464 
1465   // Use the location of the start of the function to determine where
1466   // the function definition is located. By default use the location
1467   // of the declaration as the location for the subprogram. A function
1468   // may lack a declaration in the source code if it is created by code
1469   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1470   SourceLocation Loc = FD->getLocation();
1471 
1472   // If this is a function specialization then use the pattern body
1473   // as the location for the function.
1474   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1475     if (SpecDecl->hasBody(SpecDecl))
1476       Loc = SpecDecl->getLocation();
1477 
1478   Stmt *Body = FD->getBody();
1479 
1480   if (Body) {
1481     // Coroutines always emit lifetime markers.
1482     if (isa<CoroutineBodyStmt>(Body))
1483       ShouldEmitLifetimeMarkers = true;
1484 
1485     // Initialize helper which will detect jumps which can cause invalid
1486     // lifetime markers.
1487     if (ShouldEmitLifetimeMarkers)
1488       Bypasses.Init(Body);
1489   }
1490 
1491   // Emit the standard function prologue.
1492   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1493 
1494   // Save parameters for coroutine function.
1495   if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1496     llvm::append_range(FnArgs, FD->parameters());
1497 
1498   // Ensure that the function adheres to the forward progress guarantee, which
1499   // is required by certain optimizations.
1500   // In C++11 and up, the attribute will be removed if the body contains a
1501   // trivial empty loop.
1502   if (checkIfFunctionMustProgress())
1503     CurFn->addFnAttr(llvm::Attribute::MustProgress);
1504 
1505   // Generate the body of the function.
1506   PGO.assignRegionCounters(GD, CurFn);
1507   if (isa<CXXDestructorDecl>(FD))
1508     EmitDestructorBody(Args);
1509   else if (isa<CXXConstructorDecl>(FD))
1510     EmitConstructorBody(Args);
1511   else if (getLangOpts().CUDA &&
1512            !getLangOpts().CUDAIsDevice &&
1513            FD->hasAttr<CUDAGlobalAttr>())
1514     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1515   else if (isa<CXXMethodDecl>(FD) &&
1516            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1517     // The lambda static invoker function is special, because it forwards or
1518     // clones the body of the function call operator (but is actually static).
1519     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1520   } else if (isa<CXXMethodDecl>(FD) &&
1521              isLambdaCallOperator(cast<CXXMethodDecl>(FD)) &&
1522              !FnInfo.isDelegateCall() &&
1523              cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1524              hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1525     // If emitting a lambda with static invoker on X86 Windows, change
1526     // the call operator body.
1527     // Make sure that this is a call operator with an inalloca arg and check
1528     // for delegate call to make sure this is the original call op and not the
1529     // new forwarding function for the static invoker.
1530     EmitLambdaInAllocaCallOpBody(cast<CXXMethodDecl>(FD));
1531   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1532              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1533               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1534     // Implicit copy-assignment gets the same special treatment as implicit
1535     // copy-constructors.
1536     emitImplicitAssignmentOperatorBody(Args);
1537   } else if (Body) {
1538     EmitFunctionBody(Body);
1539   } else
1540     llvm_unreachable("no definition for emitted function");
1541 
1542   // C++11 [stmt.return]p2:
1543   //   Flowing off the end of a function [...] results in undefined behavior in
1544   //   a value-returning function.
1545   // C11 6.9.1p12:
1546   //   If the '}' that terminates a function is reached, and the value of the
1547   //   function call is used by the caller, the behavior is undefined.
1548   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1549       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1550     bool ShouldEmitUnreachable =
1551         CGM.getCodeGenOpts().StrictReturn ||
1552         !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1553     if (SanOpts.has(SanitizerKind::Return)) {
1554       SanitizerScope SanScope(this);
1555       llvm::Value *IsFalse = Builder.getFalse();
1556       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1557                 SanitizerHandler::MissingReturn,
1558                 EmitCheckSourceLocation(FD->getLocation()), std::nullopt);
1559     } else if (ShouldEmitUnreachable) {
1560       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1561         EmitTrapCall(llvm::Intrinsic::trap);
1562     }
1563     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1564       Builder.CreateUnreachable();
1565       Builder.ClearInsertionPoint();
1566     }
1567   }
1568 
1569   // Emit the standard function epilogue.
1570   FinishFunction(BodyRange.getEnd());
1571 
1572   // If we haven't marked the function nothrow through other means, do
1573   // a quick pass now to see if we can.
1574   if (!CurFn->doesNotThrow())
1575     TryMarkNoThrow(CurFn);
1576 }
1577 
1578 /// ContainsLabel - Return true if the statement contains a label in it.  If
1579 /// this statement is not executed normally, it not containing a label means
1580 /// that we can just remove the code.
1581 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1582   // Null statement, not a label!
1583   if (!S) return false;
1584 
1585   // If this is a label, we have to emit the code, consider something like:
1586   // if (0) {  ...  foo:  bar(); }  goto foo;
1587   //
1588   // TODO: If anyone cared, we could track __label__'s, since we know that you
1589   // can't jump to one from outside their declared region.
1590   if (isa<LabelStmt>(S))
1591     return true;
1592 
1593   // If this is a case/default statement, and we haven't seen a switch, we have
1594   // to emit the code.
1595   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1596     return true;
1597 
1598   // If this is a switch statement, we want to ignore cases below it.
1599   if (isa<SwitchStmt>(S))
1600     IgnoreCaseStmts = true;
1601 
1602   // Scan subexpressions for verboten labels.
1603   for (const Stmt *SubStmt : S->children())
1604     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1605       return true;
1606 
1607   return false;
1608 }
1609 
1610 /// containsBreak - Return true if the statement contains a break out of it.
1611 /// If the statement (recursively) contains a switch or loop with a break
1612 /// inside of it, this is fine.
1613 bool CodeGenFunction::containsBreak(const Stmt *S) {
1614   // Null statement, not a label!
1615   if (!S) return false;
1616 
1617   // If this is a switch or loop that defines its own break scope, then we can
1618   // include it and anything inside of it.
1619   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1620       isa<ForStmt>(S))
1621     return false;
1622 
1623   if (isa<BreakStmt>(S))
1624     return true;
1625 
1626   // Scan subexpressions for verboten breaks.
1627   for (const Stmt *SubStmt : S->children())
1628     if (containsBreak(SubStmt))
1629       return true;
1630 
1631   return false;
1632 }
1633 
1634 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1635   if (!S) return false;
1636 
1637   // Some statement kinds add a scope and thus never add a decl to the current
1638   // scope. Note, this list is longer than the list of statements that might
1639   // have an unscoped decl nested within them, but this way is conservatively
1640   // correct even if more statement kinds are added.
1641   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1642       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1643       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1644       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1645     return false;
1646 
1647   if (isa<DeclStmt>(S))
1648     return true;
1649 
1650   for (const Stmt *SubStmt : S->children())
1651     if (mightAddDeclToScope(SubStmt))
1652       return true;
1653 
1654   return false;
1655 }
1656 
1657 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1658 /// to a constant, or if it does but contains a label, return false.  If it
1659 /// constant folds return true and set the boolean result in Result.
1660 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1661                                                    bool &ResultBool,
1662                                                    bool AllowLabels) {
1663   // If MC/DC is enabled, disable folding so that we can instrument all
1664   // conditions to yield complete test vectors. We still keep track of
1665   // folded conditions during region mapping and visualization.
1666   if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1667       CGM.getCodeGenOpts().MCDCCoverage)
1668     return false;
1669 
1670   llvm::APSInt ResultInt;
1671   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1672     return false;
1673 
1674   ResultBool = ResultInt.getBoolValue();
1675   return true;
1676 }
1677 
1678 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1679 /// to a constant, or if it does but contains a label, return false.  If it
1680 /// constant folds return true and set the folded value.
1681 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1682                                                    llvm::APSInt &ResultInt,
1683                                                    bool AllowLabels) {
1684   // FIXME: Rename and handle conversion of other evaluatable things
1685   // to bool.
1686   Expr::EvalResult Result;
1687   if (!Cond->EvaluateAsInt(Result, getContext()))
1688     return false;  // Not foldable, not integer or not fully evaluatable.
1689 
1690   llvm::APSInt Int = Result.Val.getInt();
1691   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1692     return false;  // Contains a label.
1693 
1694   ResultInt = Int;
1695   return true;
1696 }
1697 
1698 /// Strip parentheses and simplistic logical-NOT operators.
1699 const Expr *CodeGenFunction::stripCond(const Expr *C) {
1700   while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) {
1701     if (Op->getOpcode() != UO_LNot)
1702       break;
1703     C = Op->getSubExpr();
1704   }
1705   return C->IgnoreParens();
1706 }
1707 
1708 /// Determine whether the given condition is an instrumentable condition
1709 /// (i.e. no "&&" or "||").
1710 bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1711   const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1712   return (!BOp || !BOp->isLogicalOp());
1713 }
1714 
1715 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1716 /// increments a profile counter based on the semantics of the given logical
1717 /// operator opcode.  This is used to instrument branch condition coverage for
1718 /// logical operators.
1719 void CodeGenFunction::EmitBranchToCounterBlock(
1720     const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1721     llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1722     Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1723   // If not instrumenting, just emit a branch.
1724   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1725   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1726     return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1727 
1728   llvm::BasicBlock *ThenBlock = nullptr;
1729   llvm::BasicBlock *ElseBlock = nullptr;
1730   llvm::BasicBlock *NextBlock = nullptr;
1731 
1732   // Create the block we'll use to increment the appropriate counter.
1733   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1734 
1735   // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1736   // means we need to evaluate the condition and increment the counter on TRUE:
1737   //
1738   // if (Cond)
1739   //   goto CounterIncrBlock;
1740   // else
1741   //   goto FalseBlock;
1742   //
1743   // CounterIncrBlock:
1744   //   Counter++;
1745   //   goto TrueBlock;
1746 
1747   if (LOp == BO_LAnd) {
1748     ThenBlock = CounterIncrBlock;
1749     ElseBlock = FalseBlock;
1750     NextBlock = TrueBlock;
1751   }
1752 
1753   // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1754   // we need to evaluate the condition and increment the counter on FALSE:
1755   //
1756   // if (Cond)
1757   //   goto TrueBlock;
1758   // else
1759   //   goto CounterIncrBlock;
1760   //
1761   // CounterIncrBlock:
1762   //   Counter++;
1763   //   goto FalseBlock;
1764 
1765   else if (LOp == BO_LOr) {
1766     ThenBlock = TrueBlock;
1767     ElseBlock = CounterIncrBlock;
1768     NextBlock = FalseBlock;
1769   } else {
1770     llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1771   }
1772 
1773   // Emit Branch based on condition.
1774   EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1775 
1776   // Emit the block containing the counter increment(s).
1777   EmitBlock(CounterIncrBlock);
1778 
1779   // Increment corresponding counter; if index not provided, use Cond as index.
1780   incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1781 
1782   // Go to the next block.
1783   EmitBranch(NextBlock);
1784 }
1785 
1786 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1787 /// statement) to the specified blocks.  Based on the condition, this might try
1788 /// to simplify the codegen of the conditional based on the branch.
1789 /// \param LH The value of the likelihood attribute on the True branch.
1790 /// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1791 /// ConditionalOperator (ternary) through a recursive call for the operator's
1792 /// LHS and RHS nodes.
1793 void CodeGenFunction::EmitBranchOnBoolExpr(
1794     const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1795     uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp) {
1796   Cond = Cond->IgnoreParens();
1797 
1798   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1799     // Handle X && Y in a condition.
1800     if (CondBOp->getOpcode() == BO_LAnd) {
1801       MCDCLogOpStack.push_back(CondBOp);
1802 
1803       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1804       // folded if the case was simple enough.
1805       bool ConstantBool = false;
1806       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1807           ConstantBool) {
1808         // br(1 && X) -> br(X).
1809         incrementProfileCounter(CondBOp);
1810         EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1811                                  FalseBlock, TrueCount, LH);
1812         MCDCLogOpStack.pop_back();
1813         return;
1814       }
1815 
1816       // If we have "X && 1", simplify the code to use an uncond branch.
1817       // "X && 0" would have been constant folded to 0.
1818       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1819           ConstantBool) {
1820         // br(X && 1) -> br(X).
1821         EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1822                                  FalseBlock, TrueCount, LH, CondBOp);
1823         MCDCLogOpStack.pop_back();
1824         return;
1825       }
1826 
1827       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1828       // want to jump to the FalseBlock.
1829       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1830       // The counter tells us how often we evaluate RHS, and all of TrueCount
1831       // can be propagated to that branch.
1832       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1833 
1834       ConditionalEvaluation eval(*this);
1835       {
1836         ApplyDebugLocation DL(*this, Cond);
1837         // Propagate the likelihood attribute like __builtin_expect
1838         // __builtin_expect(X && Y, 1) -> X and Y are likely
1839         // __builtin_expect(X && Y, 0) -> only Y is unlikely
1840         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1841                              LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1842         EmitBlock(LHSTrue);
1843       }
1844 
1845       incrementProfileCounter(CondBOp);
1846       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1847 
1848       // Any temporaries created here are conditional.
1849       eval.begin(*this);
1850       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1851                                FalseBlock, TrueCount, LH);
1852       eval.end(*this);
1853       MCDCLogOpStack.pop_back();
1854       return;
1855     }
1856 
1857     if (CondBOp->getOpcode() == BO_LOr) {
1858       MCDCLogOpStack.push_back(CondBOp);
1859 
1860       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1861       // folded if the case was simple enough.
1862       bool ConstantBool = false;
1863       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1864           !ConstantBool) {
1865         // br(0 || X) -> br(X).
1866         incrementProfileCounter(CondBOp);
1867         EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1868                                  FalseBlock, TrueCount, LH);
1869         MCDCLogOpStack.pop_back();
1870         return;
1871       }
1872 
1873       // If we have "X || 0", simplify the code to use an uncond branch.
1874       // "X || 1" would have been constant folded to 1.
1875       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1876           !ConstantBool) {
1877         // br(X || 0) -> br(X).
1878         EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1879                                  FalseBlock, TrueCount, LH, CondBOp);
1880         MCDCLogOpStack.pop_back();
1881         return;
1882       }
1883       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1884       // want to jump to the TrueBlock.
1885       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1886       // We have the count for entry to the RHS and for the whole expression
1887       // being true, so we can divy up True count between the short circuit and
1888       // the RHS.
1889       uint64_t LHSCount =
1890           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1891       uint64_t RHSCount = TrueCount - LHSCount;
1892 
1893       ConditionalEvaluation eval(*this);
1894       {
1895         // Propagate the likelihood attribute like __builtin_expect
1896         // __builtin_expect(X || Y, 1) -> only Y is likely
1897         // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1898         ApplyDebugLocation DL(*this, Cond);
1899         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1900                              LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1901         EmitBlock(LHSFalse);
1902       }
1903 
1904       incrementProfileCounter(CondBOp);
1905       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1906 
1907       // Any temporaries created here are conditional.
1908       eval.begin(*this);
1909       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1910                                RHSCount, LH);
1911 
1912       eval.end(*this);
1913       MCDCLogOpStack.pop_back();
1914       return;
1915     }
1916   }
1917 
1918   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1919     // br(!x, t, f) -> br(x, f, t)
1920     // Avoid doing this optimization when instrumenting a condition for MC/DC.
1921     // LNot is taken as part of the condition for simplicity, and changing its
1922     // sense negatively impacts test vector tracking.
1923     bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
1924                          CGM.getCodeGenOpts().MCDCCoverage &&
1925                          isInstrumentedCondition(Cond);
1926     if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
1927       // Negate the count.
1928       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1929       // The values of the enum are chosen to make this negation possible.
1930       LH = static_cast<Stmt::Likelihood>(-LH);
1931       // Negate the condition and swap the destination blocks.
1932       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1933                                   FalseCount, LH);
1934     }
1935   }
1936 
1937   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1938     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1939     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1940     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1941 
1942     // The ConditionalOperator itself has no likelihood information for its
1943     // true and false branches. This matches the behavior of __builtin_expect.
1944     ConditionalEvaluation cond(*this);
1945     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1946                          getProfileCount(CondOp), Stmt::LH_None);
1947 
1948     // When computing PGO branch weights, we only know the overall count for
1949     // the true block. This code is essentially doing tail duplication of the
1950     // naive code-gen, introducing new edges for which counts are not
1951     // available. Divide the counts proportionally between the LHS and RHS of
1952     // the conditional operator.
1953     uint64_t LHSScaledTrueCount = 0;
1954     if (TrueCount) {
1955       double LHSRatio =
1956           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1957       LHSScaledTrueCount = TrueCount * LHSRatio;
1958     }
1959 
1960     cond.begin(*this);
1961     EmitBlock(LHSBlock);
1962     incrementProfileCounter(CondOp);
1963     {
1964       ApplyDebugLocation DL(*this, Cond);
1965       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1966                            LHSScaledTrueCount, LH, CondOp);
1967     }
1968     cond.end(*this);
1969 
1970     cond.begin(*this);
1971     EmitBlock(RHSBlock);
1972     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1973                          TrueCount - LHSScaledTrueCount, LH, CondOp);
1974     cond.end(*this);
1975 
1976     return;
1977   }
1978 
1979   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1980     // Conditional operator handling can give us a throw expression as a
1981     // condition for a case like:
1982     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1983     // Fold this to:
1984     //   br(c, throw x, br(y, t, f))
1985     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1986     return;
1987   }
1988 
1989   // Emit the code with the fully general case.
1990   llvm::Value *CondV;
1991   {
1992     ApplyDebugLocation DL(*this, Cond);
1993     CondV = EvaluateExprAsBool(Cond);
1994   }
1995 
1996   // If not at the top of the logical operator nest, update MCDC temp with the
1997   // boolean result of the evaluated condition.
1998   if (!MCDCLogOpStack.empty()) {
1999     const Expr *MCDCBaseExpr = Cond;
2000     // When a nested ConditionalOperator (ternary) is encountered in a boolean
2001     // expression, MC/DC tracks the result of the ternary, and this is tied to
2002     // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2003     // this is the case, the ConditionalOperator expression is passed through
2004     // the ConditionalOp parameter and then used as the MCDC base expression.
2005     if (ConditionalOp)
2006       MCDCBaseExpr = ConditionalOp;
2007 
2008     maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2009   }
2010 
2011   llvm::MDNode *Weights = nullptr;
2012   llvm::MDNode *Unpredictable = nullptr;
2013 
2014   // If the branch has a condition wrapped by __builtin_unpredictable,
2015   // create metadata that specifies that the branch is unpredictable.
2016   // Don't bother if not optimizing because that metadata would not be used.
2017   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2018   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2019     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2020     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2021       llvm::MDBuilder MDHelper(getLLVMContext());
2022       Unpredictable = MDHelper.createUnpredictable();
2023     }
2024   }
2025 
2026   // If there is a Likelihood knowledge for the cond, lower it.
2027   // Note that if not optimizing this won't emit anything.
2028   llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2029   if (CondV != NewCondV)
2030     CondV = NewCondV;
2031   else {
2032     // Otherwise, lower profile counts. Note that we do this even at -O0.
2033     uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2034     Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2035   }
2036 
2037   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
2038 }
2039 
2040 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2041 /// specified stmt yet.
2042 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2043   CGM.ErrorUnsupported(S, Type);
2044 }
2045 
2046 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
2047 /// variable-length array whose elements have a non-zero bit-pattern.
2048 ///
2049 /// \param baseType the inner-most element type of the array
2050 /// \param src - a char* pointing to the bit-pattern for a single
2051 /// base element of the array
2052 /// \param sizeInChars - the total size of the VLA, in chars
2053 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
2054                                Address dest, Address src,
2055                                llvm::Value *sizeInChars) {
2056   CGBuilderTy &Builder = CGF.Builder;
2057 
2058   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2059   llvm::Value *baseSizeInChars
2060     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2061 
2062   Address begin = dest.withElementType(CGF.Int8Ty);
2063   llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2064                                                begin.emitRawPointer(CGF),
2065                                                sizeInChars, "vla.end");
2066 
2067   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2068   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2069   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2070 
2071   // Make a loop over the VLA.  C99 guarantees that the VLA element
2072   // count must be nonzero.
2073   CGF.EmitBlock(loopBB);
2074 
2075   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2076   cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2077 
2078   CharUnits curAlign =
2079     dest.getAlignment().alignmentOfArrayElement(baseSize);
2080 
2081   // memcpy the individual element bit-pattern.
2082   Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2083                        /*volatile*/ false);
2084 
2085   // Go to the next element.
2086   llvm::Value *next =
2087     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2088 
2089   // Leave if that's the end of the VLA.
2090   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2091   Builder.CreateCondBr(done, contBB, loopBB);
2092   cur->addIncoming(next, loopBB);
2093 
2094   CGF.EmitBlock(contBB);
2095 }
2096 
2097 void
2098 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
2099   // Ignore empty classes in C++.
2100   if (getLangOpts().CPlusPlus) {
2101     if (const RecordType *RT = Ty->getAs<RecordType>()) {
2102       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
2103         return;
2104     }
2105   }
2106 
2107   if (DestPtr.getElementType() != Int8Ty)
2108     DestPtr = DestPtr.withElementType(Int8Ty);
2109 
2110   // Get size and alignment info for this aggregate.
2111   CharUnits size = getContext().getTypeSizeInChars(Ty);
2112 
2113   llvm::Value *SizeVal;
2114   const VariableArrayType *vla;
2115 
2116   // Don't bother emitting a zero-byte memset.
2117   if (size.isZero()) {
2118     // But note that getTypeInfo returns 0 for a VLA.
2119     if (const VariableArrayType *vlaType =
2120           dyn_cast_or_null<VariableArrayType>(
2121                                           getContext().getAsArrayType(Ty))) {
2122       auto VlaSize = getVLASize(vlaType);
2123       SizeVal = VlaSize.NumElts;
2124       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2125       if (!eltSize.isOne())
2126         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2127       vla = vlaType;
2128     } else {
2129       return;
2130     }
2131   } else {
2132     SizeVal = CGM.getSize(size);
2133     vla = nullptr;
2134   }
2135 
2136   // If the type contains a pointer to data member we can't memset it to zero.
2137   // Instead, create a null constant and copy it to the destination.
2138   // TODO: there are other patterns besides zero that we can usefully memset,
2139   // like -1, which happens to be the pattern used by member-pointers.
2140   if (!CGM.getTypes().isZeroInitializable(Ty)) {
2141     // For a VLA, emit a single element, then splat that over the VLA.
2142     if (vla) Ty = getContext().getBaseElementType(vla);
2143 
2144     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2145 
2146     llvm::GlobalVariable *NullVariable =
2147       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2148                                /*isConstant=*/true,
2149                                llvm::GlobalVariable::PrivateLinkage,
2150                                NullConstant, Twine());
2151     CharUnits NullAlign = DestPtr.getAlignment();
2152     NullVariable->setAlignment(NullAlign.getAsAlign());
2153     Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2154 
2155     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2156 
2157     // Get and call the appropriate llvm.memcpy overload.
2158     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2159     return;
2160   }
2161 
2162   // Otherwise, just memset the whole thing to zero.  This is legal
2163   // because in LLVM, all default initializers (other than the ones we just
2164   // handled above) are guaranteed to have a bit pattern of all zeros.
2165   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2166 }
2167 
2168 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2169   // Make sure that there is a block for the indirect goto.
2170   if (!IndirectBranch)
2171     GetIndirectGotoBlock();
2172 
2173   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2174 
2175   // Make sure the indirect branch includes all of the address-taken blocks.
2176   IndirectBranch->addDestination(BB);
2177   return llvm::BlockAddress::get(CurFn, BB);
2178 }
2179 
2180 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2181   // If we already made the indirect branch for indirect goto, return its block.
2182   if (IndirectBranch) return IndirectBranch->getParent();
2183 
2184   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2185 
2186   // Create the PHI node that indirect gotos will add entries to.
2187   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2188                                               "indirect.goto.dest");
2189 
2190   // Create the indirect branch instruction.
2191   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2192   return IndirectBranch->getParent();
2193 }
2194 
2195 /// Computes the length of an array in elements, as well as the base
2196 /// element type and a properly-typed first element pointer.
2197 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2198                                               QualType &baseType,
2199                                               Address &addr) {
2200   const ArrayType *arrayType = origArrayType;
2201 
2202   // If it's a VLA, we have to load the stored size.  Note that
2203   // this is the size of the VLA in bytes, not its size in elements.
2204   llvm::Value *numVLAElements = nullptr;
2205   if (isa<VariableArrayType>(arrayType)) {
2206     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2207 
2208     // Walk into all VLAs.  This doesn't require changes to addr,
2209     // which has type T* where T is the first non-VLA element type.
2210     do {
2211       QualType elementType = arrayType->getElementType();
2212       arrayType = getContext().getAsArrayType(elementType);
2213 
2214       // If we only have VLA components, 'addr' requires no adjustment.
2215       if (!arrayType) {
2216         baseType = elementType;
2217         return numVLAElements;
2218       }
2219     } while (isa<VariableArrayType>(arrayType));
2220 
2221     // We get out here only if we find a constant array type
2222     // inside the VLA.
2223   }
2224 
2225   // We have some number of constant-length arrays, so addr should
2226   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2227   // down to the first element of addr.
2228   SmallVector<llvm::Value*, 8> gepIndices;
2229 
2230   // GEP down to the array type.
2231   llvm::ConstantInt *zero = Builder.getInt32(0);
2232   gepIndices.push_back(zero);
2233 
2234   uint64_t countFromCLAs = 1;
2235   QualType eltType;
2236 
2237   llvm::ArrayType *llvmArrayType =
2238     dyn_cast<llvm::ArrayType>(addr.getElementType());
2239   while (llvmArrayType) {
2240     assert(isa<ConstantArrayType>(arrayType));
2241     assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2242            llvmArrayType->getNumElements());
2243 
2244     gepIndices.push_back(zero);
2245     countFromCLAs *= llvmArrayType->getNumElements();
2246     eltType = arrayType->getElementType();
2247 
2248     llvmArrayType =
2249       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2250     arrayType = getContext().getAsArrayType(arrayType->getElementType());
2251     assert((!llvmArrayType || arrayType) &&
2252            "LLVM and Clang types are out-of-synch");
2253   }
2254 
2255   if (arrayType) {
2256     // From this point onwards, the Clang array type has been emitted
2257     // as some other type (probably a packed struct). Compute the array
2258     // size, and just emit the 'begin' expression as a bitcast.
2259     while (arrayType) {
2260       countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2261       eltType = arrayType->getElementType();
2262       arrayType = getContext().getAsArrayType(eltType);
2263     }
2264 
2265     llvm::Type *baseType = ConvertType(eltType);
2266     addr = addr.withElementType(baseType);
2267   } else {
2268     // Create the actual GEP.
2269     addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2270                                              addr.emitRawPointer(*this),
2271                                              gepIndices, "array.begin"),
2272                    ConvertTypeForMem(eltType), addr.getAlignment());
2273   }
2274 
2275   baseType = eltType;
2276 
2277   llvm::Value *numElements
2278     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2279 
2280   // If we had any VLA dimensions, factor them in.
2281   if (numVLAElements)
2282     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2283 
2284   return numElements;
2285 }
2286 
2287 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2288   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2289   assert(vla && "type was not a variable array type!");
2290   return getVLASize(vla);
2291 }
2292 
2293 CodeGenFunction::VlaSizePair
2294 CodeGenFunction::getVLASize(const VariableArrayType *type) {
2295   // The number of elements so far; always size_t.
2296   llvm::Value *numElements = nullptr;
2297 
2298   QualType elementType;
2299   do {
2300     elementType = type->getElementType();
2301     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2302     assert(vlaSize && "no size for VLA!");
2303     assert(vlaSize->getType() == SizeTy);
2304 
2305     if (!numElements) {
2306       numElements = vlaSize;
2307     } else {
2308       // It's undefined behavior if this wraps around, so mark it that way.
2309       // FIXME: Teach -fsanitize=undefined to trap this.
2310       numElements = Builder.CreateNUWMul(numElements, vlaSize);
2311     }
2312   } while ((type = getContext().getAsVariableArrayType(elementType)));
2313 
2314   return { numElements, elementType };
2315 }
2316 
2317 CodeGenFunction::VlaSizePair
2318 CodeGenFunction::getVLAElements1D(QualType type) {
2319   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2320   assert(vla && "type was not a variable array type!");
2321   return getVLAElements1D(vla);
2322 }
2323 
2324 CodeGenFunction::VlaSizePair
2325 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2326   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2327   assert(VlaSize && "no size for VLA!");
2328   assert(VlaSize->getType() == SizeTy);
2329   return { VlaSize, Vla->getElementType() };
2330 }
2331 
2332 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2333   assert(type->isVariablyModifiedType() &&
2334          "Must pass variably modified type to EmitVLASizes!");
2335 
2336   EnsureInsertPoint();
2337 
2338   // We're going to walk down into the type and look for VLA
2339   // expressions.
2340   do {
2341     assert(type->isVariablyModifiedType());
2342 
2343     const Type *ty = type.getTypePtr();
2344     switch (ty->getTypeClass()) {
2345 
2346 #define TYPE(Class, Base)
2347 #define ABSTRACT_TYPE(Class, Base)
2348 #define NON_CANONICAL_TYPE(Class, Base)
2349 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2350 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2351 #include "clang/AST/TypeNodes.inc"
2352       llvm_unreachable("unexpected dependent type!");
2353 
2354     // These types are never variably-modified.
2355     case Type::Builtin:
2356     case Type::Complex:
2357     case Type::Vector:
2358     case Type::ExtVector:
2359     case Type::ConstantMatrix:
2360     case Type::Record:
2361     case Type::Enum:
2362     case Type::Using:
2363     case Type::TemplateSpecialization:
2364     case Type::ObjCTypeParam:
2365     case Type::ObjCObject:
2366     case Type::ObjCInterface:
2367     case Type::ObjCObjectPointer:
2368     case Type::BitInt:
2369       llvm_unreachable("type class is never variably-modified!");
2370 
2371     case Type::Elaborated:
2372       type = cast<ElaboratedType>(ty)->getNamedType();
2373       break;
2374 
2375     case Type::Adjusted:
2376       type = cast<AdjustedType>(ty)->getAdjustedType();
2377       break;
2378 
2379     case Type::Decayed:
2380       type = cast<DecayedType>(ty)->getPointeeType();
2381       break;
2382 
2383     case Type::Pointer:
2384       type = cast<PointerType>(ty)->getPointeeType();
2385       break;
2386 
2387     case Type::BlockPointer:
2388       type = cast<BlockPointerType>(ty)->getPointeeType();
2389       break;
2390 
2391     case Type::LValueReference:
2392     case Type::RValueReference:
2393       type = cast<ReferenceType>(ty)->getPointeeType();
2394       break;
2395 
2396     case Type::MemberPointer:
2397       type = cast<MemberPointerType>(ty)->getPointeeType();
2398       break;
2399 
2400     case Type::ArrayParameter:
2401     case Type::ConstantArray:
2402     case Type::IncompleteArray:
2403       // Losing element qualification here is fine.
2404       type = cast<ArrayType>(ty)->getElementType();
2405       break;
2406 
2407     case Type::VariableArray: {
2408       // Losing element qualification here is fine.
2409       const VariableArrayType *vat = cast<VariableArrayType>(ty);
2410 
2411       // Unknown size indication requires no size computation.
2412       // Otherwise, evaluate and record it.
2413       if (const Expr *sizeExpr = vat->getSizeExpr()) {
2414         // It's possible that we might have emitted this already,
2415         // e.g. with a typedef and a pointer to it.
2416         llvm::Value *&entry = VLASizeMap[sizeExpr];
2417         if (!entry) {
2418           llvm::Value *size = EmitScalarExpr(sizeExpr);
2419 
2420           // C11 6.7.6.2p5:
2421           //   If the size is an expression that is not an integer constant
2422           //   expression [...] each time it is evaluated it shall have a value
2423           //   greater than zero.
2424           if (SanOpts.has(SanitizerKind::VLABound)) {
2425             SanitizerScope SanScope(this);
2426             llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2427             clang::QualType SEType = sizeExpr->getType();
2428             llvm::Value *CheckCondition =
2429                 SEType->isSignedIntegerType()
2430                     ? Builder.CreateICmpSGT(size, Zero)
2431                     : Builder.CreateICmpUGT(size, Zero);
2432             llvm::Constant *StaticArgs[] = {
2433                 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2434                 EmitCheckTypeDescriptor(SEType)};
2435             EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
2436                       SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2437           }
2438 
2439           // Always zexting here would be wrong if it weren't
2440           // undefined behavior to have a negative bound.
2441           // FIXME: What about when size's type is larger than size_t?
2442           entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2443         }
2444       }
2445       type = vat->getElementType();
2446       break;
2447     }
2448 
2449     case Type::FunctionProto:
2450     case Type::FunctionNoProto:
2451       type = cast<FunctionType>(ty)->getReturnType();
2452       break;
2453 
2454     case Type::Paren:
2455     case Type::TypeOf:
2456     case Type::UnaryTransform:
2457     case Type::Attributed:
2458     case Type::BTFTagAttributed:
2459     case Type::SubstTemplateTypeParm:
2460     case Type::MacroQualified:
2461     case Type::CountAttributed:
2462       // Keep walking after single level desugaring.
2463       type = type.getSingleStepDesugaredType(getContext());
2464       break;
2465 
2466     case Type::Typedef:
2467     case Type::Decltype:
2468     case Type::Auto:
2469     case Type::DeducedTemplateSpecialization:
2470     case Type::PackIndexing:
2471       // Stop walking: nothing to do.
2472       return;
2473 
2474     case Type::TypeOfExpr:
2475       // Stop walking: emit typeof expression.
2476       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2477       return;
2478 
2479     case Type::Atomic:
2480       type = cast<AtomicType>(ty)->getValueType();
2481       break;
2482 
2483     case Type::Pipe:
2484       type = cast<PipeType>(ty)->getElementType();
2485       break;
2486     }
2487   } while (type->isVariablyModifiedType());
2488 }
2489 
2490 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2491   if (getContext().getBuiltinVaListType()->isArrayType())
2492     return EmitPointerWithAlignment(E);
2493   return EmitLValue(E).getAddress();
2494 }
2495 
2496 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2497   return EmitLValue(E).getAddress();
2498 }
2499 
2500 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2501                                               const APValue &Init) {
2502   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2503   if (CGDebugInfo *Dbg = getDebugInfo())
2504     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2505       Dbg->EmitGlobalVariable(E->getDecl(), Init);
2506 }
2507 
2508 CodeGenFunction::PeepholeProtection
2509 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2510   // At the moment, the only aggressive peephole we do in IR gen
2511   // is trunc(zext) folding, but if we add more, we can easily
2512   // extend this protection.
2513 
2514   if (!rvalue.isScalar()) return PeepholeProtection();
2515   llvm::Value *value = rvalue.getScalarVal();
2516   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2517 
2518   // Just make an extra bitcast.
2519   assert(HaveInsertPoint());
2520   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2521                                                   Builder.GetInsertBlock());
2522 
2523   PeepholeProtection protection;
2524   protection.Inst = inst;
2525   return protection;
2526 }
2527 
2528 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2529   if (!protection.Inst) return;
2530 
2531   // In theory, we could try to duplicate the peepholes now, but whatever.
2532   protection.Inst->eraseFromParent();
2533 }
2534 
2535 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2536                                               QualType Ty, SourceLocation Loc,
2537                                               SourceLocation AssumptionLoc,
2538                                               llvm::Value *Alignment,
2539                                               llvm::Value *OffsetValue) {
2540   if (Alignment->getType() != IntPtrTy)
2541     Alignment =
2542         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2543   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2544     OffsetValue =
2545         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2546   llvm::Value *TheCheck = nullptr;
2547   if (SanOpts.has(SanitizerKind::Alignment)) {
2548     llvm::Value *PtrIntValue =
2549         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2550 
2551     if (OffsetValue) {
2552       bool IsOffsetZero = false;
2553       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2554         IsOffsetZero = CI->isZero();
2555 
2556       if (!IsOffsetZero)
2557         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2558     }
2559 
2560     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2561     llvm::Value *Mask =
2562         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2563     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2564     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2565   }
2566   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2567       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2568 
2569   if (!SanOpts.has(SanitizerKind::Alignment))
2570     return;
2571   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2572                                OffsetValue, TheCheck, Assumption);
2573 }
2574 
2575 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2576                                               const Expr *E,
2577                                               SourceLocation AssumptionLoc,
2578                                               llvm::Value *Alignment,
2579                                               llvm::Value *OffsetValue) {
2580   QualType Ty = E->getType();
2581   SourceLocation Loc = E->getExprLoc();
2582 
2583   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2584                           OffsetValue);
2585 }
2586 
2587 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2588                                                  llvm::Value *AnnotatedVal,
2589                                                  StringRef AnnotationStr,
2590                                                  SourceLocation Location,
2591                                                  const AnnotateAttr *Attr) {
2592   SmallVector<llvm::Value *, 5> Args = {
2593       AnnotatedVal,
2594       CGM.EmitAnnotationString(AnnotationStr),
2595       CGM.EmitAnnotationUnit(Location),
2596       CGM.EmitAnnotationLineNo(Location),
2597   };
2598   if (Attr)
2599     Args.push_back(CGM.EmitAnnotationArgs(Attr));
2600   return Builder.CreateCall(AnnotationFn, Args);
2601 }
2602 
2603 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2604   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2605   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2606     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2607                                         {V->getType(), CGM.ConstGlobalsPtrTy}),
2608                        V, I->getAnnotation(), D->getLocation(), I);
2609 }
2610 
2611 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2612                                               Address Addr) {
2613   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2614   llvm::Value *V = Addr.emitRawPointer(*this);
2615   llvm::Type *VTy = V->getType();
2616   auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2617   unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2618   llvm::PointerType *IntrinTy =
2619       llvm::PointerType::get(CGM.getLLVMContext(), AS);
2620   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2621                                        {IntrinTy, CGM.ConstGlobalsPtrTy});
2622 
2623   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2624     // FIXME Always emit the cast inst so we can differentiate between
2625     // annotation on the first field of a struct and annotation on the struct
2626     // itself.
2627     if (VTy != IntrinTy)
2628       V = Builder.CreateBitCast(V, IntrinTy);
2629     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2630     V = Builder.CreateBitCast(V, VTy);
2631   }
2632 
2633   return Address(V, Addr.getElementType(), Addr.getAlignment());
2634 }
2635 
2636 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2637 
2638 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2639     : CGF(CGF) {
2640   assert(!CGF->IsSanitizerScope);
2641   CGF->IsSanitizerScope = true;
2642 }
2643 
2644 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2645   CGF->IsSanitizerScope = false;
2646 }
2647 
2648 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2649                                    const llvm::Twine &Name,
2650                                    llvm::BasicBlock::iterator InsertPt) const {
2651   LoopStack.InsertHelper(I);
2652   if (IsSanitizerScope)
2653     I->setNoSanitizeMetadata();
2654 }
2655 
2656 void CGBuilderInserter::InsertHelper(
2657     llvm::Instruction *I, const llvm::Twine &Name,
2658     llvm::BasicBlock::iterator InsertPt) const {
2659   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2660   if (CGF)
2661     CGF->InsertHelper(I, Name, InsertPt);
2662 }
2663 
2664 // Emits an error if we don't have a valid set of target features for the
2665 // called function.
2666 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2667                                           const FunctionDecl *TargetDecl) {
2668   // SemaChecking cannot handle below x86 builtins because they have different
2669   // parameter ranges with different TargetAttribute of caller.
2670   if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
2671     unsigned BuiltinID = TargetDecl->getBuiltinID();
2672     if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
2673         BuiltinID == X86::BI__builtin_ia32_cmpss ||
2674         BuiltinID == X86::BI__builtin_ia32_cmppd ||
2675         BuiltinID == X86::BI__builtin_ia32_cmpsd) {
2676       const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2677       llvm::StringMap<bool> TargetFetureMap;
2678       CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD);
2679       llvm::APSInt Result =
2680           *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext()));
2681       if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx"))
2682         CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
2683             << TargetDecl->getDeclName() << "avx";
2684     }
2685   }
2686   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2687 }
2688 
2689 // Emits an error if we don't have a valid set of target features for the
2690 // called function.
2691 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2692                                           const FunctionDecl *TargetDecl) {
2693   // Early exit if this is an indirect call.
2694   if (!TargetDecl)
2695     return;
2696 
2697   // Get the current enclosing function if it exists. If it doesn't
2698   // we can't check the target features anyhow.
2699   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2700   if (!FD)
2701     return;
2702 
2703   // Grab the required features for the call. For a builtin this is listed in
2704   // the td file with the default cpu, for an always_inline function this is any
2705   // listed cpu and any listed features.
2706   unsigned BuiltinID = TargetDecl->getBuiltinID();
2707   std::string MissingFeature;
2708   llvm::StringMap<bool> CallerFeatureMap;
2709   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2710   // When compiling in HipStdPar mode we have to be conservative in rejecting
2711   // target specific features in the FE, and defer the possible error to the
2712   // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
2713   // referenced by an accelerator executable function, we emit an error.
2714   bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2715   if (BuiltinID) {
2716     StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2717     if (!Builtin::evaluateRequiredTargetFeatures(
2718         FeatureList, CallerFeatureMap) && !IsHipStdPar) {
2719       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2720           << TargetDecl->getDeclName()
2721           << FeatureList;
2722     }
2723   } else if (!TargetDecl->isMultiVersion() &&
2724              TargetDecl->hasAttr<TargetAttr>()) {
2725     // Get the required features for the callee.
2726 
2727     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2728     ParsedTargetAttr ParsedAttr =
2729         CGM.getContext().filterFunctionTargetAttrs(TD);
2730 
2731     SmallVector<StringRef, 1> ReqFeatures;
2732     llvm::StringMap<bool> CalleeFeatureMap;
2733     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2734 
2735     for (const auto &F : ParsedAttr.Features) {
2736       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2737         ReqFeatures.push_back(StringRef(F).substr(1));
2738     }
2739 
2740     for (const auto &F : CalleeFeatureMap) {
2741       // Only positive features are "required".
2742       if (F.getValue())
2743         ReqFeatures.push_back(F.getKey());
2744     }
2745     if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2746       if (!CallerFeatureMap.lookup(Feature)) {
2747         MissingFeature = Feature.str();
2748         return false;
2749       }
2750       return true;
2751     }) && !IsHipStdPar)
2752       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2753           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2754   } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) {
2755     llvm::StringMap<bool> CalleeFeatureMap;
2756     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2757 
2758     for (const auto &F : CalleeFeatureMap) {
2759       if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
2760                            !CallerFeatureMap.find(F.getKey())->getValue()) &&
2761           !IsHipStdPar)
2762         CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2763             << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
2764     }
2765   }
2766 }
2767 
2768 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2769   if (!CGM.getCodeGenOpts().SanitizeStats)
2770     return;
2771 
2772   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2773   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2774   CGM.getSanStats().create(IRB, SSK);
2775 }
2776 
2777 void CodeGenFunction::EmitKCFIOperandBundle(
2778     const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2779   const FunctionProtoType *FP =
2780       Callee.getAbstractInfo().getCalleeFunctionProtoType();
2781   if (FP)
2782     Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar()));
2783 }
2784 
2785 llvm::Value *CodeGenFunction::FormAArch64ResolverCondition(
2786     const MultiVersionResolverOption &RO) {
2787   llvm::SmallVector<StringRef, 8> CondFeatures;
2788   for (const StringRef &Feature : RO.Conditions.Features) {
2789     // Optimize the Function Multi Versioning resolver by creating conditions
2790     // only for features that are not enabled in the target. The exception is
2791     // for features whose extension instructions are executed as NOP on targets
2792     // without extension support.
2793     if (!getContext().getTargetInfo().hasFeature(Feature) || Feature == "bti" ||
2794         Feature == "memtag" || Feature == "memtag2" || Feature == "memtag3" ||
2795         Feature == "dgh")
2796       CondFeatures.push_back(Feature);
2797   }
2798   if (!CondFeatures.empty()) {
2799     return EmitAArch64CpuSupports(CondFeatures);
2800   }
2801   return nullptr;
2802 }
2803 
2804 llvm::Value *CodeGenFunction::FormX86ResolverCondition(
2805     const MultiVersionResolverOption &RO) {
2806   llvm::Value *Condition = nullptr;
2807 
2808   if (!RO.Conditions.Architecture.empty()) {
2809     StringRef Arch = RO.Conditions.Architecture;
2810     // If arch= specifies an x86-64 micro-architecture level, test the feature
2811     // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2812     if (Arch.starts_with("x86-64"))
2813       Condition = EmitX86CpuSupports({Arch});
2814     else
2815       Condition = EmitX86CpuIs(Arch);
2816   }
2817 
2818   if (!RO.Conditions.Features.empty()) {
2819     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2820     Condition =
2821         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2822   }
2823   return Condition;
2824 }
2825 
2826 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2827                                              llvm::Function *Resolver,
2828                                              CGBuilderTy &Builder,
2829                                              llvm::Function *FuncToReturn,
2830                                              bool SupportsIFunc) {
2831   if (SupportsIFunc) {
2832     Builder.CreateRet(FuncToReturn);
2833     return;
2834   }
2835 
2836   llvm::SmallVector<llvm::Value *, 10> Args(
2837       llvm::make_pointer_range(Resolver->args()));
2838 
2839   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2840   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2841 
2842   if (Resolver->getReturnType()->isVoidTy())
2843     Builder.CreateRetVoid();
2844   else
2845     Builder.CreateRet(Result);
2846 }
2847 
2848 void CodeGenFunction::EmitMultiVersionResolver(
2849     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2850 
2851   llvm::Triple::ArchType ArchType =
2852       getContext().getTargetInfo().getTriple().getArch();
2853 
2854   switch (ArchType) {
2855   case llvm::Triple::x86:
2856   case llvm::Triple::x86_64:
2857     EmitX86MultiVersionResolver(Resolver, Options);
2858     return;
2859   case llvm::Triple::aarch64:
2860     EmitAArch64MultiVersionResolver(Resolver, Options);
2861     return;
2862 
2863   default:
2864     assert(false && "Only implemented for x86 and AArch64 targets");
2865   }
2866 }
2867 
2868 void CodeGenFunction::EmitAArch64MultiVersionResolver(
2869     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2870   assert(!Options.empty() && "No multiversion resolver options found");
2871   assert(Options.back().Conditions.Features.size() == 0 &&
2872          "Default case must be last");
2873   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2874   assert(SupportsIFunc &&
2875          "Multiversion resolver requires target IFUNC support");
2876   bool AArch64CpuInitialized = false;
2877   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2878 
2879   for (const MultiVersionResolverOption &RO : Options) {
2880     Builder.SetInsertPoint(CurBlock);
2881     llvm::Value *Condition = FormAArch64ResolverCondition(RO);
2882 
2883     // The 'default' or 'all features enabled' case.
2884     if (!Condition) {
2885       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2886                                        SupportsIFunc);
2887       return;
2888     }
2889 
2890     if (!AArch64CpuInitialized) {
2891       Builder.SetInsertPoint(CurBlock, CurBlock->begin());
2892       EmitAArch64CpuInit();
2893       AArch64CpuInitialized = true;
2894       Builder.SetInsertPoint(CurBlock);
2895     }
2896 
2897     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2898     CGBuilderTy RetBuilder(*this, RetBlock);
2899     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2900                                      SupportsIFunc);
2901     CurBlock = createBasicBlock("resolver_else", Resolver);
2902     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2903   }
2904 
2905   // If no default, emit an unreachable.
2906   Builder.SetInsertPoint(CurBlock);
2907   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2908   TrapCall->setDoesNotReturn();
2909   TrapCall->setDoesNotThrow();
2910   Builder.CreateUnreachable();
2911   Builder.ClearInsertionPoint();
2912 }
2913 
2914 void CodeGenFunction::EmitX86MultiVersionResolver(
2915     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2916 
2917   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2918 
2919   // Main function's basic block.
2920   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2921   Builder.SetInsertPoint(CurBlock);
2922   EmitX86CpuInit();
2923 
2924   for (const MultiVersionResolverOption &RO : Options) {
2925     Builder.SetInsertPoint(CurBlock);
2926     llvm::Value *Condition = FormX86ResolverCondition(RO);
2927 
2928     // The 'default' or 'generic' case.
2929     if (!Condition) {
2930       assert(&RO == Options.end() - 1 &&
2931              "Default or Generic case must be last");
2932       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2933                                        SupportsIFunc);
2934       return;
2935     }
2936 
2937     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2938     CGBuilderTy RetBuilder(*this, RetBlock);
2939     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2940                                      SupportsIFunc);
2941     CurBlock = createBasicBlock("resolver_else", Resolver);
2942     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2943   }
2944 
2945   // If no generic/default, emit an unreachable.
2946   Builder.SetInsertPoint(CurBlock);
2947   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2948   TrapCall->setDoesNotReturn();
2949   TrapCall->setDoesNotThrow();
2950   Builder.CreateUnreachable();
2951   Builder.ClearInsertionPoint();
2952 }
2953 
2954 // Loc - where the diagnostic will point, where in the source code this
2955 //  alignment has failed.
2956 // SecondaryLoc - if present (will be present if sufficiently different from
2957 //  Loc), the diagnostic will additionally point a "Note:" to this location.
2958 //  It should be the location where the __attribute__((assume_aligned))
2959 //  was written e.g.
2960 void CodeGenFunction::emitAlignmentAssumptionCheck(
2961     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2962     SourceLocation SecondaryLoc, llvm::Value *Alignment,
2963     llvm::Value *OffsetValue, llvm::Value *TheCheck,
2964     llvm::Instruction *Assumption) {
2965   assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
2966          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2967              llvm::Intrinsic::getDeclaration(
2968                  Builder.GetInsertBlock()->getParent()->getParent(),
2969                  llvm::Intrinsic::assume) &&
2970          "Assumption should be a call to llvm.assume().");
2971   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2972          "Assumption should be the last instruction of the basic block, "
2973          "since the basic block is still being generated.");
2974 
2975   if (!SanOpts.has(SanitizerKind::Alignment))
2976     return;
2977 
2978   // Don't check pointers to volatile data. The behavior here is implementation-
2979   // defined.
2980   if (Ty->getPointeeType().isVolatileQualified())
2981     return;
2982 
2983   // We need to temorairly remove the assumption so we can insert the
2984   // sanitizer check before it, else the check will be dropped by optimizations.
2985   Assumption->removeFromParent();
2986 
2987   {
2988     SanitizerScope SanScope(this);
2989 
2990     if (!OffsetValue)
2991       OffsetValue = Builder.getInt1(false); // no offset.
2992 
2993     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2994                                     EmitCheckSourceLocation(SecondaryLoc),
2995                                     EmitCheckTypeDescriptor(Ty)};
2996     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2997                                   EmitCheckValue(Alignment),
2998                                   EmitCheckValue(OffsetValue)};
2999     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
3000               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
3001   }
3002 
3003   // We are now in the (new, empty) "cont" basic block.
3004   // Reintroduce the assumption.
3005   Builder.Insert(Assumption);
3006   // FIXME: Assumption still has it's original basic block as it's Parent.
3007 }
3008 
3009 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
3010   if (CGDebugInfo *DI = getDebugInfo())
3011     return DI->SourceLocToDebugLoc(Location);
3012 
3013   return llvm::DebugLoc();
3014 }
3015 
3016 llvm::Value *
3017 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3018                                                       Stmt::Likelihood LH) {
3019   switch (LH) {
3020   case Stmt::LH_None:
3021     return Cond;
3022   case Stmt::LH_Likely:
3023   case Stmt::LH_Unlikely:
3024     // Don't generate llvm.expect on -O0 as the backend won't use it for
3025     // anything.
3026     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3027       return Cond;
3028     llvm::Type *CondTy = Cond->getType();
3029     assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3030     llvm::Function *FnExpect =
3031         CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3032     llvm::Value *ExpectedValueOfCond =
3033         llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3034     return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3035                               Cond->getName() + ".expval");
3036   }
3037   llvm_unreachable("Unknown Likelihood");
3038 }
3039 
3040 llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3041                                                     unsigned NumElementsDst,
3042                                                     const llvm::Twine &Name) {
3043   auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3044   unsigned NumElementsSrc = SrcTy->getNumElements();
3045   if (NumElementsSrc == NumElementsDst)
3046     return SrcVec;
3047 
3048   std::vector<int> ShuffleMask(NumElementsDst, -1);
3049   for (unsigned MaskIdx = 0;
3050        MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3051     ShuffleMask[MaskIdx] = MaskIdx;
3052 
3053   return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3054 }
3055 
3056 void CodeGenFunction::EmitPointerAuthOperandBundle(
3057     const CGPointerAuthInfo &PointerAuth,
3058     SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
3059   if (!PointerAuth.isSigned())
3060     return;
3061 
3062   auto *Key = Builder.getInt32(PointerAuth.getKey());
3063 
3064   llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3065   if (!Discriminator)
3066     Discriminator = Builder.getSize(0);
3067 
3068   llvm::Value *Args[] = {Key, Discriminator};
3069   Bundles.emplace_back("ptrauth", Args);
3070 }
3071 
3072 static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF,
3073                                           const CGPointerAuthInfo &PointerAuth,
3074                                           llvm::Value *Pointer,
3075                                           unsigned IntrinsicID) {
3076   if (!PointerAuth)
3077     return Pointer;
3078 
3079   auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3080 
3081   llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3082   if (!Discriminator) {
3083     Discriminator = CGF.Builder.getSize(0);
3084   }
3085 
3086   // Convert the pointer to intptr_t before signing it.
3087   auto OrigType = Pointer->getType();
3088   Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3089 
3090   // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3091   auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3092   Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3093 
3094   // Convert back to the original type.
3095   Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3096   return Pointer;
3097 }
3098 
3099 llvm::Value *
3100 CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth,
3101                                      llvm::Value *Pointer) {
3102   if (!PointerAuth.shouldSign())
3103     return Pointer;
3104   return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3105                                llvm::Intrinsic::ptrauth_sign);
3106 }
3107 
3108 static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3109                               const CGPointerAuthInfo &PointerAuth,
3110                               llvm::Value *Pointer) {
3111   auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3112 
3113   auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3114   // Convert the pointer to intptr_t before signing it.
3115   auto OrigType = Pointer->getType();
3116   Pointer = CGF.EmitRuntimeCall(
3117       StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3118   return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3119 }
3120 
3121 llvm::Value *
3122 CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth,
3123                                      llvm::Value *Pointer) {
3124   if (PointerAuth.shouldStrip()) {
3125     return EmitStrip(*this, PointerAuth, Pointer);
3126   }
3127   if (!PointerAuth.shouldAuth()) {
3128     return Pointer;
3129   }
3130 
3131   return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3132                                llvm::Intrinsic::ptrauth_auth);
3133 }
3134