CodeGenFunction.cpp 41 KB

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