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