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