CodeGenModule.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGDebugInfo.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenTBAA.h"
  17. #include "CGCall.h"
  18. #include "CGCXXABI.h"
  19. #include "CGObjCRuntime.h"
  20. #include "TargetInfo.h"
  21. #include "clang/Frontend/CodeGenOptions.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/CharUnits.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/Mangle.h"
  28. #include "clang/AST/RecordLayout.h"
  29. #include "clang/Basic/Builtins.h"
  30. #include "clang/Basic/Diagnostic.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Basic/ConvertUTF.h"
  34. #include "llvm/CallingConv.h"
  35. #include "llvm/Module.h"
  36. #include "llvm/Intrinsics.h"
  37. #include "llvm/LLVMContext.h"
  38. #include "llvm/ADT/Triple.h"
  39. #include "llvm/Target/TargetData.h"
  40. #include "llvm/Support/CallSite.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. using namespace clang;
  43. using namespace CodeGen;
  44. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  45. switch (CGM.getContext().Target.getCXXABI()) {
  46. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  47. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  48. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  49. }
  50. llvm_unreachable("invalid C++ ABI kind");
  51. return *CreateItaniumCXXABI(CGM);
  52. }
  53. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  54. llvm::Module &M, const llvm::TargetData &TD,
  55. Diagnostic &diags)
  56. : BlockModule(C, M, TD, Types, *this), Context(C),
  57. Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
  58. TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
  59. ABI(createCXXABI(*this)),
  60. Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
  61. TBAA(0),
  62. VTables(*this), Runtime(0),
  63. CFConstantStringClassRef(0), ConstantStringClassRef(0),
  64. VMContext(M.getContext()),
  65. NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
  66. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  67. BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
  68. BlockObjectAssign(0), BlockObjectDispose(0){
  69. if (!Features.ObjC1)
  70. Runtime = 0;
  71. else if (!Features.NeXTRuntime)
  72. Runtime = CreateGNUObjCRuntime(*this);
  73. else if (Features.ObjCNonFragileABI)
  74. Runtime = CreateMacNonFragileABIObjCRuntime(*this);
  75. else
  76. Runtime = CreateMacObjCRuntime(*this);
  77. // Enable TBAA unless it's suppressed.
  78. if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
  79. TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
  80. ABI.getMangleContext());
  81. // If debug info generation is enabled, create the CGDebugInfo object.
  82. DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
  83. }
  84. CodeGenModule::~CodeGenModule() {
  85. delete Runtime;
  86. delete &ABI;
  87. delete TBAA;
  88. delete DebugInfo;
  89. }
  90. void CodeGenModule::createObjCRuntime() {
  91. if (!Features.NeXTRuntime)
  92. Runtime = CreateGNUObjCRuntime(*this);
  93. else if (Features.ObjCNonFragileABI)
  94. Runtime = CreateMacNonFragileABIObjCRuntime(*this);
  95. else
  96. Runtime = CreateMacObjCRuntime(*this);
  97. }
  98. void CodeGenModule::Release() {
  99. EmitDeferred();
  100. EmitCXXGlobalInitFunc();
  101. EmitCXXGlobalDtorFunc();
  102. if (Runtime)
  103. if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
  104. AddGlobalCtor(ObjCInitFunction);
  105. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  106. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  107. EmitAnnotations();
  108. EmitLLVMUsed();
  109. SimplifyPersonality();
  110. if (getCodeGenOpts().EmitDeclMetadata)
  111. EmitDeclMetadata();
  112. }
  113. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  114. if (!TBAA)
  115. return 0;
  116. return TBAA->getTBAAInfo(QTy);
  117. }
  118. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  119. llvm::MDNode *TBAAInfo) {
  120. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  121. }
  122. bool CodeGenModule::isTargetDarwin() const {
  123. return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
  124. }
  125. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  126. /// specified stmt yet.
  127. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  128. bool OmitOnError) {
  129. if (OmitOnError && getDiags().hasErrorOccurred())
  130. return;
  131. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
  132. "cannot compile this %0 yet");
  133. std::string Msg = Type;
  134. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  135. << Msg << S->getSourceRange();
  136. }
  137. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  138. /// specified decl yet.
  139. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  140. bool OmitOnError) {
  141. if (OmitOnError && getDiags().hasErrorOccurred())
  142. return;
  143. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
  144. "cannot compile this %0 yet");
  145. std::string Msg = Type;
  146. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  147. }
  148. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  149. const NamedDecl *D) const {
  150. // Internal definitions always have default visibility.
  151. if (GV->hasLocalLinkage()) {
  152. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  153. return;
  154. }
  155. // Set visibility for definitions.
  156. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  157. if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  158. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  159. }
  160. /// Set the symbol visibility of type information (vtable and RTTI)
  161. /// associated with the given type.
  162. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  163. const CXXRecordDecl *RD,
  164. TypeVisibilityKind TVK) const {
  165. setGlobalVisibility(GV, RD);
  166. if (!CodeGenOpts.HiddenWeakVTables)
  167. return;
  168. // We never want to drop the visibility for RTTI names.
  169. if (TVK == TVK_ForRTTIName)
  170. return;
  171. // We want to drop the visibility to hidden for weak type symbols.
  172. // This isn't possible if there might be unresolved references
  173. // elsewhere that rely on this symbol being visible.
  174. // This should be kept roughly in sync with setThunkVisibility
  175. // in CGVTables.cpp.
  176. // Preconditions.
  177. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  178. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  179. return;
  180. // Don't override an explicit visibility attribute.
  181. if (RD->hasAttr<VisibilityAttr>())
  182. return;
  183. switch (RD->getTemplateSpecializationKind()) {
  184. // We have to disable the optimization if this is an EI definition
  185. // because there might be EI declarations in other shared objects.
  186. case TSK_ExplicitInstantiationDefinition:
  187. case TSK_ExplicitInstantiationDeclaration:
  188. return;
  189. // Every use of a non-template class's type information has to emit it.
  190. case TSK_Undeclared:
  191. break;
  192. // In theory, implicit instantiations can ignore the possibility of
  193. // an explicit instantiation declaration because there necessarily
  194. // must be an EI definition somewhere with default visibility. In
  195. // practice, it's possible to have an explicit instantiation for
  196. // an arbitrary template class, and linkers aren't necessarily able
  197. // to deal with mixed-visibility symbols.
  198. case TSK_ExplicitSpecialization:
  199. case TSK_ImplicitInstantiation:
  200. if (!CodeGenOpts.HiddenWeakTemplateVTables)
  201. return;
  202. break;
  203. }
  204. // If there's a key function, there may be translation units
  205. // that don't have the key function's definition. But ignore
  206. // this if we're emitting RTTI under -fno-rtti.
  207. if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
  208. if (Context.getKeyFunction(RD))
  209. return;
  210. }
  211. // Otherwise, drop the visibility to hidden.
  212. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  213. GV->setUnnamedAddr(true);
  214. }
  215. llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  216. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  217. llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  218. if (!Str.empty())
  219. return Str;
  220. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  221. IdentifierInfo *II = ND->getIdentifier();
  222. assert(II && "Attempt to mangle unnamed decl.");
  223. Str = II->getName();
  224. return Str;
  225. }
  226. llvm::SmallString<256> Buffer;
  227. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  228. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
  229. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  230. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
  231. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  232. getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
  233. else
  234. getCXXABI().getMangleContext().mangleName(ND, Buffer);
  235. // Allocate space for the mangled name.
  236. size_t Length = Buffer.size();
  237. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  238. std::copy(Buffer.begin(), Buffer.end(), Name);
  239. Str = llvm::StringRef(Name, Length);
  240. return Str;
  241. }
  242. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  243. const BlockDecl *BD) {
  244. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  245. const Decl *D = GD.getDecl();
  246. if (D == 0)
  247. MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
  248. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  249. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
  250. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  251. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
  252. else
  253. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
  254. }
  255. llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
  256. return getModule().getNamedValue(Name);
  257. }
  258. /// AddGlobalCtor - Add a function to the list that will be called before
  259. /// main() runs.
  260. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  261. // FIXME: Type coercion of void()* types.
  262. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  263. }
  264. /// AddGlobalDtor - Add a function to the list that will be called
  265. /// when the module is unloaded.
  266. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  267. // FIXME: Type coercion of void()* types.
  268. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  269. }
  270. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  271. // Ctor function type is void()*.
  272. llvm::FunctionType* CtorFTy =
  273. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
  274. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  275. // Get the type of a ctor entry, { i32, void ()* }.
  276. llvm::StructType* CtorStructTy =
  277. llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
  278. llvm::PointerType::getUnqual(CtorFTy), NULL);
  279. // Construct the constructor and destructor arrays.
  280. std::vector<llvm::Constant*> Ctors;
  281. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  282. std::vector<llvm::Constant*> S;
  283. S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  284. I->second, false));
  285. S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
  286. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  287. }
  288. if (!Ctors.empty()) {
  289. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  290. new llvm::GlobalVariable(TheModule, AT, false,
  291. llvm::GlobalValue::AppendingLinkage,
  292. llvm::ConstantArray::get(AT, Ctors),
  293. GlobalName);
  294. }
  295. }
  296. void CodeGenModule::EmitAnnotations() {
  297. if (Annotations.empty())
  298. return;
  299. // Create a new global variable for the ConstantStruct in the Module.
  300. llvm::Constant *Array =
  301. llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
  302. Annotations.size()),
  303. Annotations);
  304. llvm::GlobalValue *gv =
  305. new llvm::GlobalVariable(TheModule, Array->getType(), false,
  306. llvm::GlobalValue::AppendingLinkage, Array,
  307. "llvm.global.annotations");
  308. gv->setSection("llvm.metadata");
  309. }
  310. llvm::GlobalValue::LinkageTypes
  311. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  312. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  313. if (Linkage == GVA_Internal)
  314. return llvm::Function::InternalLinkage;
  315. if (D->hasAttr<DLLExportAttr>())
  316. return llvm::Function::DLLExportLinkage;
  317. if (D->hasAttr<WeakAttr>())
  318. return llvm::Function::WeakAnyLinkage;
  319. // In C99 mode, 'inline' functions are guaranteed to have a strong
  320. // definition somewhere else, so we can use available_externally linkage.
  321. if (Linkage == GVA_C99Inline)
  322. return llvm::Function::AvailableExternallyLinkage;
  323. // In C++, the compiler has to emit a definition in every translation unit
  324. // that references the function. We should use linkonce_odr because
  325. // a) if all references in this translation unit are optimized away, we
  326. // don't need to codegen it. b) if the function persists, it needs to be
  327. // merged with other definitions. c) C++ has the ODR, so we know the
  328. // definition is dependable.
  329. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  330. return llvm::Function::LinkOnceODRLinkage;
  331. // An explicit instantiation of a template has weak linkage, since
  332. // explicit instantiations can occur in multiple translation units
  333. // and must all be equivalent. However, we are not allowed to
  334. // throw away these explicit instantiations.
  335. if (Linkage == GVA_ExplicitTemplateInstantiation)
  336. return llvm::Function::WeakODRLinkage;
  337. // Otherwise, we have strong external linkage.
  338. assert(Linkage == GVA_StrongExternal);
  339. return llvm::Function::ExternalLinkage;
  340. }
  341. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  342. ///
  343. /// FIXME: This is currently only done for aliases and functions, but not for
  344. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  345. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  346. llvm::GlobalValue *GV) {
  347. SetCommonAttributes(D, GV);
  348. }
  349. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  350. const CGFunctionInfo &Info,
  351. llvm::Function *F) {
  352. unsigned CallingConv;
  353. AttributeListType AttributeList;
  354. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  355. F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
  356. AttributeList.size()));
  357. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  358. }
  359. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  360. llvm::Function *F) {
  361. if (!Features.Exceptions && !Features.ObjCNonFragileABI)
  362. F->addFnAttr(llvm::Attribute::NoUnwind);
  363. if (D->hasAttr<AlwaysInlineAttr>())
  364. F->addFnAttr(llvm::Attribute::AlwaysInline);
  365. if (D->hasAttr<NakedAttr>())
  366. F->addFnAttr(llvm::Attribute::Naked);
  367. if (D->hasAttr<NoInlineAttr>())
  368. F->addFnAttr(llvm::Attribute::NoInline);
  369. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  370. F->setUnnamedAddr(true);
  371. if (Features.getStackProtectorMode() == LangOptions::SSPOn)
  372. F->addFnAttr(llvm::Attribute::StackProtect);
  373. else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
  374. F->addFnAttr(llvm::Attribute::StackProtectReq);
  375. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  376. if (alignment)
  377. F->setAlignment(alignment);
  378. // C++ ABI requires 2-byte alignment for member functions.
  379. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  380. F->setAlignment(2);
  381. }
  382. void CodeGenModule::SetCommonAttributes(const Decl *D,
  383. llvm::GlobalValue *GV) {
  384. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  385. setGlobalVisibility(GV, ND);
  386. else
  387. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  388. if (D->hasAttr<UsedAttr>())
  389. AddUsedGlobal(GV);
  390. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  391. GV->setSection(SA->getName());
  392. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  393. }
  394. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  395. llvm::Function *F,
  396. const CGFunctionInfo &FI) {
  397. SetLLVMFunctionAttributes(D, FI, F);
  398. SetLLVMFunctionAttributesForDefinition(D, F);
  399. F->setLinkage(llvm::Function::InternalLinkage);
  400. SetCommonAttributes(D, F);
  401. }
  402. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  403. llvm::Function *F,
  404. bool IsIncompleteFunction) {
  405. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  406. if (!IsIncompleteFunction)
  407. SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
  408. // Only a few attributes are set on declarations; these may later be
  409. // overridden by a definition.
  410. if (FD->hasAttr<DLLImportAttr>()) {
  411. F->setLinkage(llvm::Function::DLLImportLinkage);
  412. } else if (FD->hasAttr<WeakAttr>() ||
  413. FD->hasAttr<WeakImportAttr>()) {
  414. // "extern_weak" is overloaded in LLVM; we probably should have
  415. // separate linkage types for this.
  416. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  417. } else {
  418. F->setLinkage(llvm::Function::ExternalLinkage);
  419. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  420. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  421. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  422. }
  423. }
  424. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  425. F->setSection(SA->getName());
  426. }
  427. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  428. assert(!GV->isDeclaration() &&
  429. "Only globals with definition can force usage.");
  430. LLVMUsed.push_back(GV);
  431. }
  432. void CodeGenModule::EmitLLVMUsed() {
  433. // Don't create llvm.used if there is no need.
  434. if (LLVMUsed.empty())
  435. return;
  436. const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
  437. // Convert LLVMUsed to what ConstantArray needs.
  438. std::vector<llvm::Constant*> UsedArray;
  439. UsedArray.resize(LLVMUsed.size());
  440. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  441. UsedArray[i] =
  442. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  443. i8PTy);
  444. }
  445. if (UsedArray.empty())
  446. return;
  447. llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
  448. llvm::GlobalVariable *GV =
  449. new llvm::GlobalVariable(getModule(), ATy, false,
  450. llvm::GlobalValue::AppendingLinkage,
  451. llvm::ConstantArray::get(ATy, UsedArray),
  452. "llvm.used");
  453. GV->setSection("llvm.metadata");
  454. }
  455. void CodeGenModule::EmitDeferred() {
  456. // Emit code for any potentially referenced deferred decls. Since a
  457. // previously unused static decl may become used during the generation of code
  458. // for a static function, iterate until no changes are made.
  459. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  460. if (!DeferredVTables.empty()) {
  461. const CXXRecordDecl *RD = DeferredVTables.back();
  462. DeferredVTables.pop_back();
  463. getVTables().GenerateClassData(getVTableLinkage(RD), RD);
  464. continue;
  465. }
  466. GlobalDecl D = DeferredDeclsToEmit.back();
  467. DeferredDeclsToEmit.pop_back();
  468. // Check to see if we've already emitted this. This is necessary
  469. // for a couple of reasons: first, decls can end up in the
  470. // deferred-decls queue multiple times, and second, decls can end
  471. // up with definitions in unusual ways (e.g. by an extern inline
  472. // function acquiring a strong function redefinition). Just
  473. // ignore these cases.
  474. //
  475. // TODO: That said, looking this up multiple times is very wasteful.
  476. llvm::StringRef Name = getMangledName(D);
  477. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  478. assert(CGRef && "Deferred decl wasn't referenced?");
  479. if (!CGRef->isDeclaration())
  480. continue;
  481. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  482. // purposes an alias counts as a definition.
  483. if (isa<llvm::GlobalAlias>(CGRef))
  484. continue;
  485. // Otherwise, emit the definition and move on to the next one.
  486. EmitGlobalDefinition(D);
  487. }
  488. }
  489. /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
  490. /// annotation information for a given GlobalValue. The annotation struct is
  491. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  492. /// GlobalValue being annotated. The second field is the constant string
  493. /// created from the AnnotateAttr's annotation. The third field is a constant
  494. /// string containing the name of the translation unit. The fourth field is
  495. /// the line number in the file of the annotated value declaration.
  496. ///
  497. /// FIXME: this does not unique the annotation string constants, as llvm-gcc
  498. /// appears to.
  499. ///
  500. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  501. const AnnotateAttr *AA,
  502. unsigned LineNo) {
  503. llvm::Module *M = &getModule();
  504. // get [N x i8] constants for the annotation string, and the filename string
  505. // which are the 2nd and 3rd elements of the global annotation structure.
  506. const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
  507. llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
  508. AA->getAnnotation(), true);
  509. llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
  510. M->getModuleIdentifier(),
  511. true);
  512. // Get the two global values corresponding to the ConstantArrays we just
  513. // created to hold the bytes of the strings.
  514. llvm::GlobalValue *annoGV =
  515. new llvm::GlobalVariable(*M, anno->getType(), false,
  516. llvm::GlobalValue::PrivateLinkage, anno,
  517. GV->getName());
  518. // translation unit name string, emitted into the llvm.metadata section.
  519. llvm::GlobalValue *unitGV =
  520. new llvm::GlobalVariable(*M, unit->getType(), false,
  521. llvm::GlobalValue::PrivateLinkage, unit,
  522. ".str");
  523. unitGV->setUnnamedAddr(true);
  524. // Create the ConstantStruct for the global annotation.
  525. llvm::Constant *Fields[4] = {
  526. llvm::ConstantExpr::getBitCast(GV, SBP),
  527. llvm::ConstantExpr::getBitCast(annoGV, SBP),
  528. llvm::ConstantExpr::getBitCast(unitGV, SBP),
  529. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
  530. };
  531. return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
  532. }
  533. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  534. // Never defer when EmitAllDecls is specified.
  535. if (Features.EmitAllDecls)
  536. return false;
  537. return !getContext().DeclMustBeEmitted(Global);
  538. }
  539. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  540. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  541. assert(AA && "No alias?");
  542. const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  543. // See if there is already something with the target's name in the module.
  544. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  545. llvm::Constant *Aliasee;
  546. if (isa<llvm::FunctionType>(DeclTy))
  547. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
  548. else
  549. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  550. llvm::PointerType::getUnqual(DeclTy), 0);
  551. if (!Entry) {
  552. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  553. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  554. WeakRefReferences.insert(F);
  555. }
  556. return Aliasee;
  557. }
  558. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  559. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  560. // Weak references don't produce any output by themselves.
  561. if (Global->hasAttr<WeakRefAttr>())
  562. return;
  563. // If this is an alias definition (which otherwise looks like a declaration)
  564. // emit it now.
  565. if (Global->hasAttr<AliasAttr>())
  566. return EmitAliasDefinition(GD);
  567. // Ignore declarations, they will be emitted on their first use.
  568. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  569. if (FD->getIdentifier()) {
  570. llvm::StringRef Name = FD->getName();
  571. if (Name == "_Block_object_assign") {
  572. BlockObjectAssignDecl = FD;
  573. } else if (Name == "_Block_object_dispose") {
  574. BlockObjectDisposeDecl = FD;
  575. }
  576. }
  577. // Forward declarations are emitted lazily on first use.
  578. if (!FD->isThisDeclarationADefinition())
  579. return;
  580. } else {
  581. const VarDecl *VD = cast<VarDecl>(Global);
  582. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  583. if (VD->getIdentifier()) {
  584. llvm::StringRef Name = VD->getName();
  585. if (Name == "_NSConcreteGlobalBlock") {
  586. NSConcreteGlobalBlockDecl = VD;
  587. } else if (Name == "_NSConcreteStackBlock") {
  588. NSConcreteStackBlockDecl = VD;
  589. }
  590. }
  591. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  592. return;
  593. }
  594. // Defer code generation when possible if this is a static definition, inline
  595. // function etc. These we only want to emit if they are used.
  596. if (!MayDeferGeneration(Global)) {
  597. // Emit the definition if it can't be deferred.
  598. EmitGlobalDefinition(GD);
  599. return;
  600. }
  601. // If we're deferring emission of a C++ variable with an
  602. // initializer, remember the order in which it appeared in the file.
  603. if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
  604. cast<VarDecl>(Global)->hasInit()) {
  605. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  606. CXXGlobalInits.push_back(0);
  607. }
  608. // If the value has already been used, add it directly to the
  609. // DeferredDeclsToEmit list.
  610. llvm::StringRef MangledName = getMangledName(GD);
  611. if (GetGlobalValue(MangledName))
  612. DeferredDeclsToEmit.push_back(GD);
  613. else {
  614. // Otherwise, remember that we saw a deferred decl with this name. The
  615. // first use of the mangled name will cause it to move into
  616. // DeferredDeclsToEmit.
  617. DeferredDecls[MangledName] = GD;
  618. }
  619. }
  620. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  621. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  622. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  623. Context.getSourceManager(),
  624. "Generating code for declaration");
  625. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  626. // At -O0, don't generate IR for functions with available_externally
  627. // linkage.
  628. if (CodeGenOpts.OptimizationLevel == 0 &&
  629. !Function->hasAttr<AlwaysInlineAttr>() &&
  630. getFunctionLinkage(Function)
  631. == llvm::Function::AvailableExternallyLinkage)
  632. return;
  633. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  634. if (Method->isVirtual())
  635. getVTables().EmitThunks(GD);
  636. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  637. return EmitCXXConstructor(CD, GD.getCtorType());
  638. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
  639. return EmitCXXDestructor(DD, GD.getDtorType());
  640. }
  641. return EmitGlobalFunctionDefinition(GD);
  642. }
  643. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  644. return EmitGlobalVarDefinition(VD);
  645. assert(0 && "Invalid argument to EmitGlobalDefinition()");
  646. }
  647. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  648. /// module, create and return an llvm Function with the specified type. If there
  649. /// is something in the module with the specified name, return it potentially
  650. /// bitcasted to the right type.
  651. ///
  652. /// If D is non-null, it specifies a decl that correspond to this. This is used
  653. /// to set the attributes on the function when it is first created.
  654. llvm::Constant *
  655. CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
  656. const llvm::Type *Ty,
  657. GlobalDecl D) {
  658. // Lookup the entry, lazily creating it if necessary.
  659. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  660. if (Entry) {
  661. if (WeakRefReferences.count(Entry)) {
  662. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  663. if (FD && !FD->hasAttr<WeakAttr>())
  664. Entry->setLinkage(llvm::Function::ExternalLinkage);
  665. WeakRefReferences.erase(Entry);
  666. }
  667. if (Entry->getType()->getElementType() == Ty)
  668. return Entry;
  669. // Make sure the result is of the correct type.
  670. const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  671. return llvm::ConstantExpr::getBitCast(Entry, PTy);
  672. }
  673. // This function doesn't have a complete type (for example, the return
  674. // type is an incomplete struct). Use a fake type instead, and make
  675. // sure not to try to set attributes.
  676. bool IsIncompleteFunction = false;
  677. const llvm::FunctionType *FTy;
  678. if (isa<llvm::FunctionType>(Ty)) {
  679. FTy = cast<llvm::FunctionType>(Ty);
  680. } else {
  681. FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
  682. IsIncompleteFunction = true;
  683. }
  684. llvm::Function *F = llvm::Function::Create(FTy,
  685. llvm::Function::ExternalLinkage,
  686. MangledName, &getModule());
  687. assert(F->getName() == MangledName && "name was uniqued!");
  688. if (D.getDecl())
  689. SetFunctionAttributes(D, F, IsIncompleteFunction);
  690. // This is the first use or definition of a mangled name. If there is a
  691. // deferred decl with this name, remember that we need to emit it at the end
  692. // of the file.
  693. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  694. if (DDI != DeferredDecls.end()) {
  695. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  696. // list, and remove it from DeferredDecls (since we don't need it anymore).
  697. DeferredDeclsToEmit.push_back(DDI->second);
  698. DeferredDecls.erase(DDI);
  699. // Otherwise, there are cases we have to worry about where we're
  700. // using a declaration for which we must emit a definition but where
  701. // we might not find a top-level definition:
  702. // - member functions defined inline in their classes
  703. // - friend functions defined inline in some class
  704. // - special member functions with implicit definitions
  705. // If we ever change our AST traversal to walk into class methods,
  706. // this will be unnecessary.
  707. } else if (getLangOptions().CPlusPlus && D.getDecl()) {
  708. // Look for a declaration that's lexically in a record.
  709. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  710. do {
  711. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  712. if (FD->isImplicit()) {
  713. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  714. DeferredDeclsToEmit.push_back(D);
  715. break;
  716. } else if (FD->isThisDeclarationADefinition()) {
  717. DeferredDeclsToEmit.push_back(D);
  718. break;
  719. }
  720. }
  721. FD = FD->getPreviousDeclaration();
  722. } while (FD);
  723. }
  724. // Make sure the result is of the requested type.
  725. if (!IsIncompleteFunction) {
  726. assert(F->getType()->getElementType() == Ty);
  727. return F;
  728. }
  729. const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  730. return llvm::ConstantExpr::getBitCast(F, PTy);
  731. }
  732. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  733. /// non-null, then this function will use the specified type if it has to
  734. /// create it (this occurs when we see a definition of the function).
  735. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  736. const llvm::Type *Ty) {
  737. // If there was no specific requested type, just convert it now.
  738. if (!Ty)
  739. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  740. llvm::StringRef MangledName = getMangledName(GD);
  741. return GetOrCreateLLVMFunction(MangledName, Ty, GD);
  742. }
  743. /// CreateRuntimeFunction - Create a new runtime function with the specified
  744. /// type and name.
  745. llvm::Constant *
  746. CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
  747. llvm::StringRef Name) {
  748. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
  749. }
  750. static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
  751. if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
  752. return false;
  753. if (Context.getLangOptions().CPlusPlus &&
  754. Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
  755. // FIXME: We should do something fancier here!
  756. return false;
  757. }
  758. return true;
  759. }
  760. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  761. /// create and return an llvm GlobalVariable with the specified type. If there
  762. /// is something in the module with the specified name, return it potentially
  763. /// bitcasted to the right type.
  764. ///
  765. /// If D is non-null, it specifies a decl that correspond to this. This is used
  766. /// to set the attributes on the global when it is first created.
  767. llvm::Constant *
  768. CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
  769. const llvm::PointerType *Ty,
  770. const VarDecl *D,
  771. bool UnnamedAddr) {
  772. // Lookup the entry, lazily creating it if necessary.
  773. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  774. if (Entry) {
  775. if (WeakRefReferences.count(Entry)) {
  776. if (D && !D->hasAttr<WeakAttr>())
  777. Entry->setLinkage(llvm::Function::ExternalLinkage);
  778. WeakRefReferences.erase(Entry);
  779. }
  780. if (UnnamedAddr)
  781. Entry->setUnnamedAddr(true);
  782. if (Entry->getType() == Ty)
  783. return Entry;
  784. // Make sure the result is of the correct type.
  785. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  786. }
  787. // This is the first use or definition of a mangled name. If there is a
  788. // deferred decl with this name, remember that we need to emit it at the end
  789. // of the file.
  790. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  791. if (DDI != DeferredDecls.end()) {
  792. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  793. // list, and remove it from DeferredDecls (since we don't need it anymore).
  794. DeferredDeclsToEmit.push_back(DDI->second);
  795. DeferredDecls.erase(DDI);
  796. }
  797. llvm::GlobalVariable *GV =
  798. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  799. llvm::GlobalValue::ExternalLinkage,
  800. 0, MangledName, 0,
  801. false, Ty->getAddressSpace());
  802. // Handle things which are present even on external declarations.
  803. if (D) {
  804. // FIXME: This code is overly simple and should be merged with other global
  805. // handling.
  806. GV->setConstant(DeclIsConstantGlobal(Context, D));
  807. // Set linkage and visibility in case we never see a definition.
  808. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  809. if (LV.linkage() != ExternalLinkage) {
  810. GV->setLinkage(llvm::GlobalValue::InternalLinkage);
  811. } else {
  812. if (D->hasAttr<DLLImportAttr>())
  813. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  814. else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
  815. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  816. // Set visibility on a declaration only if it's explicit.
  817. if (LV.visibilityExplicit())
  818. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  819. }
  820. GV->setThreadLocal(D->isThreadSpecified());
  821. }
  822. return GV;
  823. }
  824. llvm::GlobalVariable *
  825. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
  826. const llvm::Type *Ty,
  827. llvm::GlobalValue::LinkageTypes Linkage) {
  828. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  829. llvm::GlobalVariable *OldGV = 0;
  830. if (GV) {
  831. // Check if the variable has the right type.
  832. if (GV->getType()->getElementType() == Ty)
  833. return GV;
  834. // Because C++ name mangling, the only way we can end up with an already
  835. // existing global with the same name is if it has been declared extern "C".
  836. assert(GV->isDeclaration() && "Declaration has wrong type!");
  837. OldGV = GV;
  838. }
  839. // Create a new variable.
  840. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  841. Linkage, 0, Name);
  842. if (OldGV) {
  843. // Replace occurrences of the old variable if needed.
  844. GV->takeName(OldGV);
  845. if (!OldGV->use_empty()) {
  846. llvm::Constant *NewPtrForOldDecl =
  847. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  848. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  849. }
  850. OldGV->eraseFromParent();
  851. }
  852. return GV;
  853. }
  854. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  855. /// given global variable. If Ty is non-null and if the global doesn't exist,
  856. /// then it will be greated with the specified type instead of whatever the
  857. /// normal requested type would be.
  858. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  859. const llvm::Type *Ty) {
  860. assert(D->hasGlobalStorage() && "Not a global variable");
  861. QualType ASTTy = D->getType();
  862. if (Ty == 0)
  863. Ty = getTypes().ConvertTypeForMem(ASTTy);
  864. const llvm::PointerType *PTy =
  865. llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
  866. llvm::StringRef MangledName = getMangledName(D);
  867. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  868. }
  869. /// CreateRuntimeVariable - Create a new runtime global variable with the
  870. /// specified type and name.
  871. llvm::Constant *
  872. CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
  873. llvm::StringRef Name) {
  874. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  875. true);
  876. }
  877. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  878. assert(!D->getInit() && "Cannot emit definite definitions here!");
  879. if (MayDeferGeneration(D)) {
  880. // If we have not seen a reference to this variable yet, place it
  881. // into the deferred declarations table to be emitted if needed
  882. // later.
  883. llvm::StringRef MangledName = getMangledName(D);
  884. if (!GetGlobalValue(MangledName)) {
  885. DeferredDecls[MangledName] = D;
  886. return;
  887. }
  888. }
  889. // The tentative definition is the only definition.
  890. EmitGlobalVarDefinition(D);
  891. }
  892. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  893. if (DefinitionRequired)
  894. getVTables().GenerateClassData(getVTableLinkage(Class), Class);
  895. }
  896. llvm::GlobalVariable::LinkageTypes
  897. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  898. if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
  899. return llvm::GlobalVariable::InternalLinkage;
  900. if (const CXXMethodDecl *KeyFunction
  901. = RD->getASTContext().getKeyFunction(RD)) {
  902. // If this class has a key function, use that to determine the linkage of
  903. // the vtable.
  904. const FunctionDecl *Def = 0;
  905. if (KeyFunction->hasBody(Def))
  906. KeyFunction = cast<CXXMethodDecl>(Def);
  907. switch (KeyFunction->getTemplateSpecializationKind()) {
  908. case TSK_Undeclared:
  909. case TSK_ExplicitSpecialization:
  910. // When compiling with optimizations turned on, we emit all vtables,
  911. // even if the key function is not defined in the current translation
  912. // unit. If this is the case, use available_externally linkage.
  913. if (!Def && CodeGenOpts.OptimizationLevel)
  914. return llvm::GlobalVariable::AvailableExternallyLinkage;
  915. if (KeyFunction->isInlined())
  916. return llvm::GlobalVariable::LinkOnceODRLinkage;
  917. return llvm::GlobalVariable::ExternalLinkage;
  918. case TSK_ImplicitInstantiation:
  919. return llvm::GlobalVariable::LinkOnceODRLinkage;
  920. case TSK_ExplicitInstantiationDefinition:
  921. return llvm::GlobalVariable::WeakODRLinkage;
  922. case TSK_ExplicitInstantiationDeclaration:
  923. // FIXME: Use available_externally linkage. However, this currently
  924. // breaks LLVM's build due to undefined symbols.
  925. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  926. return llvm::GlobalVariable::LinkOnceODRLinkage;
  927. }
  928. }
  929. switch (RD->getTemplateSpecializationKind()) {
  930. case TSK_Undeclared:
  931. case TSK_ExplicitSpecialization:
  932. case TSK_ImplicitInstantiation:
  933. return llvm::GlobalVariable::LinkOnceODRLinkage;
  934. case TSK_ExplicitInstantiationDefinition:
  935. return llvm::GlobalVariable::WeakODRLinkage;
  936. case TSK_ExplicitInstantiationDeclaration:
  937. // FIXME: Use available_externally linkage. However, this currently
  938. // breaks LLVM's build due to undefined symbols.
  939. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  940. return llvm::GlobalVariable::LinkOnceODRLinkage;
  941. }
  942. // Silence GCC warning.
  943. return llvm::GlobalVariable::LinkOnceODRLinkage;
  944. }
  945. CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
  946. return Context.toCharUnitsFromBits(
  947. TheTargetData.getTypeStoreSizeInBits(Ty));
  948. }
  949. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  950. llvm::Constant *Init = 0;
  951. QualType ASTTy = D->getType();
  952. bool NonConstInit = false;
  953. const Expr *InitExpr = D->getAnyInitializer();
  954. if (!InitExpr) {
  955. // This is a tentative definition; tentative definitions are
  956. // implicitly initialized with { 0 }.
  957. //
  958. // Note that tentative definitions are only emitted at the end of
  959. // a translation unit, so they should never have incomplete
  960. // type. In addition, EmitTentativeDefinition makes sure that we
  961. // never attempt to emit a tentative definition if a real one
  962. // exists. A use may still exists, however, so we still may need
  963. // to do a RAUW.
  964. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  965. Init = EmitNullConstant(D->getType());
  966. } else {
  967. Init = EmitConstantExpr(InitExpr, D->getType());
  968. if (!Init) {
  969. QualType T = InitExpr->getType();
  970. if (D->getType()->isReferenceType())
  971. T = D->getType();
  972. if (getLangOptions().CPlusPlus) {
  973. Init = EmitNullConstant(T);
  974. NonConstInit = true;
  975. } else {
  976. ErrorUnsupported(D, "static initializer");
  977. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  978. }
  979. } else {
  980. // We don't need an initializer, so remove the entry for the delayed
  981. // initializer position (just in case this entry was delayed).
  982. if (getLangOptions().CPlusPlus)
  983. DelayedCXXInitPosition.erase(D);
  984. }
  985. }
  986. const llvm::Type* InitType = Init->getType();
  987. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  988. // Strip off a bitcast if we got one back.
  989. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  990. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  991. // all zero index gep.
  992. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  993. Entry = CE->getOperand(0);
  994. }
  995. // Entry is now either a Function or GlobalVariable.
  996. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  997. // We have a definition after a declaration with the wrong type.
  998. // We must make a new GlobalVariable* and update everything that used OldGV
  999. // (a declaration or tentative definition) with the new GlobalVariable*
  1000. // (which will be a definition).
  1001. //
  1002. // This happens if there is a prototype for a global (e.g.
  1003. // "extern int x[];") and then a definition of a different type (e.g.
  1004. // "int x[10];"). This also happens when an initializer has a different type
  1005. // from the type of the global (this happens with unions).
  1006. if (GV == 0 ||
  1007. GV->getType()->getElementType() != InitType ||
  1008. GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
  1009. // Move the old entry aside so that we'll create a new one.
  1010. Entry->setName(llvm::StringRef());
  1011. // Make a new global with the correct type, this is now guaranteed to work.
  1012. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1013. // Replace all uses of the old global with the new global
  1014. llvm::Constant *NewPtrForOldDecl =
  1015. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1016. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1017. // Erase the old global, since it is no longer used.
  1018. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1019. }
  1020. if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
  1021. SourceManager &SM = Context.getSourceManager();
  1022. AddAnnotation(EmitAnnotateAttr(GV, AA,
  1023. SM.getInstantiationLineNumber(D->getLocation())));
  1024. }
  1025. GV->setInitializer(Init);
  1026. // If it is safe to mark the global 'constant', do so now.
  1027. GV->setConstant(false);
  1028. if (!NonConstInit && DeclIsConstantGlobal(Context, D))
  1029. GV->setConstant(true);
  1030. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1031. // Set the llvm linkage type as appropriate.
  1032. llvm::GlobalValue::LinkageTypes Linkage =
  1033. GetLLVMLinkageVarDefinition(D, GV);
  1034. GV->setLinkage(Linkage);
  1035. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1036. // common vars aren't constant even if declared const.
  1037. GV->setConstant(false);
  1038. SetCommonAttributes(D, GV);
  1039. // Emit the initializer function if necessary.
  1040. if (NonConstInit)
  1041. EmitCXXGlobalVarDeclInitFunc(D, GV);
  1042. // Emit global variable debug information.
  1043. if (CGDebugInfo *DI = getDebugInfo()) {
  1044. DI->setLocation(D->getLocation());
  1045. DI->EmitGlobalVariable(GV, D);
  1046. }
  1047. }
  1048. llvm::GlobalValue::LinkageTypes
  1049. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1050. llvm::GlobalVariable *GV) {
  1051. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1052. if (Linkage == GVA_Internal)
  1053. return llvm::Function::InternalLinkage;
  1054. else if (D->hasAttr<DLLImportAttr>())
  1055. return llvm::Function::DLLImportLinkage;
  1056. else if (D->hasAttr<DLLExportAttr>())
  1057. return llvm::Function::DLLExportLinkage;
  1058. else if (D->hasAttr<WeakAttr>()) {
  1059. if (GV->isConstant())
  1060. return llvm::GlobalVariable::WeakODRLinkage;
  1061. else
  1062. return llvm::GlobalVariable::WeakAnyLinkage;
  1063. } else if (Linkage == GVA_TemplateInstantiation ||
  1064. Linkage == GVA_ExplicitTemplateInstantiation)
  1065. // FIXME: It seems like we can provide more specific linkage here
  1066. // (LinkOnceODR, WeakODR).
  1067. return llvm::GlobalVariable::WeakAnyLinkage;
  1068. else if (!getLangOptions().CPlusPlus &&
  1069. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1070. D->getAttr<CommonAttr>()) &&
  1071. !D->hasExternalStorage() && !D->getInit() &&
  1072. !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
  1073. // Thread local vars aren't considered common linkage.
  1074. return llvm::GlobalVariable::CommonLinkage;
  1075. }
  1076. return llvm::GlobalVariable::ExternalLinkage;
  1077. }
  1078. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1079. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1080. /// existing call uses of the old function in the module, this adjusts them to
  1081. /// call the new function directly.
  1082. ///
  1083. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1084. /// functions to be able to inline them. If there is a bitcast in the way, it
  1085. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1086. /// run at -O0.
  1087. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1088. llvm::Function *NewFn) {
  1089. // If we're redefining a global as a function, don't transform it.
  1090. llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
  1091. if (OldFn == 0) return;
  1092. const llvm::Type *NewRetTy = NewFn->getReturnType();
  1093. llvm::SmallVector<llvm::Value*, 4> ArgList;
  1094. for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
  1095. UI != E; ) {
  1096. // TODO: Do invokes ever occur in C code? If so, we should handle them too.
  1097. llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
  1098. llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
  1099. if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
  1100. llvm::CallSite CS(CI);
  1101. if (!CI || !CS.isCallee(I)) continue;
  1102. // If the return types don't match exactly, and if the call isn't dead, then
  1103. // we can't transform this call.
  1104. if (CI->getType() != NewRetTy && !CI->use_empty())
  1105. continue;
  1106. // If the function was passed too few arguments, don't transform. If extra
  1107. // arguments were passed, we silently drop them. If any of the types
  1108. // mismatch, we don't transform.
  1109. unsigned ArgNo = 0;
  1110. bool DontTransform = false;
  1111. for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
  1112. E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
  1113. if (CS.arg_size() == ArgNo ||
  1114. CS.getArgument(ArgNo)->getType() != AI->getType()) {
  1115. DontTransform = true;
  1116. break;
  1117. }
  1118. }
  1119. if (DontTransform)
  1120. continue;
  1121. // Okay, we can transform this. Create the new call instruction and copy
  1122. // over the required information.
  1123. ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
  1124. llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
  1125. ArgList.end(), "", CI);
  1126. ArgList.clear();
  1127. if (!NewCall->getType()->isVoidTy())
  1128. NewCall->takeName(CI);
  1129. NewCall->setAttributes(CI->getAttributes());
  1130. NewCall->setCallingConv(CI->getCallingConv());
  1131. // Finally, remove the old call, replacing any uses with the new one.
  1132. if (!CI->use_empty())
  1133. CI->replaceAllUsesWith(NewCall);
  1134. // Copy debug location attached to CI.
  1135. if (!CI->getDebugLoc().isUnknown())
  1136. NewCall->setDebugLoc(CI->getDebugLoc());
  1137. CI->eraseFromParent();
  1138. }
  1139. }
  1140. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1141. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1142. const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
  1143. // Get or create the prototype for the function.
  1144. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1145. // Strip off a bitcast if we got one back.
  1146. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1147. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1148. Entry = CE->getOperand(0);
  1149. }
  1150. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1151. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1152. // If the types mismatch then we have to rewrite the definition.
  1153. assert(OldFn->isDeclaration() &&
  1154. "Shouldn't replace non-declaration");
  1155. // F is the Function* for the one with the wrong type, we must make a new
  1156. // Function* and update everything that used F (a declaration) with the new
  1157. // Function* (which will be a definition).
  1158. //
  1159. // This happens if there is a prototype for a function
  1160. // (e.g. "int f()") and then a definition of a different type
  1161. // (e.g. "int f(int x)"). Move the old function aside so that it
  1162. // doesn't interfere with GetAddrOfFunction.
  1163. OldFn->setName(llvm::StringRef());
  1164. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1165. // If this is an implementation of a function without a prototype, try to
  1166. // replace any existing uses of the function (which may be calls) with uses
  1167. // of the new function
  1168. if (D->getType()->isFunctionNoProtoType()) {
  1169. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1170. OldFn->removeDeadConstantUsers();
  1171. }
  1172. // Replace uses of F with the Function we will endow with a body.
  1173. if (!Entry->use_empty()) {
  1174. llvm::Constant *NewPtrForOldDecl =
  1175. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1176. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1177. }
  1178. // Ok, delete the old function now, which is dead.
  1179. OldFn->eraseFromParent();
  1180. Entry = NewFn;
  1181. }
  1182. // We need to set linkage and visibility on the function before
  1183. // generating code for it because various parts of IR generation
  1184. // want to propagate this information down (e.g. to local static
  1185. // declarations).
  1186. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1187. setFunctionLinkage(D, Fn);
  1188. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1189. setGlobalVisibility(Fn, D);
  1190. CodeGenFunction(*this).GenerateCode(D, Fn);
  1191. SetFunctionDefinitionAttributes(D, Fn);
  1192. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1193. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1194. AddGlobalCtor(Fn, CA->getPriority());
  1195. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1196. AddGlobalDtor(Fn, DA->getPriority());
  1197. }
  1198. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1199. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1200. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1201. assert(AA && "Not an alias?");
  1202. llvm::StringRef MangledName = getMangledName(GD);
  1203. // If there is a definition in the module, then it wins over the alias.
  1204. // This is dubious, but allow it to be safe. Just ignore the alias.
  1205. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1206. if (Entry && !Entry->isDeclaration())
  1207. return;
  1208. const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1209. // Create a reference to the named value. This ensures that it is emitted
  1210. // if a deferred decl.
  1211. llvm::Constant *Aliasee;
  1212. if (isa<llvm::FunctionType>(DeclTy))
  1213. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
  1214. else
  1215. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1216. llvm::PointerType::getUnqual(DeclTy), 0);
  1217. // Create the new alias itself, but don't set a name yet.
  1218. llvm::GlobalValue *GA =
  1219. new llvm::GlobalAlias(Aliasee->getType(),
  1220. llvm::Function::ExternalLinkage,
  1221. "", Aliasee, &getModule());
  1222. if (Entry) {
  1223. assert(Entry->isDeclaration());
  1224. // If there is a declaration in the module, then we had an extern followed
  1225. // by the alias, as in:
  1226. // extern int test6();
  1227. // ...
  1228. // int test6() __attribute__((alias("test7")));
  1229. //
  1230. // Remove it and replace uses of it with the alias.
  1231. GA->takeName(Entry);
  1232. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1233. Entry->getType()));
  1234. Entry->eraseFromParent();
  1235. } else {
  1236. GA->setName(MangledName);
  1237. }
  1238. // Set attributes which are particular to an alias; this is a
  1239. // specialization of the attributes which may be set on a global
  1240. // variable/function.
  1241. if (D->hasAttr<DLLExportAttr>()) {
  1242. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1243. // The dllexport attribute is ignored for undefined symbols.
  1244. if (FD->hasBody())
  1245. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1246. } else {
  1247. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1248. }
  1249. } else if (D->hasAttr<WeakAttr>() ||
  1250. D->hasAttr<WeakRefAttr>() ||
  1251. D->hasAttr<WeakImportAttr>()) {
  1252. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1253. }
  1254. SetCommonAttributes(D, GA);
  1255. }
  1256. /// getBuiltinLibFunction - Given a builtin id for a function like
  1257. /// "__builtin_fabsf", return a Function* for "fabsf".
  1258. llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
  1259. unsigned BuiltinID) {
  1260. assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
  1261. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
  1262. "isn't a lib fn");
  1263. // Get the name, skip over the __builtin_ prefix (if necessary).
  1264. const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
  1265. if (Context.BuiltinInfo.isLibFunction(BuiltinID))
  1266. Name += 10;
  1267. const llvm::FunctionType *Ty =
  1268. cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
  1269. return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
  1270. }
  1271. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
  1272. unsigned NumTys) {
  1273. return llvm::Intrinsic::getDeclaration(&getModule(),
  1274. (llvm::Intrinsic::ID)IID, Tys, NumTys);
  1275. }
  1276. static llvm::StringMapEntry<llvm::Constant*> &
  1277. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1278. const StringLiteral *Literal,
  1279. bool TargetIsLSB,
  1280. bool &IsUTF16,
  1281. unsigned &StringLength) {
  1282. llvm::StringRef String = Literal->getString();
  1283. unsigned NumBytes = String.size();
  1284. // Check for simple case.
  1285. if (!Literal->containsNonAsciiOrNull()) {
  1286. StringLength = NumBytes;
  1287. return Map.GetOrCreateValue(String);
  1288. }
  1289. // Otherwise, convert the UTF8 literals into a byte string.
  1290. llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
  1291. const UTF8 *FromPtr = (UTF8 *)String.data();
  1292. UTF16 *ToPtr = &ToBuf[0];
  1293. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1294. &ToPtr, ToPtr + NumBytes,
  1295. strictConversion);
  1296. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1297. StringLength = ToPtr - &ToBuf[0];
  1298. // Render the UTF-16 string into a byte array and convert to the target byte
  1299. // order.
  1300. //
  1301. // FIXME: This isn't something we should need to do here.
  1302. llvm::SmallString<128> AsBytes;
  1303. AsBytes.reserve(StringLength * 2);
  1304. for (unsigned i = 0; i != StringLength; ++i) {
  1305. unsigned short Val = ToBuf[i];
  1306. if (TargetIsLSB) {
  1307. AsBytes.push_back(Val & 0xFF);
  1308. AsBytes.push_back(Val >> 8);
  1309. } else {
  1310. AsBytes.push_back(Val >> 8);
  1311. AsBytes.push_back(Val & 0xFF);
  1312. }
  1313. }
  1314. // Append one extra null character, the second is automatically added by our
  1315. // caller.
  1316. AsBytes.push_back(0);
  1317. IsUTF16 = true;
  1318. return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
  1319. }
  1320. llvm::Constant *
  1321. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1322. unsigned StringLength = 0;
  1323. bool isUTF16 = false;
  1324. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1325. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1326. getTargetData().isLittleEndian(),
  1327. isUTF16, StringLength);
  1328. if (llvm::Constant *C = Entry.getValue())
  1329. return C;
  1330. llvm::Constant *Zero =
  1331. llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
  1332. llvm::Constant *Zeros[] = { Zero, Zero };
  1333. // If we don't already have it, get __CFConstantStringClassReference.
  1334. if (!CFConstantStringClassRef) {
  1335. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1336. Ty = llvm::ArrayType::get(Ty, 0);
  1337. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1338. "__CFConstantStringClassReference");
  1339. // Decay array -> ptr
  1340. CFConstantStringClassRef =
  1341. llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1342. }
  1343. QualType CFTy = getContext().getCFConstantStringType();
  1344. const llvm::StructType *STy =
  1345. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1346. std::vector<llvm::Constant*> Fields(4);
  1347. // Class pointer.
  1348. Fields[0] = CFConstantStringClassRef;
  1349. // Flags.
  1350. const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1351. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1352. llvm::ConstantInt::get(Ty, 0x07C8);
  1353. // String pointer.
  1354. llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
  1355. llvm::GlobalValue::LinkageTypes Linkage;
  1356. bool isConstant;
  1357. if (isUTF16) {
  1358. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1359. Linkage = llvm::GlobalValue::InternalLinkage;
  1360. // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
  1361. // does make plain ascii ones writable.
  1362. isConstant = true;
  1363. } else {
  1364. Linkage = llvm::GlobalValue::PrivateLinkage;
  1365. isConstant = !Features.WritableStrings;
  1366. }
  1367. llvm::GlobalVariable *GV =
  1368. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1369. ".str");
  1370. GV->setUnnamedAddr(true);
  1371. if (isUTF16) {
  1372. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1373. GV->setAlignment(Align.getQuantity());
  1374. }
  1375. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1376. // String length.
  1377. Ty = getTypes().ConvertType(getContext().LongTy);
  1378. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1379. // The struct.
  1380. C = llvm::ConstantStruct::get(STy, Fields);
  1381. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1382. llvm::GlobalVariable::PrivateLinkage, C,
  1383. "_unnamed_cfstring_");
  1384. if (const char *Sect = getContext().Target.getCFStringSection())
  1385. GV->setSection(Sect);
  1386. Entry.setValue(GV);
  1387. return GV;
  1388. }
  1389. llvm::Constant *
  1390. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1391. unsigned StringLength = 0;
  1392. bool isUTF16 = false;
  1393. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1394. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1395. getTargetData().isLittleEndian(),
  1396. isUTF16, StringLength);
  1397. if (llvm::Constant *C = Entry.getValue())
  1398. return C;
  1399. llvm::Constant *Zero =
  1400. llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
  1401. llvm::Constant *Zeros[] = { Zero, Zero };
  1402. // If we don't already have it, get _NSConstantStringClassReference.
  1403. if (!ConstantStringClassRef) {
  1404. std::string StringClass(getLangOptions().ObjCConstantStringClass);
  1405. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1406. Ty = llvm::ArrayType::get(Ty, 0);
  1407. llvm::Constant *GV;
  1408. if (StringClass.empty())
  1409. GV = CreateRuntimeVariable(Ty,
  1410. Features.ObjCNonFragileABI ?
  1411. "OBJC_CLASS_$_NSConstantString" :
  1412. "_NSConstantStringClassReference");
  1413. else {
  1414. std::string str;
  1415. if (Features.ObjCNonFragileABI)
  1416. str = "OBJC_CLASS_$_" + StringClass;
  1417. else
  1418. str = "_" + StringClass + "ClassReference";
  1419. GV = CreateRuntimeVariable(Ty, str);
  1420. }
  1421. // Decay array -> ptr
  1422. ConstantStringClassRef =
  1423. llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1424. }
  1425. QualType NSTy = getContext().getNSConstantStringType();
  1426. const llvm::StructType *STy =
  1427. cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1428. std::vector<llvm::Constant*> Fields(3);
  1429. // Class pointer.
  1430. Fields[0] = ConstantStringClassRef;
  1431. // String pointer.
  1432. llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
  1433. llvm::GlobalValue::LinkageTypes Linkage;
  1434. bool isConstant;
  1435. if (isUTF16) {
  1436. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1437. Linkage = llvm::GlobalValue::InternalLinkage;
  1438. // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
  1439. // does make plain ascii ones writable.
  1440. isConstant = true;
  1441. } else {
  1442. Linkage = llvm::GlobalValue::PrivateLinkage;
  1443. isConstant = !Features.WritableStrings;
  1444. }
  1445. llvm::GlobalVariable *GV =
  1446. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1447. ".str");
  1448. GV->setUnnamedAddr(true);
  1449. if (isUTF16) {
  1450. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1451. GV->setAlignment(Align.getQuantity());
  1452. }
  1453. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1454. // String length.
  1455. const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1456. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1457. // The struct.
  1458. C = llvm::ConstantStruct::get(STy, Fields);
  1459. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1460. llvm::GlobalVariable::PrivateLinkage, C,
  1461. "_unnamed_nsstring_");
  1462. // FIXME. Fix section.
  1463. if (const char *Sect =
  1464. Features.ObjCNonFragileABI
  1465. ? getContext().Target.getNSStringNonFragileABISection()
  1466. : getContext().Target.getNSStringSection())
  1467. GV->setSection(Sect);
  1468. Entry.setValue(GV);
  1469. return GV;
  1470. }
  1471. /// GetStringForStringLiteral - Return the appropriate bytes for a
  1472. /// string literal, properly padded to match the literal type.
  1473. std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
  1474. const ASTContext &Context = getContext();
  1475. const ConstantArrayType *CAT =
  1476. Context.getAsConstantArrayType(E->getType());
  1477. assert(CAT && "String isn't pointer or array!");
  1478. // Resize the string to the right size.
  1479. uint64_t RealLen = CAT->getSize().getZExtValue();
  1480. if (E->isWide())
  1481. RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
  1482. std::string Str = E->getString().str();
  1483. Str.resize(RealLen, '\0');
  1484. return Str;
  1485. }
  1486. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  1487. /// constant array for the given string literal.
  1488. llvm::Constant *
  1489. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  1490. // FIXME: This can be more efficient.
  1491. // FIXME: We shouldn't need to bitcast the constant in the wide string case.
  1492. llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
  1493. if (S->isWide()) {
  1494. llvm::Type *DestTy =
  1495. llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
  1496. C = llvm::ConstantExpr::getBitCast(C, DestTy);
  1497. }
  1498. return C;
  1499. }
  1500. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  1501. /// array for the given ObjCEncodeExpr node.
  1502. llvm::Constant *
  1503. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  1504. std::string Str;
  1505. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1506. return GetAddrOfConstantCString(Str);
  1507. }
  1508. /// GenerateWritableString -- Creates storage for a string literal.
  1509. static llvm::Constant *GenerateStringLiteral(const std::string &str,
  1510. bool constant,
  1511. CodeGenModule &CGM,
  1512. const char *GlobalName) {
  1513. // Create Constant for this string literal. Don't add a '\0'.
  1514. llvm::Constant *C =
  1515. llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
  1516. // Create a global variable for this string
  1517. llvm::GlobalVariable *GV =
  1518. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  1519. llvm::GlobalValue::PrivateLinkage,
  1520. C, GlobalName);
  1521. GV->setUnnamedAddr(true);
  1522. return GV;
  1523. }
  1524. /// GetAddrOfConstantString - Returns a pointer to a character array
  1525. /// containing the literal. This contents are exactly that of the
  1526. /// given string, i.e. it will not be null terminated automatically;
  1527. /// see GetAddrOfConstantCString. Note that whether the result is
  1528. /// actually a pointer to an LLVM constant depends on
  1529. /// Feature.WriteableStrings.
  1530. ///
  1531. /// The result has pointer to array type.
  1532. llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
  1533. const char *GlobalName) {
  1534. bool IsConstant = !Features.WritableStrings;
  1535. // Get the default prefix if a name wasn't specified.
  1536. if (!GlobalName)
  1537. GlobalName = ".str";
  1538. // Don't share any string literals if strings aren't constant.
  1539. if (!IsConstant)
  1540. return GenerateStringLiteral(str, false, *this, GlobalName);
  1541. llvm::StringMapEntry<llvm::Constant *> &Entry =
  1542. ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
  1543. if (Entry.getValue())
  1544. return Entry.getValue();
  1545. // Create a global variable for this.
  1546. llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
  1547. Entry.setValue(C);
  1548. return C;
  1549. }
  1550. /// GetAddrOfConstantCString - Returns a pointer to a character
  1551. /// array containing the literal and a terminating '\-'
  1552. /// character. The result has pointer to array type.
  1553. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
  1554. const char *GlobalName){
  1555. return GetAddrOfConstantString(str + '\0', GlobalName);
  1556. }
  1557. /// EmitObjCPropertyImplementations - Emit information for synthesized
  1558. /// properties for an implementation.
  1559. void CodeGenModule::EmitObjCPropertyImplementations(const
  1560. ObjCImplementationDecl *D) {
  1561. for (ObjCImplementationDecl::propimpl_iterator
  1562. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  1563. ObjCPropertyImplDecl *PID = *i;
  1564. // Dynamic is just for type-checking.
  1565. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  1566. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  1567. // Determine which methods need to be implemented, some may have
  1568. // been overridden. Note that ::isSynthesized is not the method
  1569. // we want, that just indicates if the decl came from a
  1570. // property. What we want to know is if the method is defined in
  1571. // this implementation.
  1572. if (!D->getInstanceMethod(PD->getGetterName()))
  1573. CodeGenFunction(*this).GenerateObjCGetter(
  1574. const_cast<ObjCImplementationDecl *>(D), PID);
  1575. if (!PD->isReadOnly() &&
  1576. !D->getInstanceMethod(PD->getSetterName()))
  1577. CodeGenFunction(*this).GenerateObjCSetter(
  1578. const_cast<ObjCImplementationDecl *>(D), PID);
  1579. }
  1580. }
  1581. }
  1582. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  1583. /// for an implementation.
  1584. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  1585. if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
  1586. return;
  1587. DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
  1588. assert(DC && "EmitObjCIvarInitializations - null DeclContext");
  1589. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  1590. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  1591. ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
  1592. D->getLocation(),
  1593. D->getLocation(), cxxSelector,
  1594. getContext().VoidTy, 0,
  1595. DC, true, false, true, false,
  1596. ObjCMethodDecl::Required);
  1597. D->addInstanceMethod(DTORMethod);
  1598. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  1599. II = &getContext().Idents.get(".cxx_construct");
  1600. cxxSelector = getContext().Selectors.getSelector(0, &II);
  1601. // The constructor returns 'self'.
  1602. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  1603. D->getLocation(),
  1604. D->getLocation(), cxxSelector,
  1605. getContext().getObjCIdType(), 0,
  1606. DC, true, false, true, false,
  1607. ObjCMethodDecl::Required);
  1608. D->addInstanceMethod(CTORMethod);
  1609. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  1610. }
  1611. /// EmitNamespace - Emit all declarations in a namespace.
  1612. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  1613. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  1614. I != E; ++I)
  1615. EmitTopLevelDecl(*I);
  1616. }
  1617. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  1618. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  1619. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  1620. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  1621. ErrorUnsupported(LSD, "linkage spec");
  1622. return;
  1623. }
  1624. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  1625. I != E; ++I)
  1626. EmitTopLevelDecl(*I);
  1627. }
  1628. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  1629. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  1630. // If an error has occurred, stop code generation, but continue
  1631. // parsing and semantic analysis (to ensure all warnings and errors
  1632. // are emitted).
  1633. if (Diags.hasErrorOccurred())
  1634. return;
  1635. // Ignore dependent declarations.
  1636. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  1637. return;
  1638. switch (D->getKind()) {
  1639. case Decl::CXXConversion:
  1640. case Decl::CXXMethod:
  1641. case Decl::Function:
  1642. // Skip function templates
  1643. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
  1644. return;
  1645. EmitGlobal(cast<FunctionDecl>(D));
  1646. break;
  1647. case Decl::Var:
  1648. EmitGlobal(cast<VarDecl>(D));
  1649. break;
  1650. // C++ Decls
  1651. case Decl::Namespace:
  1652. EmitNamespace(cast<NamespaceDecl>(D));
  1653. break;
  1654. // No code generation needed.
  1655. case Decl::UsingShadow:
  1656. case Decl::Using:
  1657. case Decl::UsingDirective:
  1658. case Decl::ClassTemplate:
  1659. case Decl::FunctionTemplate:
  1660. case Decl::NamespaceAlias:
  1661. break;
  1662. case Decl::CXXConstructor:
  1663. // Skip function templates
  1664. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
  1665. return;
  1666. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  1667. break;
  1668. case Decl::CXXDestructor:
  1669. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  1670. break;
  1671. case Decl::StaticAssert:
  1672. // Nothing to do.
  1673. break;
  1674. // Objective-C Decls
  1675. // Forward declarations, no (immediate) code generation.
  1676. case Decl::ObjCClass:
  1677. case Decl::ObjCForwardProtocol:
  1678. case Decl::ObjCInterface:
  1679. break;
  1680. case Decl::ObjCCategory: {
  1681. ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
  1682. if (CD->IsClassExtension() && CD->hasSynthBitfield())
  1683. Context.ResetObjCLayout(CD->getClassInterface());
  1684. break;
  1685. }
  1686. case Decl::ObjCProtocol:
  1687. Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
  1688. break;
  1689. case Decl::ObjCCategoryImpl:
  1690. // Categories have properties but don't support synthesize so we
  1691. // can ignore them here.
  1692. Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  1693. break;
  1694. case Decl::ObjCImplementation: {
  1695. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  1696. if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
  1697. Context.ResetObjCLayout(OMD->getClassInterface());
  1698. EmitObjCPropertyImplementations(OMD);
  1699. EmitObjCIvarInitializations(OMD);
  1700. Runtime->GenerateClass(OMD);
  1701. break;
  1702. }
  1703. case Decl::ObjCMethod: {
  1704. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  1705. // If this is not a prototype, emit the body.
  1706. if (OMD->getBody())
  1707. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  1708. break;
  1709. }
  1710. case Decl::ObjCCompatibleAlias:
  1711. // compatibility-alias is a directive and has no code gen.
  1712. break;
  1713. case Decl::LinkageSpec:
  1714. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  1715. break;
  1716. case Decl::FileScopeAsm: {
  1717. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  1718. llvm::StringRef AsmString = AD->getAsmString()->getString();
  1719. const std::string &S = getModule().getModuleInlineAsm();
  1720. if (S.empty())
  1721. getModule().setModuleInlineAsm(AsmString);
  1722. else
  1723. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  1724. break;
  1725. }
  1726. default:
  1727. // Make sure we handled everything we should, every other kind is a
  1728. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  1729. // function. Need to recode Decl::Kind to do that easily.
  1730. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  1731. }
  1732. }
  1733. /// Turns the given pointer into a constant.
  1734. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  1735. const void *Ptr) {
  1736. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  1737. const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  1738. return llvm::ConstantInt::get(i64, PtrInt);
  1739. }
  1740. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  1741. llvm::NamedMDNode *&GlobalMetadata,
  1742. GlobalDecl D,
  1743. llvm::GlobalValue *Addr) {
  1744. if (!GlobalMetadata)
  1745. GlobalMetadata =
  1746. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  1747. // TODO: should we report variant information for ctors/dtors?
  1748. llvm::Value *Ops[] = {
  1749. Addr,
  1750. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  1751. };
  1752. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
  1753. }
  1754. /// Emits metadata nodes associating all the global values in the
  1755. /// current module with the Decls they came from. This is useful for
  1756. /// projects using IR gen as a subroutine.
  1757. ///
  1758. /// Since there's currently no way to associate an MDNode directly
  1759. /// with an llvm::GlobalValue, we create a global named metadata
  1760. /// with the name 'clang.global.decl.ptrs'.
  1761. void CodeGenModule::EmitDeclMetadata() {
  1762. llvm::NamedMDNode *GlobalMetadata = 0;
  1763. // StaticLocalDeclMap
  1764. for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
  1765. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  1766. I != E; ++I) {
  1767. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  1768. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  1769. }
  1770. }
  1771. /// Emits metadata nodes for all the local variables in the current
  1772. /// function.
  1773. void CodeGenFunction::EmitDeclMetadata() {
  1774. if (LocalDeclMap.empty()) return;
  1775. llvm::LLVMContext &Context = getLLVMContext();
  1776. // Find the unique metadata ID for this name.
  1777. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  1778. llvm::NamedMDNode *GlobalMetadata = 0;
  1779. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  1780. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  1781. const Decl *D = I->first;
  1782. llvm::Value *Addr = I->second;
  1783. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  1784. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  1785. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
  1786. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  1787. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  1788. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  1789. }
  1790. }
  1791. }
  1792. ///@name Custom Runtime Function Interfaces
  1793. ///@{
  1794. //
  1795. // FIXME: These can be eliminated once we can have clients just get the required
  1796. // AST nodes from the builtin tables.
  1797. llvm::Constant *CodeGenModule::getBlockObjectDispose() {
  1798. if (BlockObjectDispose)
  1799. return BlockObjectDispose;
  1800. // If we saw an explicit decl, use that.
  1801. if (BlockObjectDisposeDecl) {
  1802. return BlockObjectDispose = GetAddrOfFunction(
  1803. BlockObjectDisposeDecl,
  1804. getTypes().GetFunctionType(BlockObjectDisposeDecl));
  1805. }
  1806. // Otherwise construct the function by hand.
  1807. const llvm::FunctionType *FTy;
  1808. std::vector<const llvm::Type*> ArgTys;
  1809. const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
  1810. ArgTys.push_back(PtrToInt8Ty);
  1811. ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
  1812. FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
  1813. return BlockObjectDispose =
  1814. CreateRuntimeFunction(FTy, "_Block_object_dispose");
  1815. }
  1816. llvm::Constant *CodeGenModule::getBlockObjectAssign() {
  1817. if (BlockObjectAssign)
  1818. return BlockObjectAssign;
  1819. // If we saw an explicit decl, use that.
  1820. if (BlockObjectAssignDecl) {
  1821. return BlockObjectAssign = GetAddrOfFunction(
  1822. BlockObjectAssignDecl,
  1823. getTypes().GetFunctionType(BlockObjectAssignDecl));
  1824. }
  1825. // Otherwise construct the function by hand.
  1826. const llvm::FunctionType *FTy;
  1827. std::vector<const llvm::Type*> ArgTys;
  1828. const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
  1829. ArgTys.push_back(PtrToInt8Ty);
  1830. ArgTys.push_back(PtrToInt8Ty);
  1831. ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
  1832. FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
  1833. return BlockObjectAssign =
  1834. CreateRuntimeFunction(FTy, "_Block_object_assign");
  1835. }
  1836. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  1837. if (NSConcreteGlobalBlock)
  1838. return NSConcreteGlobalBlock;
  1839. // If we saw an explicit decl, use that.
  1840. if (NSConcreteGlobalBlockDecl) {
  1841. return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
  1842. NSConcreteGlobalBlockDecl,
  1843. getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
  1844. }
  1845. // Otherwise construct the variable by hand.
  1846. return NSConcreteGlobalBlock = CreateRuntimeVariable(
  1847. PtrToInt8Ty, "_NSConcreteGlobalBlock");
  1848. }
  1849. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  1850. if (NSConcreteStackBlock)
  1851. return NSConcreteStackBlock;
  1852. // If we saw an explicit decl, use that.
  1853. if (NSConcreteStackBlockDecl) {
  1854. return NSConcreteStackBlock = GetAddrOfGlobalVar(
  1855. NSConcreteStackBlockDecl,
  1856. getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
  1857. }
  1858. // Otherwise construct the variable by hand.
  1859. return NSConcreteStackBlock = CreateRuntimeVariable(
  1860. PtrToInt8Ty, "_NSConcreteStackBlock");
  1861. }
  1862. ///@}