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