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