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