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