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