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