CodeGenFunction.cpp 41 KB

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