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