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