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