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