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