CodeGenFunction.cpp 40 KB

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