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