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