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