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