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