CodeGenFunction.cpp 39 KB

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