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