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()->use_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   // MDNode for the kernel argument address space qualifiers.
343   SmallVector<llvm::Value*, 8> addressQuals;
344   addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
345 
346   // MDNode for the kernel argument access qualifiers (images only).
347   SmallVector<llvm::Value*, 8> accessQuals;
348   accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
349 
350   // MDNode for the kernel argument type names.
351   SmallVector<llvm::Value*, 8> argTypeNames;
352   argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
353 
354   // MDNode for the kernel argument type qualifiers.
355   SmallVector<llvm::Value*, 8> argTypeQuals;
356   argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
357 
358   // MDNode for the kernel argument names.
359   SmallVector<llvm::Value*, 8> argNames;
360   argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
361 
362   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
363     const ParmVarDecl *parm = FD->getParamDecl(i);
364     QualType ty = parm->getType();
365     std::string typeQuals;
366 
367     if (ty->isPointerType()) {
368       QualType pointeeTy = ty->getPointeeType();
369 
370       // Get address qualifier.
371       addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
372         pointeeTy.getAddressSpace())));
373 
374       // Get argument type name.
375       std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*";
376 
377       // Turn "unsigned type" to "utype"
378       std::string::size_type pos = typeName.find("unsigned");
379       if (pos != std::string::npos)
380         typeName.erase(pos+1, 8);
381 
382       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
383 
384       // Get argument type qualifiers:
385       if (ty.isRestrictQualified())
386         typeQuals = "restrict";
387       if (pointeeTy.isConstQualified() ||
388           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
389         typeQuals += typeQuals.empty() ? "const" : " const";
390       if (pointeeTy.isVolatileQualified())
391         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
392     } else {
393       uint32_t AddrSpc = 0;
394       if (ty->isImageType())
395         AddrSpc =
396           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
397 
398       addressQuals.push_back(Builder.getInt32(AddrSpc));
399 
400       // Get argument type name.
401       std::string typeName = ty.getUnqualifiedType().getAsString();
402 
403       // Turn "unsigned type" to "utype"
404       std::string::size_type pos = typeName.find("unsigned");
405       if (pos != std::string::npos)
406         typeName.erase(pos+1, 8);
407 
408       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
409 
410       // Get argument type qualifiers:
411       if (ty.isConstQualified())
412         typeQuals = "const";
413       if (ty.isVolatileQualified())
414         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
415     }
416 
417     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
418 
419     // Get image access qualifier:
420     if (ty->isImageType()) {
421       const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
422       if (A && A->isWriteOnly())
423         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
424       else
425         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
426       // FIXME: what about read_write?
427     } else
428       accessQuals.push_back(llvm::MDString::get(Context, "none"));
429 
430     // Get argument name.
431     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
432   }
433 
434   kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
435   kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
436   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
437   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
438   kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
439 }
440 
441 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
442                                                llvm::Function *Fn)
443 {
444   if (!FD->hasAttr<OpenCLKernelAttr>())
445     return;
446 
447   llvm::LLVMContext &Context = getLLVMContext();
448 
449   SmallVector <llvm::Value*, 5> kernelMDArgs;
450   kernelMDArgs.push_back(Fn);
451 
452   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
453     GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
454                          Builder, getContext());
455 
456   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
457     QualType hintQTy = A->getTypeHint();
458     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
459     bool isSignedInteger =
460         hintQTy->isSignedIntegerType() ||
461         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
462     llvm::Value *attrMDArgs[] = {
463       llvm::MDString::get(Context, "vec_type_hint"),
464       llvm::UndefValue::get(CGM.getTypes().ConvertType(A->getTypeHint())),
465       llvm::ConstantInt::get(
466           llvm::IntegerType::get(Context, 32),
467           llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
468     };
469     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
470   }
471 
472   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
473     llvm::Value *attrMDArgs[] = {
474       llvm::MDString::get(Context, "work_group_size_hint"),
475       Builder.getInt32(A->getXDim()),
476       Builder.getInt32(A->getYDim()),
477       Builder.getInt32(A->getZDim())
478     };
479     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
480   }
481 
482   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
483     llvm::Value *attrMDArgs[] = {
484       llvm::MDString::get(Context, "reqd_work_group_size"),
485       Builder.getInt32(A->getXDim()),
486       Builder.getInt32(A->getYDim()),
487       Builder.getInt32(A->getZDim())
488     };
489     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
490   }
491 
492   llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
493   llvm::NamedMDNode *OpenCLKernelMetadata =
494     CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
495   OpenCLKernelMetadata->addOperand(kernelMDNode);
496 }
497 
498 void CodeGenFunction::StartFunction(GlobalDecl GD,
499                                     QualType RetTy,
500                                     llvm::Function *Fn,
501                                     const CGFunctionInfo &FnInfo,
502                                     const FunctionArgList &Args,
503                                     SourceLocation StartLoc) {
504   const Decl *D = GD.getDecl();
505 
506   DidCallStackSave = false;
507   CurCodeDecl = D;
508   CurFuncDecl = (D ? D->getNonClosureContext() : 0);
509   FnRetTy = RetTy;
510   CurFn = Fn;
511   CurFnInfo = &FnInfo;
512   assert(CurFn->isDeclaration() && "Function already has body?");
513 
514   if (CGM.getSanitizerBlacklist().isIn(*Fn)) {
515     SanOpts = &SanitizerOptions::Disabled;
516     SanitizePerformTypeCheck = false;
517   }
518 
519   // Pass inline keyword to optimizer if it appears explicitly on any
520   // declaration. Also, in the case of -fno-inline attach NoInline
521   // attribute to all function that are not marked AlwaysInline or ForceInline.
522   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
523     if (!CGM.getCodeGenOpts().NoInline) {
524       for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
525              RE = FD->redecls_end(); RI != RE; ++RI)
526         if (RI->isInlineSpecified()) {
527           Fn->addFnAttr(llvm::Attribute::InlineHint);
528           break;
529         }
530     } else if (!FD->hasAttr<AlwaysInlineAttr>() &&
531                !FD->hasAttr<ForceInlineAttr>())
532       Fn->addFnAttr(llvm::Attribute::NoInline);
533   }
534 
535   if (getLangOpts().OpenCL) {
536     // Add metadata for a kernel function.
537     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
538       EmitOpenCLKernelMetadata(FD, Fn);
539   }
540 
541   // If we are checking function types, emit a function type signature as
542   // prefix data.
543   if (getLangOpts().CPlusPlus && SanOpts->Function) {
544     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
545       if (llvm::Constant *PrefixSig =
546               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
547         llvm::Constant *FTRTTIConst =
548             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
549         llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
550         llvm::Constant *PrefixStructConst =
551             llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
552         Fn->setPrefixData(PrefixStructConst);
553       }
554     }
555   }
556 
557   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
558 
559   // Create a marker to make it easy to insert allocas into the entryblock
560   // later.  Don't create this with the builder, because we don't want it
561   // folded.
562   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
563   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
564   if (Builder.isNamePreserving())
565     AllocaInsertPt->setName("allocapt");
566 
567   ReturnBlock = getJumpDestInCurrentScope("return");
568 
569   Builder.SetInsertPoint(EntryBB);
570 
571   // Emit subprogram debug descriptor.
572   if (CGDebugInfo *DI = getDebugInfo()) {
573     SmallVector<QualType, 16> ArgTypes;
574     for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
575 	 i != e; ++i) {
576       ArgTypes.push_back((*i)->getType());
577     }
578 
579     QualType FnType =
580       getContext().getFunctionType(RetTy, ArgTypes,
581                                    FunctionProtoType::ExtProtoInfo());
582 
583     DI->setLocation(StartLoc);
584     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
585   }
586 
587   if (ShouldInstrumentFunction())
588     EmitFunctionInstrumentation("__cyg_profile_func_enter");
589 
590   if (CGM.getCodeGenOpts().InstrumentForProfiling)
591     EmitMCountInstrumentation();
592 
593   PGO.assignRegionCounters(GD);
594   if (CGM.getPGOData()) {
595     if (D) {
596       // Turn on InlineHint attribute for hot functions.
597       if (CGM.getPGOData()->isHotFunction(CGM.getMangledName(GD)))
598         Fn->addFnAttr(llvm::Attribute::InlineHint);
599       // Turn on Cold attribute for cold functions.
600       else if (CGM.getPGOData()->isColdFunction(CGM.getMangledName(GD)))
601         Fn->addFnAttr(llvm::Attribute::Cold);
602     }
603   }
604 
605   if (RetTy->isVoidType()) {
606     // Void type; nothing to return.
607     ReturnValue = 0;
608   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
609              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
610     // Indirect aggregate return; emit returned value directly into sret slot.
611     // This reduces code size, and affects correctness in C++.
612     ReturnValue = CurFn->arg_begin();
613   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
614              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
615     // Load the sret pointer from the argument struct and return into that.
616     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
617     llvm::Function::arg_iterator EI = CurFn->arg_end();
618     --EI;
619     llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
620     ReturnValue = Builder.CreateLoad(Addr, "agg.result");
621   } else {
622     ReturnValue = CreateIRTemp(RetTy, "retval");
623 
624     // Tell the epilog emitter to autorelease the result.  We do this
625     // now so that various specialized functions can suppress it
626     // during their IR-generation.
627     if (getLangOpts().ObjCAutoRefCount &&
628         !CurFnInfo->isReturnsRetained() &&
629         RetTy->isObjCRetainableType())
630       AutoreleaseResult = true;
631   }
632 
633   EmitStartEHSpec(CurCodeDecl);
634 
635   PrologueCleanupDepth = EHStack.stable_begin();
636   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
637 
638   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
639     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
640     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
641     if (MD->getParent()->isLambda() &&
642         MD->getOverloadedOperator() == OO_Call) {
643       // We're in a lambda; figure out the captures.
644       MD->getParent()->getCaptureFields(LambdaCaptureFields,
645                                         LambdaThisCaptureField);
646       if (LambdaThisCaptureField) {
647         // If this lambda captures this, load it.
648         LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
649         CXXThisValue = EmitLoadOfLValue(ThisLValue,
650                                         SourceLocation()).getScalarVal();
651       }
652     } else {
653       // Not in a lambda; just use 'this' from the method.
654       // FIXME: Should we generate a new load for each use of 'this'?  The
655       // fast register allocator would be happier...
656       CXXThisValue = CXXABIThisValue;
657     }
658   }
659 
660   // If any of the arguments have a variably modified type, make sure to
661   // emit the type size.
662   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
663        i != e; ++i) {
664     const VarDecl *VD = *i;
665 
666     // Dig out the type as written from ParmVarDecls; it's unclear whether
667     // the standard (C99 6.9.1p10) requires this, but we're following the
668     // precedent set by gcc.
669     QualType Ty;
670     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
671       Ty = PVD->getOriginalType();
672     else
673       Ty = VD->getType();
674 
675     if (Ty->isVariablyModifiedType())
676       EmitVariablyModifiedType(Ty);
677   }
678   // Emit a location at the end of the prologue.
679   if (CGDebugInfo *DI = getDebugInfo())
680     DI->EmitLocation(Builder, StartLoc);
681 }
682 
683 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
684                                        const Stmt *Body) {
685   RegionCounter Cnt = getPGORegionCounter(Body);
686   Cnt.beginRegion(Builder);
687   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
688     EmitCompoundStmtWithoutScope(*S);
689   else
690     EmitStmt(Body);
691 }
692 
693 /// Tries to mark the given function nounwind based on the
694 /// non-existence of any throwing calls within it.  We believe this is
695 /// lightweight enough to do at -O0.
696 static void TryMarkNoThrow(llvm::Function *F) {
697   // LLVM treats 'nounwind' on a function as part of the type, so we
698   // can't do this on functions that can be overwritten.
699   if (F->mayBeOverridden()) return;
700 
701   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
702     for (llvm::BasicBlock::iterator
703            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
704       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
705         if (!Call->doesNotThrow())
706           return;
707       } else if (isa<llvm::ResumeInst>(&*BI)) {
708         return;
709       }
710   F->setDoesNotThrow();
711 }
712 
713 static void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
714                                           const FunctionDecl *UnsizedDealloc) {
715   // This is a weak discardable definition of the sized deallocation function.
716   CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
717 
718   // Call the unsized deallocation function and forward the first argument
719   // unchanged.
720   llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
721   CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
722 }
723 
724 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
725                                    const CGFunctionInfo &FnInfo) {
726   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
727 
728   // Check if we should generate debug info for this function.
729   if (FD->hasAttr<NoDebugAttr>())
730     DebugInfo = NULL; // disable debug info indefinitely for this function
731 
732   FunctionArgList Args;
733   QualType ResTy = FD->getReturnType();
734 
735   CurGD = GD;
736   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
737   if (MD && MD->isInstance()) {
738     if (CGM.getCXXABI().HasThisReturn(GD))
739       ResTy = MD->getThisType(getContext());
740     CGM.getCXXABI().buildThisParam(*this, Args);
741   }
742 
743   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
744     Args.push_back(FD->getParamDecl(i));
745 
746   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
747     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
748 
749   SourceRange BodyRange;
750   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
751   CurEHLocation = BodyRange.getEnd();
752 
753   // Emit the standard function prologue.
754   StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
755 
756   // Generate the body of the function.
757   if (isa<CXXDestructorDecl>(FD))
758     EmitDestructorBody(Args);
759   else if (isa<CXXConstructorDecl>(FD))
760     EmitConstructorBody(Args);
761   else if (getLangOpts().CUDA &&
762            !CGM.getCodeGenOpts().CUDAIsDevice &&
763            FD->hasAttr<CUDAGlobalAttr>())
764     CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
765   else if (isa<CXXConversionDecl>(FD) &&
766            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
767     // The lambda conversion to block pointer is special; the semantics can't be
768     // expressed in the AST, so IRGen needs to special-case it.
769     EmitLambdaToBlockPointerBody(Args);
770   } else if (isa<CXXMethodDecl>(FD) &&
771              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
772     // The lambda static invoker function is special, because it forwards or
773     // clones the body of the function call operator (but is actually static).
774     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
775   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
776              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
777               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
778     // Implicit copy-assignment gets the same special treatment as implicit
779     // copy-constructors.
780     emitImplicitAssignmentOperatorBody(Args);
781   } else if (Stmt *Body = FD->getBody()) {
782     EmitFunctionBody(Args, Body);
783   } else if (FunctionDecl *UnsizedDealloc =
784                  FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
785     // Global sized deallocation functions get an implicit weak definition if
786     // they don't have an explicit definition.
787     EmitSizedDeallocationFunction(*this, UnsizedDealloc);
788   } else
789     llvm_unreachable("no definition for emitted function");
790 
791   // C++11 [stmt.return]p2:
792   //   Flowing off the end of a function [...] results in undefined behavior in
793   //   a value-returning function.
794   // C11 6.9.1p12:
795   //   If the '}' that terminates a function is reached, and the value of the
796   //   function call is used by the caller, the behavior is undefined.
797   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() &&
798       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
799     if (SanOpts->Return)
800       EmitCheck(Builder.getFalse(), "missing_return",
801                 EmitCheckSourceLocation(FD->getLocation()),
802                 ArrayRef<llvm::Value *>(), CRK_Unrecoverable);
803     else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
804       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
805     Builder.CreateUnreachable();
806     Builder.ClearInsertionPoint();
807   }
808 
809   // Emit the standard function epilogue.
810   FinishFunction(BodyRange.getEnd());
811 
812   // If we haven't marked the function nothrow through other means, do
813   // a quick pass now to see if we can.
814   if (!CurFn->doesNotThrow())
815     TryMarkNoThrow(CurFn);
816 
817   PGO.emitWriteoutFunction(CurGD);
818   PGO.destroyRegionCounters();
819 }
820 
821 /// ContainsLabel - Return true if the statement contains a label in it.  If
822 /// this statement is not executed normally, it not containing a label means
823 /// that we can just remove the code.
824 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
825   // Null statement, not a label!
826   if (S == 0) return false;
827 
828   // If this is a label, we have to emit the code, consider something like:
829   // if (0) {  ...  foo:  bar(); }  goto foo;
830   //
831   // TODO: If anyone cared, we could track __label__'s, since we know that you
832   // can't jump to one from outside their declared region.
833   if (isa<LabelStmt>(S))
834     return true;
835 
836   // If this is a case/default statement, and we haven't seen a switch, we have
837   // to emit the code.
838   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
839     return true;
840 
841   // If this is a switch statement, we want to ignore cases below it.
842   if (isa<SwitchStmt>(S))
843     IgnoreCaseStmts = true;
844 
845   // Scan subexpressions for verboten labels.
846   for (Stmt::const_child_range I = S->children(); I; ++I)
847     if (ContainsLabel(*I, IgnoreCaseStmts))
848       return true;
849 
850   return false;
851 }
852 
853 /// containsBreak - Return true if the statement contains a break out of it.
854 /// If the statement (recursively) contains a switch or loop with a break
855 /// inside of it, this is fine.
856 bool CodeGenFunction::containsBreak(const Stmt *S) {
857   // Null statement, not a label!
858   if (S == 0) return false;
859 
860   // If this is a switch or loop that defines its own break scope, then we can
861   // include it and anything inside of it.
862   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
863       isa<ForStmt>(S))
864     return false;
865 
866   if (isa<BreakStmt>(S))
867     return true;
868 
869   // Scan subexpressions for verboten breaks.
870   for (Stmt::const_child_range I = S->children(); I; ++I)
871     if (containsBreak(*I))
872       return true;
873 
874   return false;
875 }
876 
877 
878 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
879 /// to a constant, or if it does but contains a label, return false.  If it
880 /// constant folds return true and set the boolean result in Result.
881 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
882                                                    bool &ResultBool) {
883   llvm::APSInt ResultInt;
884   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
885     return false;
886 
887   ResultBool = ResultInt.getBoolValue();
888   return true;
889 }
890 
891 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
892 /// to a constant, or if it does but contains a label, return false.  If it
893 /// constant folds return true and set the folded value.
894 bool CodeGenFunction::
895 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
896   // FIXME: Rename and handle conversion of other evaluatable things
897   // to bool.
898   llvm::APSInt Int;
899   if (!Cond->EvaluateAsInt(Int, getContext()))
900     return false;  // Not foldable, not integer or not fully evaluatable.
901 
902   if (CodeGenFunction::ContainsLabel(Cond))
903     return false;  // Contains a label.
904 
905   ResultInt = Int;
906   return true;
907 }
908 
909 
910 
911 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
912 /// statement) to the specified blocks.  Based on the condition, this might try
913 /// to simplify the codegen of the conditional based on the branch.
914 ///
915 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
916                                            llvm::BasicBlock *TrueBlock,
917                                            llvm::BasicBlock *FalseBlock,
918                                            uint64_t TrueCount) {
919   Cond = Cond->IgnoreParens();
920 
921   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
922     RegionCounter Cnt = getPGORegionCounter(CondBOp);
923 
924     // Handle X && Y in a condition.
925     if (CondBOp->getOpcode() == BO_LAnd) {
926       // If we have "1 && X", simplify the code.  "0 && X" would have constant
927       // folded if the case was simple enough.
928       bool ConstantBool = false;
929       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
930           ConstantBool) {
931         // br(1 && X) -> br(X).
932         Cnt.beginRegion(Builder);
933         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
934                                     TrueCount);
935       }
936 
937       // If we have "X && 1", simplify the code to use an uncond branch.
938       // "X && 0" would have been constant folded to 0.
939       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
940           ConstantBool) {
941         // br(X && 1) -> br(X).
942         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
943                                     TrueCount);
944       }
945 
946       // Emit the LHS as a conditional.  If the LHS conditional is false, we
947       // want to jump to the FalseBlock.
948       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
949       // The counter tells us how often we evaluate RHS, and all of TrueCount
950       // can be propagated to that branch.
951       uint64_t RHSCount = Cnt.getCount();
952 
953       ConditionalEvaluation eval(*this);
954       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
955       EmitBlock(LHSTrue);
956 
957       // Any temporaries created here are conditional.
958       Cnt.beginRegion(Builder);
959       eval.begin(*this);
960       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
961       eval.end(*this);
962       Cnt.adjustForControlFlow();
963       Cnt.applyAdjustmentsToRegion();
964 
965       return;
966     }
967 
968     if (CondBOp->getOpcode() == BO_LOr) {
969       // If we have "0 || X", simplify the code.  "1 || X" would have constant
970       // folded if the case was simple enough.
971       bool ConstantBool = false;
972       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
973           !ConstantBool) {
974         // br(0 || X) -> br(X).
975         Cnt.beginRegion(Builder);
976         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
977                                     TrueCount);
978       }
979 
980       // If we have "X || 0", simplify the code to use an uncond branch.
981       // "X || 1" would have been constant folded to 1.
982       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
983           !ConstantBool) {
984         // br(X || 0) -> br(X).
985         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
986                                     TrueCount);
987       }
988 
989       // Emit the LHS as a conditional.  If the LHS conditional is true, we
990       // want to jump to the TrueBlock.
991       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
992       // We have the count for entry to the RHS and for the whole expression
993       // being true, so we can divy up True count between the short circuit and
994       // the RHS.
995       uint64_t LHSCount = Cnt.getParentCount() - Cnt.getCount();
996       uint64_t RHSCount = TrueCount - LHSCount;
997 
998       ConditionalEvaluation eval(*this);
999       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1000       EmitBlock(LHSFalse);
1001 
1002       // Any temporaries created here are conditional.
1003       Cnt.beginRegion(Builder);
1004       eval.begin(*this);
1005       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1006 
1007       eval.end(*this);
1008       Cnt.adjustForControlFlow();
1009       Cnt.applyAdjustmentsToRegion();
1010 
1011       return;
1012     }
1013   }
1014 
1015   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1016     // br(!x, t, f) -> br(x, f, t)
1017     if (CondUOp->getOpcode() == UO_LNot) {
1018       // Negate the count.
1019       uint64_t FalseCount = PGO.getCurrentRegionCount() - TrueCount;
1020       // Negate the condition and swap the destination blocks.
1021       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1022                                   FalseCount);
1023     }
1024   }
1025 
1026   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1027     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1028     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1029     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1030 
1031     RegionCounter Cnt = getPGORegionCounter(CondOp);
1032     ConditionalEvaluation cond(*this);
1033     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
1034 
1035     // When computing PGO branch weights, we only know the overall count for
1036     // the true block. This code is essentially doing tail duplication of the
1037     // naive code-gen, introducing new edges for which counts are not
1038     // available. Divide the counts proportionally between the LHS and RHS of
1039     // the conditional operator.
1040     uint64_t LHSScaledTrueCount = 0;
1041     if (TrueCount) {
1042       double LHSRatio = Cnt.getCount() / (double) PGO.getCurrentRegionCount();
1043       LHSScaledTrueCount = TrueCount * LHSRatio;
1044     }
1045 
1046     cond.begin(*this);
1047     EmitBlock(LHSBlock);
1048     Cnt.beginRegion(Builder);
1049     EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1050                          LHSScaledTrueCount);
1051     cond.end(*this);
1052 
1053     cond.begin(*this);
1054     EmitBlock(RHSBlock);
1055     Cnt.beginElseRegion();
1056     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1057                          TrueCount - LHSScaledTrueCount);
1058     cond.end(*this);
1059 
1060     return;
1061   }
1062 
1063   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1064     // Conditional operator handling can give us a throw expression as a
1065     // condition for a case like:
1066     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1067     // Fold this to:
1068     //   br(c, throw x, br(y, t, f))
1069     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1070     return;
1071   }
1072 
1073   // Create branch weights based on the number of times we get here and the
1074   // number of times the condition should be true.
1075   uint64_t CurrentCount = PGO.getCurrentRegionCountWithMin(TrueCount);
1076   llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount,
1077                                                   CurrentCount - TrueCount);
1078 
1079   // Emit the code with the fully general case.
1080   llvm::Value *CondV = EvaluateExprAsBool(Cond);
1081   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1082 }
1083 
1084 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1085 /// specified stmt yet.
1086 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1087   CGM.ErrorUnsupported(S, Type);
1088 }
1089 
1090 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1091 /// variable-length array whose elements have a non-zero bit-pattern.
1092 ///
1093 /// \param baseType the inner-most element type of the array
1094 /// \param src - a char* pointing to the bit-pattern for a single
1095 /// base element of the array
1096 /// \param sizeInChars - the total size of the VLA, in chars
1097 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1098                                llvm::Value *dest, llvm::Value *src,
1099                                llvm::Value *sizeInChars) {
1100   std::pair<CharUnits,CharUnits> baseSizeAndAlign
1101     = CGF.getContext().getTypeInfoInChars(baseType);
1102 
1103   CGBuilderTy &Builder = CGF.Builder;
1104 
1105   llvm::Value *baseSizeInChars
1106     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1107 
1108   llvm::Type *i8p = Builder.getInt8PtrTy();
1109 
1110   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1111   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1112 
1113   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1114   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1115   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1116 
1117   // Make a loop over the VLA.  C99 guarantees that the VLA element
1118   // count must be nonzero.
1119   CGF.EmitBlock(loopBB);
1120 
1121   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1122   cur->addIncoming(begin, originBB);
1123 
1124   // memcpy the individual element bit-pattern.
1125   Builder.CreateMemCpy(cur, src, baseSizeInChars,
1126                        baseSizeAndAlign.second.getQuantity(),
1127                        /*volatile*/ false);
1128 
1129   // Go to the next element.
1130   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1131 
1132   // Leave if that's the end of the VLA.
1133   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1134   Builder.CreateCondBr(done, contBB, loopBB);
1135   cur->addIncoming(next, loopBB);
1136 
1137   CGF.EmitBlock(contBB);
1138 }
1139 
1140 void
1141 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1142   // Ignore empty classes in C++.
1143   if (getLangOpts().CPlusPlus) {
1144     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1145       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1146         return;
1147     }
1148   }
1149 
1150   // Cast the dest ptr to the appropriate i8 pointer type.
1151   unsigned DestAS =
1152     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1153   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1154   if (DestPtr->getType() != BP)
1155     DestPtr = Builder.CreateBitCast(DestPtr, BP);
1156 
1157   // Get size and alignment info for this aggregate.
1158   std::pair<CharUnits, CharUnits> TypeInfo =
1159     getContext().getTypeInfoInChars(Ty);
1160   CharUnits Size = TypeInfo.first;
1161   CharUnits Align = TypeInfo.second;
1162 
1163   llvm::Value *SizeVal;
1164   const VariableArrayType *vla;
1165 
1166   // Don't bother emitting a zero-byte memset.
1167   if (Size.isZero()) {
1168     // But note that getTypeInfo returns 0 for a VLA.
1169     if (const VariableArrayType *vlaType =
1170           dyn_cast_or_null<VariableArrayType>(
1171                                           getContext().getAsArrayType(Ty))) {
1172       QualType eltType;
1173       llvm::Value *numElts;
1174       llvm::tie(numElts, eltType) = getVLASize(vlaType);
1175 
1176       SizeVal = numElts;
1177       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1178       if (!eltSize.isOne())
1179         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1180       vla = vlaType;
1181     } else {
1182       return;
1183     }
1184   } else {
1185     SizeVal = CGM.getSize(Size);
1186     vla = 0;
1187   }
1188 
1189   // If the type contains a pointer to data member we can't memset it to zero.
1190   // Instead, create a null constant and copy it to the destination.
1191   // TODO: there are other patterns besides zero that we can usefully memset,
1192   // like -1, which happens to be the pattern used by member-pointers.
1193   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1194     // For a VLA, emit a single element, then splat that over the VLA.
1195     if (vla) Ty = getContext().getBaseElementType(vla);
1196 
1197     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1198 
1199     llvm::GlobalVariable *NullVariable =
1200       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1201                                /*isConstant=*/true,
1202                                llvm::GlobalVariable::PrivateLinkage,
1203                                NullConstant, Twine());
1204     llvm::Value *SrcPtr =
1205       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1206 
1207     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1208 
1209     // Get and call the appropriate llvm.memcpy overload.
1210     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1211     return;
1212   }
1213 
1214   // Otherwise, just memset the whole thing to zero.  This is legal
1215   // because in LLVM, all default initializers (other than the ones we just
1216   // handled above) are guaranteed to have a bit pattern of all zeros.
1217   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1218                        Align.getQuantity(), false);
1219 }
1220 
1221 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1222   // Make sure that there is a block for the indirect goto.
1223   if (IndirectBranch == 0)
1224     GetIndirectGotoBlock();
1225 
1226   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1227 
1228   // Make sure the indirect branch includes all of the address-taken blocks.
1229   IndirectBranch->addDestination(BB);
1230   return llvm::BlockAddress::get(CurFn, BB);
1231 }
1232 
1233 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1234   // If we already made the indirect branch for indirect goto, return its block.
1235   if (IndirectBranch) return IndirectBranch->getParent();
1236 
1237   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1238 
1239   // Create the PHI node that indirect gotos will add entries to.
1240   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1241                                               "indirect.goto.dest");
1242 
1243   // Create the indirect branch instruction.
1244   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1245   return IndirectBranch->getParent();
1246 }
1247 
1248 /// Computes the length of an array in elements, as well as the base
1249 /// element type and a properly-typed first element pointer.
1250 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1251                                               QualType &baseType,
1252                                               llvm::Value *&addr) {
1253   const ArrayType *arrayType = origArrayType;
1254 
1255   // If it's a VLA, we have to load the stored size.  Note that
1256   // this is the size of the VLA in bytes, not its size in elements.
1257   llvm::Value *numVLAElements = 0;
1258   if (isa<VariableArrayType>(arrayType)) {
1259     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1260 
1261     // Walk into all VLAs.  This doesn't require changes to addr,
1262     // which has type T* where T is the first non-VLA element type.
1263     do {
1264       QualType elementType = arrayType->getElementType();
1265       arrayType = getContext().getAsArrayType(elementType);
1266 
1267       // If we only have VLA components, 'addr' requires no adjustment.
1268       if (!arrayType) {
1269         baseType = elementType;
1270         return numVLAElements;
1271       }
1272     } while (isa<VariableArrayType>(arrayType));
1273 
1274     // We get out here only if we find a constant array type
1275     // inside the VLA.
1276   }
1277 
1278   // We have some number of constant-length arrays, so addr should
1279   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1280   // down to the first element of addr.
1281   SmallVector<llvm::Value*, 8> gepIndices;
1282 
1283   // GEP down to the array type.
1284   llvm::ConstantInt *zero = Builder.getInt32(0);
1285   gepIndices.push_back(zero);
1286 
1287   uint64_t countFromCLAs = 1;
1288   QualType eltType;
1289 
1290   llvm::ArrayType *llvmArrayType =
1291     dyn_cast<llvm::ArrayType>(
1292       cast<llvm::PointerType>(addr->getType())->getElementType());
1293   while (llvmArrayType) {
1294     assert(isa<ConstantArrayType>(arrayType));
1295     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1296              == llvmArrayType->getNumElements());
1297 
1298     gepIndices.push_back(zero);
1299     countFromCLAs *= llvmArrayType->getNumElements();
1300     eltType = arrayType->getElementType();
1301 
1302     llvmArrayType =
1303       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1304     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1305     assert((!llvmArrayType || arrayType) &&
1306            "LLVM and Clang types are out-of-synch");
1307   }
1308 
1309   if (arrayType) {
1310     // From this point onwards, the Clang array type has been emitted
1311     // as some other type (probably a packed struct). Compute the array
1312     // size, and just emit the 'begin' expression as a bitcast.
1313     while (arrayType) {
1314       countFromCLAs *=
1315           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1316       eltType = arrayType->getElementType();
1317       arrayType = getContext().getAsArrayType(eltType);
1318     }
1319 
1320     unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1321     llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1322     addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1323   } else {
1324     // Create the actual GEP.
1325     addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1326   }
1327 
1328   baseType = eltType;
1329 
1330   llvm::Value *numElements
1331     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1332 
1333   // If we had any VLA dimensions, factor them in.
1334   if (numVLAElements)
1335     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1336 
1337   return numElements;
1338 }
1339 
1340 std::pair<llvm::Value*, QualType>
1341 CodeGenFunction::getVLASize(QualType type) {
1342   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1343   assert(vla && "type was not a variable array type!");
1344   return getVLASize(vla);
1345 }
1346 
1347 std::pair<llvm::Value*, QualType>
1348 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1349   // The number of elements so far; always size_t.
1350   llvm::Value *numElements = 0;
1351 
1352   QualType elementType;
1353   do {
1354     elementType = type->getElementType();
1355     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1356     assert(vlaSize && "no size for VLA!");
1357     assert(vlaSize->getType() == SizeTy);
1358 
1359     if (!numElements) {
1360       numElements = vlaSize;
1361     } else {
1362       // It's undefined behavior if this wraps around, so mark it that way.
1363       // FIXME: Teach -fcatch-undefined-behavior to trap this.
1364       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1365     }
1366   } while ((type = getContext().getAsVariableArrayType(elementType)));
1367 
1368   return std::pair<llvm::Value*,QualType>(numElements, elementType);
1369 }
1370 
1371 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1372   assert(type->isVariablyModifiedType() &&
1373          "Must pass variably modified type to EmitVLASizes!");
1374 
1375   EnsureInsertPoint();
1376 
1377   // We're going to walk down into the type and look for VLA
1378   // expressions.
1379   do {
1380     assert(type->isVariablyModifiedType());
1381 
1382     const Type *ty = type.getTypePtr();
1383     switch (ty->getTypeClass()) {
1384 
1385 #define TYPE(Class, Base)
1386 #define ABSTRACT_TYPE(Class, Base)
1387 #define NON_CANONICAL_TYPE(Class, Base)
1388 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1389 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1390 #include "clang/AST/TypeNodes.def"
1391       llvm_unreachable("unexpected dependent type!");
1392 
1393     // These types are never variably-modified.
1394     case Type::Builtin:
1395     case Type::Complex:
1396     case Type::Vector:
1397     case Type::ExtVector:
1398     case Type::Record:
1399     case Type::Enum:
1400     case Type::Elaborated:
1401     case Type::TemplateSpecialization:
1402     case Type::ObjCObject:
1403     case Type::ObjCInterface:
1404     case Type::ObjCObjectPointer:
1405       llvm_unreachable("type class is never variably-modified!");
1406 
1407     case Type::Adjusted:
1408       type = cast<AdjustedType>(ty)->getAdjustedType();
1409       break;
1410 
1411     case Type::Decayed:
1412       type = cast<DecayedType>(ty)->getPointeeType();
1413       break;
1414 
1415     case Type::Pointer:
1416       type = cast<PointerType>(ty)->getPointeeType();
1417       break;
1418 
1419     case Type::BlockPointer:
1420       type = cast<BlockPointerType>(ty)->getPointeeType();
1421       break;
1422 
1423     case Type::LValueReference:
1424     case Type::RValueReference:
1425       type = cast<ReferenceType>(ty)->getPointeeType();
1426       break;
1427 
1428     case Type::MemberPointer:
1429       type = cast<MemberPointerType>(ty)->getPointeeType();
1430       break;
1431 
1432     case Type::ConstantArray:
1433     case Type::IncompleteArray:
1434       // Losing element qualification here is fine.
1435       type = cast<ArrayType>(ty)->getElementType();
1436       break;
1437 
1438     case Type::VariableArray: {
1439       // Losing element qualification here is fine.
1440       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1441 
1442       // Unknown size indication requires no size computation.
1443       // Otherwise, evaluate and record it.
1444       if (const Expr *size = vat->getSizeExpr()) {
1445         // It's possible that we might have emitted this already,
1446         // e.g. with a typedef and a pointer to it.
1447         llvm::Value *&entry = VLASizeMap[size];
1448         if (!entry) {
1449           llvm::Value *Size = EmitScalarExpr(size);
1450 
1451           // C11 6.7.6.2p5:
1452           //   If the size is an expression that is not an integer constant
1453           //   expression [...] each time it is evaluated it shall have a value
1454           //   greater than zero.
1455           if (SanOpts->VLABound &&
1456               size->getType()->isSignedIntegerType()) {
1457             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1458             llvm::Constant *StaticArgs[] = {
1459               EmitCheckSourceLocation(size->getLocStart()),
1460               EmitCheckTypeDescriptor(size->getType())
1461             };
1462             EmitCheck(Builder.CreateICmpSGT(Size, Zero),
1463                       "vla_bound_not_positive", StaticArgs, Size,
1464                       CRK_Recoverable);
1465           }
1466 
1467           // Always zexting here would be wrong if it weren't
1468           // undefined behavior to have a negative bound.
1469           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1470         }
1471       }
1472       type = vat->getElementType();
1473       break;
1474     }
1475 
1476     case Type::FunctionProto:
1477     case Type::FunctionNoProto:
1478       type = cast<FunctionType>(ty)->getReturnType();
1479       break;
1480 
1481     case Type::Paren:
1482     case Type::TypeOf:
1483     case Type::UnaryTransform:
1484     case Type::Attributed:
1485     case Type::SubstTemplateTypeParm:
1486     case Type::PackExpansion:
1487       // Keep walking after single level desugaring.
1488       type = type.getSingleStepDesugaredType(getContext());
1489       break;
1490 
1491     case Type::Typedef:
1492     case Type::Decltype:
1493     case Type::Auto:
1494       // Stop walking: nothing to do.
1495       return;
1496 
1497     case Type::TypeOfExpr:
1498       // Stop walking: emit typeof expression.
1499       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1500       return;
1501 
1502     case Type::Atomic:
1503       type = cast<AtomicType>(ty)->getValueType();
1504       break;
1505     }
1506   } while (type->isVariablyModifiedType());
1507 }
1508 
1509 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
1510   if (getContext().getBuiltinVaListType()->isArrayType())
1511     return EmitScalarExpr(E);
1512   return EmitLValue(E).getAddress();
1513 }
1514 
1515 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1516                                               llvm::Constant *Init) {
1517   assert (Init && "Invalid DeclRefExpr initializer!");
1518   if (CGDebugInfo *Dbg = getDebugInfo())
1519     if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1520       Dbg->EmitGlobalVariable(E->getDecl(), Init);
1521 }
1522 
1523 CodeGenFunction::PeepholeProtection
1524 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1525   // At the moment, the only aggressive peephole we do in IR gen
1526   // is trunc(zext) folding, but if we add more, we can easily
1527   // extend this protection.
1528 
1529   if (!rvalue.isScalar()) return PeepholeProtection();
1530   llvm::Value *value = rvalue.getScalarVal();
1531   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1532 
1533   // Just make an extra bitcast.
1534   assert(HaveInsertPoint());
1535   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1536                                                   Builder.GetInsertBlock());
1537 
1538   PeepholeProtection protection;
1539   protection.Inst = inst;
1540   return protection;
1541 }
1542 
1543 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1544   if (!protection.Inst) return;
1545 
1546   // In theory, we could try to duplicate the peepholes now, but whatever.
1547   protection.Inst->eraseFromParent();
1548 }
1549 
1550 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1551                                                  llvm::Value *AnnotatedVal,
1552                                                  StringRef AnnotationStr,
1553                                                  SourceLocation Location) {
1554   llvm::Value *Args[4] = {
1555     AnnotatedVal,
1556     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1557     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1558     CGM.EmitAnnotationLineNo(Location)
1559   };
1560   return Builder.CreateCall(AnnotationFn, Args);
1561 }
1562 
1563 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1564   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1565   // FIXME We create a new bitcast for every annotation because that's what
1566   // llvm-gcc was doing.
1567   for (specific_attr_iterator<AnnotateAttr>
1568        ai = D->specific_attr_begin<AnnotateAttr>(),
1569        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1570     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1571                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1572                        (*ai)->getAnnotation(), D->getLocation());
1573 }
1574 
1575 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1576                                                    llvm::Value *V) {
1577   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1578   llvm::Type *VTy = V->getType();
1579   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1580                                     CGM.Int8PtrTy);
1581 
1582   for (specific_attr_iterator<AnnotateAttr>
1583        ai = D->specific_attr_begin<AnnotateAttr>(),
1584        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
1585     // FIXME Always emit the cast inst so we can differentiate between
1586     // annotation on the first field of a struct and annotation on the struct
1587     // itself.
1588     if (VTy != CGM.Int8PtrTy)
1589       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1590     V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
1591     V = Builder.CreateBitCast(V, VTy);
1592   }
1593 
1594   return V;
1595 }
1596 
1597 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1598