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