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