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