CodeGenModule.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  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 "CGCUDARuntime.h"
  19. #include "CGCXXABI.h"
  20. #include "CGObjCRuntime.h"
  21. #include "CGOpenCLRuntime.h"
  22. #include "TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "clang/AST/ASTContext.h"
  25. #include "clang/AST/CharUnits.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclCXX.h"
  28. #include "clang/AST/DeclTemplate.h"
  29. #include "clang/AST/Mangle.h"
  30. #include "clang/AST/RecordLayout.h"
  31. #include "clang/AST/RecursiveASTVisitor.h"
  32. #include "clang/Basic/Builtins.h"
  33. #include "clang/Basic/Diagnostic.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "clang/Basic/ConvertUTF.h"
  37. #include "llvm/CallingConv.h"
  38. #include "llvm/Module.h"
  39. #include "llvm/Intrinsics.h"
  40. #include "llvm/LLVMContext.h"
  41. #include "llvm/ADT/APSInt.h"
  42. #include "llvm/ADT/Triple.h"
  43. #include "llvm/Target/Mangler.h"
  44. #include "llvm/Target/TargetData.h"
  45. #include "llvm/Support/CallSite.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. using namespace clang;
  48. using namespace CodeGen;
  49. static const char AnnotationSection[] = "llvm.metadata";
  50. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  51. switch (CGM.getContext().getTargetInfo().getCXXABI()) {
  52. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  53. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  54. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  55. }
  56. llvm_unreachable("invalid C++ ABI kind");
  57. }
  58. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  59. llvm::Module &M, const llvm::TargetData &TD,
  60. DiagnosticsEngine &diags)
  61. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  62. TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
  63. ABI(createCXXABI(*this)),
  64. Types(*this),
  65. TBAA(0),
  66. VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
  67. DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
  68. RRData(0), CFConstantStringClassRef(0),
  69. ConstantStringClassRef(0), NSConstantStringType(0),
  70. VMContext(M.getContext()),
  71. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  72. BlockObjectAssign(0), BlockObjectDispose(0),
  73. BlockDescriptorType(0), GenericBlockLiteralType(0) {
  74. // Initialize the type cache.
  75. llvm::LLVMContext &LLVMContext = M.getContext();
  76. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  77. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  78. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  79. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  80. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  81. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  82. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  83. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  84. PointerAlignInBytes =
  85. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  86. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  87. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  88. Int8PtrTy = Int8Ty->getPointerTo(0);
  89. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  90. if (LangOpts.ObjC1)
  91. createObjCRuntime();
  92. if (LangOpts.OpenCL)
  93. createOpenCLRuntime();
  94. if (LangOpts.CUDA)
  95. createCUDARuntime();
  96. // Enable TBAA unless it's suppressed.
  97. if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
  98. TBAA = new CodeGenTBAA(Context, VMContext, getLangOpts(),
  99. ABI.getMangleContext());
  100. // If debug info or coverage generation is enabled, create the CGDebugInfo
  101. // object.
  102. if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
  103. CodeGenOpts.EmitGcovNotes)
  104. DebugInfo = new CGDebugInfo(*this);
  105. Block.GlobalUniqueCount = 0;
  106. if (C.getLangOpts().ObjCAutoRefCount)
  107. ARCData = new ARCEntrypoints();
  108. RRData = new RREntrypoints();
  109. }
  110. CodeGenModule::~CodeGenModule() {
  111. delete ObjCRuntime;
  112. delete OpenCLRuntime;
  113. delete CUDARuntime;
  114. delete TheTargetCodeGenInfo;
  115. delete &ABI;
  116. delete TBAA;
  117. delete DebugInfo;
  118. delete ARCData;
  119. delete RRData;
  120. }
  121. void CodeGenModule::createObjCRuntime() {
  122. if (!LangOpts.NeXTRuntime)
  123. ObjCRuntime = CreateGNUObjCRuntime(*this);
  124. else
  125. ObjCRuntime = CreateMacObjCRuntime(*this);
  126. }
  127. void CodeGenModule::createOpenCLRuntime() {
  128. OpenCLRuntime = new CGOpenCLRuntime(*this);
  129. }
  130. void CodeGenModule::createCUDARuntime() {
  131. CUDARuntime = CreateNVCUDARuntime(*this);
  132. }
  133. void CodeGenModule::Release() {
  134. EmitDeferred();
  135. EmitCXXGlobalInitFunc();
  136. EmitCXXGlobalDtorFunc();
  137. if (ObjCRuntime)
  138. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  139. AddGlobalCtor(ObjCInitFunction);
  140. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  141. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  142. EmitGlobalAnnotations();
  143. EmitLLVMUsed();
  144. SimplifyPersonality();
  145. if (getCodeGenOpts().EmitDeclMetadata)
  146. EmitDeclMetadata();
  147. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  148. EmitCoverageFile();
  149. if (DebugInfo)
  150. DebugInfo->finalize();
  151. }
  152. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  153. // Make sure that this type is translated.
  154. Types.UpdateCompletedType(TD);
  155. }
  156. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  157. if (!TBAA)
  158. return 0;
  159. return TBAA->getTBAAInfo(QTy);
  160. }
  161. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  162. if (!TBAA)
  163. return 0;
  164. return TBAA->getTBAAInfoForVTablePtr();
  165. }
  166. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  167. llvm::MDNode *TBAAInfo) {
  168. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  169. }
  170. bool CodeGenModule::isTargetDarwin() const {
  171. return getContext().getTargetInfo().getTriple().isOSDarwin();
  172. }
  173. void CodeGenModule::Error(SourceLocation loc, const Twine &error) {
  174. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  175. error.str());
  176. getDiags().Report(Context.getFullLoc(loc), diagID);
  177. }
  178. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  179. /// specified stmt yet.
  180. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  181. bool OmitOnError) {
  182. if (OmitOnError && getDiags().hasErrorOccurred())
  183. return;
  184. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  185. "cannot compile this %0 yet");
  186. std::string Msg = Type;
  187. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  188. << Msg << S->getSourceRange();
  189. }
  190. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  191. /// specified decl yet.
  192. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  193. bool OmitOnError) {
  194. if (OmitOnError && getDiags().hasErrorOccurred())
  195. return;
  196. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  197. "cannot compile this %0 yet");
  198. std::string Msg = Type;
  199. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  200. }
  201. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  202. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  203. }
  204. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  205. const NamedDecl *D) const {
  206. // Internal definitions always have default visibility.
  207. if (GV->hasLocalLinkage()) {
  208. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  209. return;
  210. }
  211. // Set visibility for definitions.
  212. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  213. if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  214. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  215. }
  216. /// Set the symbol visibility of type information (vtable and RTTI)
  217. /// associated with the given type.
  218. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  219. const CXXRecordDecl *RD,
  220. TypeVisibilityKind TVK) const {
  221. setGlobalVisibility(GV, RD);
  222. if (!CodeGenOpts.HiddenWeakVTables)
  223. return;
  224. // We never want to drop the visibility for RTTI names.
  225. if (TVK == TVK_ForRTTIName)
  226. return;
  227. // We want to drop the visibility to hidden for weak type symbols.
  228. // This isn't possible if there might be unresolved references
  229. // elsewhere that rely on this symbol being visible.
  230. // This should be kept roughly in sync with setThunkVisibility
  231. // in CGVTables.cpp.
  232. // Preconditions.
  233. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  234. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  235. return;
  236. // Don't override an explicit visibility attribute.
  237. if (RD->getExplicitVisibility())
  238. return;
  239. switch (RD->getTemplateSpecializationKind()) {
  240. // We have to disable the optimization if this is an EI definition
  241. // because there might be EI declarations in other shared objects.
  242. case TSK_ExplicitInstantiationDefinition:
  243. case TSK_ExplicitInstantiationDeclaration:
  244. return;
  245. // Every use of a non-template class's type information has to emit it.
  246. case TSK_Undeclared:
  247. break;
  248. // In theory, implicit instantiations can ignore the possibility of
  249. // an explicit instantiation declaration because there necessarily
  250. // must be an EI definition somewhere with default visibility. In
  251. // practice, it's possible to have an explicit instantiation for
  252. // an arbitrary template class, and linkers aren't necessarily able
  253. // to deal with mixed-visibility symbols.
  254. case TSK_ExplicitSpecialization:
  255. case TSK_ImplicitInstantiation:
  256. if (!CodeGenOpts.HiddenWeakTemplateVTables)
  257. return;
  258. break;
  259. }
  260. // If there's a key function, there may be translation units
  261. // that don't have the key function's definition. But ignore
  262. // this if we're emitting RTTI under -fno-rtti.
  263. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  264. if (Context.getKeyFunction(RD))
  265. return;
  266. }
  267. // Otherwise, drop the visibility to hidden.
  268. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  269. GV->setUnnamedAddr(true);
  270. }
  271. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  272. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  273. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  274. if (!Str.empty())
  275. return Str;
  276. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  277. IdentifierInfo *II = ND->getIdentifier();
  278. assert(II && "Attempt to mangle unnamed decl.");
  279. Str = II->getName();
  280. return Str;
  281. }
  282. SmallString<256> Buffer;
  283. llvm::raw_svector_ostream Out(Buffer);
  284. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  285. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  286. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  287. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  288. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  289. getCXXABI().getMangleContext().mangleBlock(BD, Out);
  290. else
  291. getCXXABI().getMangleContext().mangleName(ND, Out);
  292. // Allocate space for the mangled name.
  293. Out.flush();
  294. size_t Length = Buffer.size();
  295. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  296. std::copy(Buffer.begin(), Buffer.end(), Name);
  297. Str = StringRef(Name, Length);
  298. return Str;
  299. }
  300. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  301. const BlockDecl *BD) {
  302. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  303. const Decl *D = GD.getDecl();
  304. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  305. if (D == 0)
  306. MangleCtx.mangleGlobalBlock(BD, Out);
  307. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  308. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  309. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  310. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  311. else
  312. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  313. }
  314. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  315. return getModule().getNamedValue(Name);
  316. }
  317. /// AddGlobalCtor - Add a function to the list that will be called before
  318. /// main() runs.
  319. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  320. // FIXME: Type coercion of void()* types.
  321. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  322. }
  323. /// AddGlobalDtor - Add a function to the list that will be called
  324. /// when the module is unloaded.
  325. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  326. // FIXME: Type coercion of void()* types.
  327. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  328. }
  329. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  330. // Ctor function type is void()*.
  331. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  332. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  333. // Get the type of a ctor entry, { i32, void ()* }.
  334. llvm::StructType *CtorStructTy =
  335. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  336. // Construct the constructor and destructor arrays.
  337. SmallVector<llvm::Constant*, 8> Ctors;
  338. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  339. llvm::Constant *S[] = {
  340. llvm::ConstantInt::get(Int32Ty, I->second, false),
  341. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  342. };
  343. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  344. }
  345. if (!Ctors.empty()) {
  346. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  347. new llvm::GlobalVariable(TheModule, AT, false,
  348. llvm::GlobalValue::AppendingLinkage,
  349. llvm::ConstantArray::get(AT, Ctors),
  350. GlobalName);
  351. }
  352. }
  353. llvm::GlobalValue::LinkageTypes
  354. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  355. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  356. if (Linkage == GVA_Internal)
  357. return llvm::Function::InternalLinkage;
  358. if (D->hasAttr<DLLExportAttr>())
  359. return llvm::Function::DLLExportLinkage;
  360. if (D->hasAttr<WeakAttr>())
  361. return llvm::Function::WeakAnyLinkage;
  362. // In C99 mode, 'inline' functions are guaranteed to have a strong
  363. // definition somewhere else, so we can use available_externally linkage.
  364. if (Linkage == GVA_C99Inline)
  365. return llvm::Function::AvailableExternallyLinkage;
  366. // Note that Apple's kernel linker doesn't support symbol
  367. // coalescing, so we need to avoid linkonce and weak linkages there.
  368. // Normally, this means we just map to internal, but for explicit
  369. // instantiations we'll map to external.
  370. // In C++, the compiler has to emit a definition in every translation unit
  371. // that references the function. We should use linkonce_odr because
  372. // a) if all references in this translation unit are optimized away, we
  373. // don't need to codegen it. b) if the function persists, it needs to be
  374. // merged with other definitions. c) C++ has the ODR, so we know the
  375. // definition is dependable.
  376. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  377. return !Context.getLangOpts().AppleKext
  378. ? llvm::Function::LinkOnceODRLinkage
  379. : llvm::Function::InternalLinkage;
  380. // An explicit instantiation of a template has weak linkage, since
  381. // explicit instantiations can occur in multiple translation units
  382. // and must all be equivalent. However, we are not allowed to
  383. // throw away these explicit instantiations.
  384. if (Linkage == GVA_ExplicitTemplateInstantiation)
  385. return !Context.getLangOpts().AppleKext
  386. ? llvm::Function::WeakODRLinkage
  387. : llvm::Function::ExternalLinkage;
  388. // Otherwise, we have strong external linkage.
  389. assert(Linkage == GVA_StrongExternal);
  390. return llvm::Function::ExternalLinkage;
  391. }
  392. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  393. ///
  394. /// FIXME: This is currently only done for aliases and functions, but not for
  395. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  396. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  397. llvm::GlobalValue *GV) {
  398. SetCommonAttributes(D, GV);
  399. }
  400. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  401. const CGFunctionInfo &Info,
  402. llvm::Function *F) {
  403. unsigned CallingConv;
  404. AttributeListType AttributeList;
  405. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  406. F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
  407. AttributeList.size()));
  408. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  409. }
  410. /// Determines whether the language options require us to model
  411. /// unwind exceptions. We treat -fexceptions as mandating this
  412. /// except under the fragile ObjC ABI with only ObjC exceptions
  413. /// enabled. This means, for example, that C with -fexceptions
  414. /// enables this.
  415. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  416. // If exceptions are completely disabled, obviously this is false.
  417. if (!LangOpts.Exceptions) return false;
  418. // If C++ exceptions are enabled, this is true.
  419. if (LangOpts.CXXExceptions) return true;
  420. // If ObjC exceptions are enabled, this depends on the ABI.
  421. if (LangOpts.ObjCExceptions) {
  422. if (!LangOpts.ObjCNonFragileABI) return false;
  423. }
  424. return true;
  425. }
  426. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  427. llvm::Function *F) {
  428. if (CodeGenOpts.UnwindTables)
  429. F->setHasUWTable();
  430. if (!hasUnwindExceptions(LangOpts))
  431. F->addFnAttr(llvm::Attribute::NoUnwind);
  432. if (D->hasAttr<NakedAttr>()) {
  433. // Naked implies noinline: we should not be inlining such functions.
  434. F->addFnAttr(llvm::Attribute::Naked);
  435. F->addFnAttr(llvm::Attribute::NoInline);
  436. }
  437. if (D->hasAttr<NoInlineAttr>())
  438. F->addFnAttr(llvm::Attribute::NoInline);
  439. // (noinline wins over always_inline, and we can't specify both in IR)
  440. if (D->hasAttr<AlwaysInlineAttr>() &&
  441. !F->hasFnAttr(llvm::Attribute::NoInline))
  442. F->addFnAttr(llvm::Attribute::AlwaysInline);
  443. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  444. F->setUnnamedAddr(true);
  445. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  446. F->addFnAttr(llvm::Attribute::StackProtect);
  447. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  448. F->addFnAttr(llvm::Attribute::StackProtectReq);
  449. if (LangOpts.AddressSanitizer) {
  450. // When AddressSanitizer is enabled, set AddressSafety attribute
  451. // unless __attribute__((no_address_safety_analysis)) is used.
  452. if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
  453. F->addFnAttr(llvm::Attribute::AddressSafety);
  454. }
  455. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  456. if (alignment)
  457. F->setAlignment(alignment);
  458. // C++ ABI requires 2-byte alignment for member functions.
  459. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  460. F->setAlignment(2);
  461. }
  462. void CodeGenModule::SetCommonAttributes(const Decl *D,
  463. llvm::GlobalValue *GV) {
  464. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  465. setGlobalVisibility(GV, ND);
  466. else
  467. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  468. if (D->hasAttr<UsedAttr>())
  469. AddUsedGlobal(GV);
  470. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  471. GV->setSection(SA->getName());
  472. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  473. }
  474. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  475. llvm::Function *F,
  476. const CGFunctionInfo &FI) {
  477. SetLLVMFunctionAttributes(D, FI, F);
  478. SetLLVMFunctionAttributesForDefinition(D, F);
  479. F->setLinkage(llvm::Function::InternalLinkage);
  480. SetCommonAttributes(D, F);
  481. }
  482. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  483. llvm::Function *F,
  484. bool IsIncompleteFunction) {
  485. if (unsigned IID = F->getIntrinsicID()) {
  486. // If this is an intrinsic function, set the function's attributes
  487. // to the intrinsic's attributes.
  488. F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
  489. return;
  490. }
  491. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  492. if (!IsIncompleteFunction)
  493. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  494. // Only a few attributes are set on declarations; these may later be
  495. // overridden by a definition.
  496. if (FD->hasAttr<DLLImportAttr>()) {
  497. F->setLinkage(llvm::Function::DLLImportLinkage);
  498. } else if (FD->hasAttr<WeakAttr>() ||
  499. FD->isWeakImported()) {
  500. // "extern_weak" is overloaded in LLVM; we probably should have
  501. // separate linkage types for this.
  502. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  503. } else {
  504. F->setLinkage(llvm::Function::ExternalLinkage);
  505. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  506. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  507. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  508. }
  509. }
  510. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  511. F->setSection(SA->getName());
  512. }
  513. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  514. assert(!GV->isDeclaration() &&
  515. "Only globals with definition can force usage.");
  516. LLVMUsed.push_back(GV);
  517. }
  518. void CodeGenModule::EmitLLVMUsed() {
  519. // Don't create llvm.used if there is no need.
  520. if (LLVMUsed.empty())
  521. return;
  522. // Convert LLVMUsed to what ConstantArray needs.
  523. SmallVector<llvm::Constant*, 8> UsedArray;
  524. UsedArray.resize(LLVMUsed.size());
  525. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  526. UsedArray[i] =
  527. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  528. Int8PtrTy);
  529. }
  530. if (UsedArray.empty())
  531. return;
  532. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  533. llvm::GlobalVariable *GV =
  534. new llvm::GlobalVariable(getModule(), ATy, false,
  535. llvm::GlobalValue::AppendingLinkage,
  536. llvm::ConstantArray::get(ATy, UsedArray),
  537. "llvm.used");
  538. GV->setSection("llvm.metadata");
  539. }
  540. void CodeGenModule::EmitDeferred() {
  541. // Emit code for any potentially referenced deferred decls. Since a
  542. // previously unused static decl may become used during the generation of code
  543. // for a static function, iterate until no changes are made.
  544. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  545. if (!DeferredVTables.empty()) {
  546. const CXXRecordDecl *RD = DeferredVTables.back();
  547. DeferredVTables.pop_back();
  548. getVTables().GenerateClassData(getVTableLinkage(RD), RD);
  549. continue;
  550. }
  551. GlobalDecl D = DeferredDeclsToEmit.back();
  552. DeferredDeclsToEmit.pop_back();
  553. // Check to see if we've already emitted this. This is necessary
  554. // for a couple of reasons: first, decls can end up in the
  555. // deferred-decls queue multiple times, and second, decls can end
  556. // up with definitions in unusual ways (e.g. by an extern inline
  557. // function acquiring a strong function redefinition). Just
  558. // ignore these cases.
  559. //
  560. // TODO: That said, looking this up multiple times is very wasteful.
  561. StringRef Name = getMangledName(D);
  562. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  563. assert(CGRef && "Deferred decl wasn't referenced?");
  564. if (!CGRef->isDeclaration())
  565. continue;
  566. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  567. // purposes an alias counts as a definition.
  568. if (isa<llvm::GlobalAlias>(CGRef))
  569. continue;
  570. // Otherwise, emit the definition and move on to the next one.
  571. EmitGlobalDefinition(D);
  572. }
  573. }
  574. void CodeGenModule::EmitGlobalAnnotations() {
  575. if (Annotations.empty())
  576. return;
  577. // Create a new global variable for the ConstantStruct in the Module.
  578. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  579. Annotations[0]->getType(), Annotations.size()), Annotations);
  580. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  581. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  582. "llvm.global.annotations");
  583. gv->setSection(AnnotationSection);
  584. }
  585. llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
  586. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  587. if (i != AnnotationStrings.end())
  588. return i->second;
  589. // Not found yet, create a new global.
  590. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  591. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  592. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  593. gv->setSection(AnnotationSection);
  594. gv->setUnnamedAddr(true);
  595. AnnotationStrings[Str] = gv;
  596. return gv;
  597. }
  598. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  599. SourceManager &SM = getContext().getSourceManager();
  600. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  601. if (PLoc.isValid())
  602. return EmitAnnotationString(PLoc.getFilename());
  603. return EmitAnnotationString(SM.getBufferName(Loc));
  604. }
  605. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  606. SourceManager &SM = getContext().getSourceManager();
  607. PresumedLoc PLoc = SM.getPresumedLoc(L);
  608. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  609. SM.getExpansionLineNumber(L);
  610. return llvm::ConstantInt::get(Int32Ty, LineNo);
  611. }
  612. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  613. const AnnotateAttr *AA,
  614. SourceLocation L) {
  615. // Get the globals for file name, annotation, and the line number.
  616. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  617. *UnitGV = EmitAnnotationUnit(L),
  618. *LineNoCst = EmitAnnotationLineNo(L);
  619. // Create the ConstantStruct for the global annotation.
  620. llvm::Constant *Fields[4] = {
  621. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  622. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  623. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  624. LineNoCst
  625. };
  626. return llvm::ConstantStruct::getAnon(Fields);
  627. }
  628. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  629. llvm::GlobalValue *GV) {
  630. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  631. // Get the struct elements for these annotations.
  632. for (specific_attr_iterator<AnnotateAttr>
  633. ai = D->specific_attr_begin<AnnotateAttr>(),
  634. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  635. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  636. }
  637. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  638. // Never defer when EmitAllDecls is specified.
  639. if (LangOpts.EmitAllDecls)
  640. return false;
  641. return !getContext().DeclMustBeEmitted(Global);
  642. }
  643. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  644. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  645. assert(AA && "No alias?");
  646. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  647. // See if there is already something with the target's name in the module.
  648. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  649. llvm::Constant *Aliasee;
  650. if (isa<llvm::FunctionType>(DeclTy))
  651. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  652. /*ForVTable=*/false);
  653. else
  654. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  655. llvm::PointerType::getUnqual(DeclTy), 0);
  656. if (!Entry) {
  657. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  658. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  659. WeakRefReferences.insert(F);
  660. }
  661. return Aliasee;
  662. }
  663. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  664. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  665. // Weak references don't produce any output by themselves.
  666. if (Global->hasAttr<WeakRefAttr>())
  667. return;
  668. // If this is an alias definition (which otherwise looks like a declaration)
  669. // emit it now.
  670. if (Global->hasAttr<AliasAttr>())
  671. return EmitAliasDefinition(GD);
  672. // If this is CUDA, be selective about which declarations we emit.
  673. if (LangOpts.CUDA) {
  674. if (CodeGenOpts.CUDAIsDevice) {
  675. if (!Global->hasAttr<CUDADeviceAttr>() &&
  676. !Global->hasAttr<CUDAGlobalAttr>() &&
  677. !Global->hasAttr<CUDAConstantAttr>() &&
  678. !Global->hasAttr<CUDASharedAttr>())
  679. return;
  680. } else {
  681. if (!Global->hasAttr<CUDAHostAttr>() && (
  682. Global->hasAttr<CUDADeviceAttr>() ||
  683. Global->hasAttr<CUDAConstantAttr>() ||
  684. Global->hasAttr<CUDASharedAttr>()))
  685. return;
  686. }
  687. }
  688. // Ignore declarations, they will be emitted on their first use.
  689. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  690. // Forward declarations are emitted lazily on first use.
  691. if (!FD->doesThisDeclarationHaveABody()) {
  692. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  693. return;
  694. const FunctionDecl *InlineDefinition = 0;
  695. FD->getBody(InlineDefinition);
  696. StringRef MangledName = getMangledName(GD);
  697. DeferredDecls.erase(MangledName);
  698. EmitGlobalDefinition(InlineDefinition);
  699. return;
  700. }
  701. } else {
  702. const VarDecl *VD = cast<VarDecl>(Global);
  703. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  704. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  705. return;
  706. }
  707. // Defer code generation when possible if this is a static definition, inline
  708. // function etc. These we only want to emit if they are used.
  709. if (!MayDeferGeneration(Global)) {
  710. // Emit the definition if it can't be deferred.
  711. EmitGlobalDefinition(GD);
  712. return;
  713. }
  714. // If we're deferring emission of a C++ variable with an
  715. // initializer, remember the order in which it appeared in the file.
  716. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  717. cast<VarDecl>(Global)->hasInit()) {
  718. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  719. CXXGlobalInits.push_back(0);
  720. }
  721. // If the value has already been used, add it directly to the
  722. // DeferredDeclsToEmit list.
  723. StringRef MangledName = getMangledName(GD);
  724. if (GetGlobalValue(MangledName))
  725. DeferredDeclsToEmit.push_back(GD);
  726. else {
  727. // Otherwise, remember that we saw a deferred decl with this name. The
  728. // first use of the mangled name will cause it to move into
  729. // DeferredDeclsToEmit.
  730. DeferredDecls[MangledName] = GD;
  731. }
  732. }
  733. namespace {
  734. struct FunctionIsDirectlyRecursive :
  735. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  736. const StringRef Name;
  737. const Builtin::Context &BI;
  738. bool Result;
  739. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  740. Name(N), BI(C), Result(false) {
  741. }
  742. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  743. bool TraverseCallExpr(CallExpr *E) {
  744. const FunctionDecl *FD = E->getDirectCallee();
  745. if (!FD)
  746. return true;
  747. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  748. if (Attr && Name == Attr->getLabel()) {
  749. Result = true;
  750. return false;
  751. }
  752. unsigned BuiltinID = FD->getBuiltinID();
  753. if (!BuiltinID)
  754. return true;
  755. StringRef BuiltinName = BI.GetName(BuiltinID);
  756. if (BuiltinName.startswith("__builtin_") &&
  757. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  758. Result = true;
  759. return false;
  760. }
  761. return true;
  762. }
  763. };
  764. }
  765. // isTriviallyRecursive - Check if this function calls another
  766. // decl that, because of the asm attribute or the other decl being a builtin,
  767. // ends up pointing to itself.
  768. bool
  769. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  770. StringRef Name;
  771. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  772. // asm labels are a special kind of mangling we have to support.
  773. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  774. if (!Attr)
  775. return false;
  776. Name = Attr->getLabel();
  777. } else {
  778. Name = FD->getName();
  779. }
  780. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  781. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  782. return Walker.Result;
  783. }
  784. bool
  785. CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
  786. if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
  787. return true;
  788. if (CodeGenOpts.OptimizationLevel == 0 &&
  789. !F->hasAttr<AlwaysInlineAttr>())
  790. return false;
  791. // PR9614. Avoid cases where the source code is lying to us. An available
  792. // externally function should have an equivalent function somewhere else,
  793. // but a function that calls itself is clearly not equivalent to the real
  794. // implementation.
  795. // This happens in glibc's btowc and in some configure checks.
  796. return !isTriviallyRecursive(F);
  797. }
  798. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  799. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  800. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  801. Context.getSourceManager(),
  802. "Generating code for declaration");
  803. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  804. // At -O0, don't generate IR for functions with available_externally
  805. // linkage.
  806. if (!shouldEmitFunction(Function))
  807. return;
  808. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  809. // Make sure to emit the definition(s) before we emit the thunks.
  810. // This is necessary for the generation of certain thunks.
  811. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  812. EmitCXXConstructor(CD, GD.getCtorType());
  813. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  814. EmitCXXDestructor(DD, GD.getDtorType());
  815. else
  816. EmitGlobalFunctionDefinition(GD);
  817. if (Method->isVirtual())
  818. getVTables().EmitThunks(GD);
  819. return;
  820. }
  821. return EmitGlobalFunctionDefinition(GD);
  822. }
  823. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  824. return EmitGlobalVarDefinition(VD);
  825. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  826. }
  827. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  828. /// module, create and return an llvm Function with the specified type. If there
  829. /// is something in the module with the specified name, return it potentially
  830. /// bitcasted to the right type.
  831. ///
  832. /// If D is non-null, it specifies a decl that correspond to this. This is used
  833. /// to set the attributes on the function when it is first created.
  834. llvm::Constant *
  835. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  836. llvm::Type *Ty,
  837. GlobalDecl D, bool ForVTable,
  838. llvm::Attributes ExtraAttrs) {
  839. // Lookup the entry, lazily creating it if necessary.
  840. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  841. if (Entry) {
  842. if (WeakRefReferences.count(Entry)) {
  843. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  844. if (FD && !FD->hasAttr<WeakAttr>())
  845. Entry->setLinkage(llvm::Function::ExternalLinkage);
  846. WeakRefReferences.erase(Entry);
  847. }
  848. if (Entry->getType()->getElementType() == Ty)
  849. return Entry;
  850. // Make sure the result is of the correct type.
  851. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  852. }
  853. // This function doesn't have a complete type (for example, the return
  854. // type is an incomplete struct). Use a fake type instead, and make
  855. // sure not to try to set attributes.
  856. bool IsIncompleteFunction = false;
  857. llvm::FunctionType *FTy;
  858. if (isa<llvm::FunctionType>(Ty)) {
  859. FTy = cast<llvm::FunctionType>(Ty);
  860. } else {
  861. FTy = llvm::FunctionType::get(VoidTy, false);
  862. IsIncompleteFunction = true;
  863. }
  864. llvm::Function *F = llvm::Function::Create(FTy,
  865. llvm::Function::ExternalLinkage,
  866. MangledName, &getModule());
  867. assert(F->getName() == MangledName && "name was uniqued!");
  868. if (D.getDecl())
  869. SetFunctionAttributes(D, F, IsIncompleteFunction);
  870. if (ExtraAttrs != llvm::Attribute::None)
  871. F->addFnAttr(ExtraAttrs);
  872. // This is the first use or definition of a mangled name. If there is a
  873. // deferred decl with this name, remember that we need to emit it at the end
  874. // of the file.
  875. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  876. if (DDI != DeferredDecls.end()) {
  877. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  878. // list, and remove it from DeferredDecls (since we don't need it anymore).
  879. DeferredDeclsToEmit.push_back(DDI->second);
  880. DeferredDecls.erase(DDI);
  881. // Otherwise, there are cases we have to worry about where we're
  882. // using a declaration for which we must emit a definition but where
  883. // we might not find a top-level definition:
  884. // - member functions defined inline in their classes
  885. // - friend functions defined inline in some class
  886. // - special member functions with implicit definitions
  887. // If we ever change our AST traversal to walk into class methods,
  888. // this will be unnecessary.
  889. //
  890. // We also don't emit a definition for a function if it's going to be an entry
  891. // in a vtable, unless it's already marked as used.
  892. } else if (getLangOpts().CPlusPlus && D.getDecl()) {
  893. // Look for a declaration that's lexically in a record.
  894. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  895. do {
  896. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  897. if (FD->isImplicit() && !ForVTable) {
  898. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  899. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  900. break;
  901. } else if (FD->doesThisDeclarationHaveABody()) {
  902. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  903. break;
  904. }
  905. }
  906. FD = FD->getPreviousDecl();
  907. } while (FD);
  908. }
  909. // Make sure the result is of the requested type.
  910. if (!IsIncompleteFunction) {
  911. assert(F->getType()->getElementType() == Ty);
  912. return F;
  913. }
  914. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  915. return llvm::ConstantExpr::getBitCast(F, PTy);
  916. }
  917. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  918. /// non-null, then this function will use the specified type if it has to
  919. /// create it (this occurs when we see a definition of the function).
  920. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  921. llvm::Type *Ty,
  922. bool ForVTable) {
  923. // If there was no specific requested type, just convert it now.
  924. if (!Ty)
  925. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  926. StringRef MangledName = getMangledName(GD);
  927. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  928. }
  929. /// CreateRuntimeFunction - Create a new runtime function with the specified
  930. /// type and name.
  931. llvm::Constant *
  932. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  933. StringRef Name,
  934. llvm::Attributes ExtraAttrs) {
  935. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  936. ExtraAttrs);
  937. }
  938. /// isTypeConstant - Determine whether an object of this type can be emitted
  939. /// as a constant.
  940. ///
  941. /// If ExcludeCtor is true, the duration when the object's constructor runs
  942. /// will not be considered. The caller will need to verify that the object is
  943. /// not written to during its construction.
  944. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  945. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  946. return false;
  947. if (Context.getLangOpts().CPlusPlus) {
  948. if (const CXXRecordDecl *Record
  949. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  950. return ExcludeCtor && !Record->hasMutableFields() &&
  951. Record->hasTrivialDestructor();
  952. }
  953. return true;
  954. }
  955. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  956. /// create and return an llvm GlobalVariable with the specified type. If there
  957. /// is something in the module with the specified name, return it potentially
  958. /// bitcasted to the right type.
  959. ///
  960. /// If D is non-null, it specifies a decl that correspond to this. This is used
  961. /// to set the attributes on the global when it is first created.
  962. llvm::Constant *
  963. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  964. llvm::PointerType *Ty,
  965. const VarDecl *D,
  966. bool UnnamedAddr) {
  967. // Lookup the entry, lazily creating it if necessary.
  968. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  969. if (Entry) {
  970. if (WeakRefReferences.count(Entry)) {
  971. if (D && !D->hasAttr<WeakAttr>())
  972. Entry->setLinkage(llvm::Function::ExternalLinkage);
  973. WeakRefReferences.erase(Entry);
  974. }
  975. if (UnnamedAddr)
  976. Entry->setUnnamedAddr(true);
  977. if (Entry->getType() == Ty)
  978. return Entry;
  979. // Make sure the result is of the correct type.
  980. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  981. }
  982. // This is the first use or definition of a mangled name. If there is a
  983. // deferred decl with this name, remember that we need to emit it at the end
  984. // of the file.
  985. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  986. if (DDI != DeferredDecls.end()) {
  987. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  988. // list, and remove it from DeferredDecls (since we don't need it anymore).
  989. DeferredDeclsToEmit.push_back(DDI->second);
  990. DeferredDecls.erase(DDI);
  991. }
  992. llvm::GlobalVariable *GV =
  993. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  994. llvm::GlobalValue::ExternalLinkage,
  995. 0, MangledName, 0,
  996. false, Ty->getAddressSpace());
  997. // Handle things which are present even on external declarations.
  998. if (D) {
  999. // FIXME: This code is overly simple and should be merged with other global
  1000. // handling.
  1001. GV->setConstant(isTypeConstant(D->getType(), false));
  1002. // Set linkage and visibility in case we never see a definition.
  1003. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  1004. if (LV.linkage() != ExternalLinkage) {
  1005. // Don't set internal linkage on declarations.
  1006. } else {
  1007. if (D->hasAttr<DLLImportAttr>())
  1008. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1009. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1010. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1011. // Set visibility on a declaration only if it's explicit.
  1012. if (LV.visibilityExplicit())
  1013. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  1014. }
  1015. GV->setThreadLocal(D->isThreadSpecified());
  1016. }
  1017. return GV;
  1018. }
  1019. llvm::GlobalVariable *
  1020. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1021. llvm::Type *Ty,
  1022. llvm::GlobalValue::LinkageTypes Linkage) {
  1023. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1024. llvm::GlobalVariable *OldGV = 0;
  1025. if (GV) {
  1026. // Check if the variable has the right type.
  1027. if (GV->getType()->getElementType() == Ty)
  1028. return GV;
  1029. // Because C++ name mangling, the only way we can end up with an already
  1030. // existing global with the same name is if it has been declared extern "C".
  1031. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1032. OldGV = GV;
  1033. }
  1034. // Create a new variable.
  1035. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1036. Linkage, 0, Name);
  1037. if (OldGV) {
  1038. // Replace occurrences of the old variable if needed.
  1039. GV->takeName(OldGV);
  1040. if (!OldGV->use_empty()) {
  1041. llvm::Constant *NewPtrForOldDecl =
  1042. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1043. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1044. }
  1045. OldGV->eraseFromParent();
  1046. }
  1047. return GV;
  1048. }
  1049. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1050. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1051. /// then it will be greated with the specified type instead of whatever the
  1052. /// normal requested type would be.
  1053. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1054. llvm::Type *Ty) {
  1055. assert(D->hasGlobalStorage() && "Not a global variable");
  1056. QualType ASTTy = D->getType();
  1057. if (Ty == 0)
  1058. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1059. llvm::PointerType *PTy =
  1060. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1061. StringRef MangledName = getMangledName(D);
  1062. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1063. }
  1064. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1065. /// specified type and name.
  1066. llvm::Constant *
  1067. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1068. StringRef Name) {
  1069. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1070. true);
  1071. }
  1072. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1073. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1074. if (MayDeferGeneration(D)) {
  1075. // If we have not seen a reference to this variable yet, place it
  1076. // into the deferred declarations table to be emitted if needed
  1077. // later.
  1078. StringRef MangledName = getMangledName(D);
  1079. if (!GetGlobalValue(MangledName)) {
  1080. DeferredDecls[MangledName] = D;
  1081. return;
  1082. }
  1083. }
  1084. // The tentative definition is the only definition.
  1085. EmitGlobalVarDefinition(D);
  1086. }
  1087. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  1088. if (DefinitionRequired)
  1089. getVTables().GenerateClassData(getVTableLinkage(Class), Class);
  1090. }
  1091. llvm::GlobalVariable::LinkageTypes
  1092. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  1093. if (RD->getLinkage() != ExternalLinkage)
  1094. return llvm::GlobalVariable::InternalLinkage;
  1095. if (const CXXMethodDecl *KeyFunction
  1096. = RD->getASTContext().getKeyFunction(RD)) {
  1097. // If this class has a key function, use that to determine the linkage of
  1098. // the vtable.
  1099. const FunctionDecl *Def = 0;
  1100. if (KeyFunction->hasBody(Def))
  1101. KeyFunction = cast<CXXMethodDecl>(Def);
  1102. switch (KeyFunction->getTemplateSpecializationKind()) {
  1103. case TSK_Undeclared:
  1104. case TSK_ExplicitSpecialization:
  1105. // When compiling with optimizations turned on, we emit all vtables,
  1106. // even if the key function is not defined in the current translation
  1107. // unit. If this is the case, use available_externally linkage.
  1108. if (!Def && CodeGenOpts.OptimizationLevel)
  1109. return llvm::GlobalVariable::AvailableExternallyLinkage;
  1110. if (KeyFunction->isInlined())
  1111. return !Context.getLangOpts().AppleKext ?
  1112. llvm::GlobalVariable::LinkOnceODRLinkage :
  1113. llvm::Function::InternalLinkage;
  1114. return llvm::GlobalVariable::ExternalLinkage;
  1115. case TSK_ImplicitInstantiation:
  1116. return !Context.getLangOpts().AppleKext ?
  1117. llvm::GlobalVariable::LinkOnceODRLinkage :
  1118. llvm::Function::InternalLinkage;
  1119. case TSK_ExplicitInstantiationDefinition:
  1120. return !Context.getLangOpts().AppleKext ?
  1121. llvm::GlobalVariable::WeakODRLinkage :
  1122. llvm::Function::InternalLinkage;
  1123. case TSK_ExplicitInstantiationDeclaration:
  1124. // FIXME: Use available_externally linkage. However, this currently
  1125. // breaks LLVM's build due to undefined symbols.
  1126. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1127. return !Context.getLangOpts().AppleKext ?
  1128. llvm::GlobalVariable::LinkOnceODRLinkage :
  1129. llvm::Function::InternalLinkage;
  1130. }
  1131. }
  1132. if (Context.getLangOpts().AppleKext)
  1133. return llvm::Function::InternalLinkage;
  1134. switch (RD->getTemplateSpecializationKind()) {
  1135. case TSK_Undeclared:
  1136. case TSK_ExplicitSpecialization:
  1137. case TSK_ImplicitInstantiation:
  1138. // FIXME: Use available_externally linkage. However, this currently
  1139. // breaks LLVM's build due to undefined symbols.
  1140. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1141. case TSK_ExplicitInstantiationDeclaration:
  1142. return llvm::GlobalVariable::LinkOnceODRLinkage;
  1143. case TSK_ExplicitInstantiationDefinition:
  1144. return llvm::GlobalVariable::WeakODRLinkage;
  1145. }
  1146. llvm_unreachable("Invalid TemplateSpecializationKind!");
  1147. }
  1148. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1149. return Context.toCharUnitsFromBits(
  1150. TheTargetData.getTypeStoreSizeInBits(Ty));
  1151. }
  1152. llvm::Constant *
  1153. CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
  1154. const Expr *rawInit) {
  1155. ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
  1156. if (const ExprWithCleanups *withCleanups =
  1157. dyn_cast<ExprWithCleanups>(rawInit)) {
  1158. cleanups = withCleanups->getObjects();
  1159. rawInit = withCleanups->getSubExpr();
  1160. }
  1161. const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
  1162. if (!init || !init->initializesStdInitializerList() ||
  1163. init->getNumInits() == 0)
  1164. return 0;
  1165. ASTContext &ctx = getContext();
  1166. unsigned numInits = init->getNumInits();
  1167. // FIXME: This check is here because we would otherwise silently miscompile
  1168. // nested global std::initializer_lists. Better would be to have a real
  1169. // implementation.
  1170. for (unsigned i = 0; i < numInits; ++i) {
  1171. const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
  1172. if (inner && inner->initializesStdInitializerList()) {
  1173. ErrorUnsupported(inner, "nested global std::initializer_list");
  1174. return 0;
  1175. }
  1176. }
  1177. // Synthesize a fake VarDecl for the array and initialize that.
  1178. QualType elementType = init->getInit(0)->getType();
  1179. llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
  1180. QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
  1181. ArrayType::Normal, 0);
  1182. IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
  1183. TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
  1184. arrayType, D->getLocation());
  1185. VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
  1186. D->getDeclContext()),
  1187. D->getLocStart(), D->getLocation(),
  1188. name, arrayType, sourceInfo,
  1189. SC_Static, SC_Static);
  1190. // Now clone the InitListExpr to initialize the array instead.
  1191. // Incredible hack: we want to use the existing InitListExpr here, so we need
  1192. // to tell it that it no longer initializes a std::initializer_list.
  1193. Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
  1194. const_cast<InitListExpr*>(init)->getInits(),
  1195. init->getNumInits(),
  1196. init->getRBraceLoc());
  1197. arrayInit->setType(arrayType);
  1198. if (!cleanups.empty())
  1199. arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
  1200. backingArray->setInit(arrayInit);
  1201. // Emit the definition of the array.
  1202. EmitGlobalVarDefinition(backingArray);
  1203. // Inspect the initializer list to validate it and determine its type.
  1204. // FIXME: doing this every time is probably inefficient; caching would be nice
  1205. RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
  1206. RecordDecl::field_iterator field = record->field_begin();
  1207. if (field == record->field_end()) {
  1208. ErrorUnsupported(D, "weird std::initializer_list");
  1209. return 0;
  1210. }
  1211. QualType elementPtr = ctx.getPointerType(elementType.withConst());
  1212. // Start pointer.
  1213. if (!ctx.hasSameType(field->getType(), elementPtr)) {
  1214. ErrorUnsupported(D, "weird std::initializer_list");
  1215. return 0;
  1216. }
  1217. ++field;
  1218. if (field == record->field_end()) {
  1219. ErrorUnsupported(D, "weird std::initializer_list");
  1220. return 0;
  1221. }
  1222. bool isStartEnd = false;
  1223. if (ctx.hasSameType(field->getType(), elementPtr)) {
  1224. // End pointer.
  1225. isStartEnd = true;
  1226. } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
  1227. ErrorUnsupported(D, "weird std::initializer_list");
  1228. return 0;
  1229. }
  1230. // Now build an APValue representing the std::initializer_list.
  1231. APValue initListValue(APValue::UninitStruct(), 0, 2);
  1232. APValue &startField = initListValue.getStructField(0);
  1233. APValue::LValuePathEntry startOffsetPathEntry;
  1234. startOffsetPathEntry.ArrayIndex = 0;
  1235. startField = APValue(APValue::LValueBase(backingArray),
  1236. CharUnits::fromQuantity(0),
  1237. llvm::makeArrayRef(startOffsetPathEntry),
  1238. /*IsOnePastTheEnd=*/false, 0);
  1239. if (isStartEnd) {
  1240. APValue &endField = initListValue.getStructField(1);
  1241. APValue::LValuePathEntry endOffsetPathEntry;
  1242. endOffsetPathEntry.ArrayIndex = numInits;
  1243. endField = APValue(APValue::LValueBase(backingArray),
  1244. ctx.getTypeSizeInChars(elementType) * numInits,
  1245. llvm::makeArrayRef(endOffsetPathEntry),
  1246. /*IsOnePastTheEnd=*/true, 0);
  1247. } else {
  1248. APValue &sizeField = initListValue.getStructField(1);
  1249. sizeField = APValue(llvm::APSInt(numElements));
  1250. }
  1251. // Emit the constant for the initializer_list.
  1252. llvm::Constant *llvmInit =
  1253. EmitConstantValueForMemory(initListValue, D->getType());
  1254. assert(llvmInit && "failed to initialize as constant");
  1255. return llvmInit;
  1256. }
  1257. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1258. llvm::Constant *Init = 0;
  1259. QualType ASTTy = D->getType();
  1260. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1261. bool NeedsGlobalCtor = false;
  1262. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1263. const VarDecl *InitDecl;
  1264. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1265. if (!InitExpr) {
  1266. // This is a tentative definition; tentative definitions are
  1267. // implicitly initialized with { 0 }.
  1268. //
  1269. // Note that tentative definitions are only emitted at the end of
  1270. // a translation unit, so they should never have incomplete
  1271. // type. In addition, EmitTentativeDefinition makes sure that we
  1272. // never attempt to emit a tentative definition if a real one
  1273. // exists. A use may still exists, however, so we still may need
  1274. // to do a RAUW.
  1275. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1276. Init = EmitNullConstant(D->getType());
  1277. } else {
  1278. // If this is a std::initializer_list, emit the special initializer.
  1279. Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
  1280. // An empty init list will perform zero-initialization, which happens
  1281. // to be exactly what we want.
  1282. // FIXME: It does so in a global constructor, which is *not* what we
  1283. // want.
  1284. if (!Init)
  1285. Init = EmitConstantInit(*InitDecl);
  1286. if (!Init) {
  1287. QualType T = InitExpr->getType();
  1288. if (D->getType()->isReferenceType())
  1289. T = D->getType();
  1290. if (getLangOpts().CPlusPlus) {
  1291. Init = EmitNullConstant(T);
  1292. NeedsGlobalCtor = true;
  1293. } else {
  1294. ErrorUnsupported(D, "static initializer");
  1295. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1296. }
  1297. } else {
  1298. // We don't need an initializer, so remove the entry for the delayed
  1299. // initializer position (just in case this entry was delayed) if we
  1300. // also don't need to register a destructor.
  1301. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1302. DelayedCXXInitPosition.erase(D);
  1303. }
  1304. }
  1305. llvm::Type* InitType = Init->getType();
  1306. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1307. // Strip off a bitcast if we got one back.
  1308. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1309. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1310. // all zero index gep.
  1311. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1312. Entry = CE->getOperand(0);
  1313. }
  1314. // Entry is now either a Function or GlobalVariable.
  1315. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1316. // We have a definition after a declaration with the wrong type.
  1317. // We must make a new GlobalVariable* and update everything that used OldGV
  1318. // (a declaration or tentative definition) with the new GlobalVariable*
  1319. // (which will be a definition).
  1320. //
  1321. // This happens if there is a prototype for a global (e.g.
  1322. // "extern int x[];") and then a definition of a different type (e.g.
  1323. // "int x[10];"). This also happens when an initializer has a different type
  1324. // from the type of the global (this happens with unions).
  1325. if (GV == 0 ||
  1326. GV->getType()->getElementType() != InitType ||
  1327. GV->getType()->getAddressSpace() !=
  1328. getContext().getTargetAddressSpace(ASTTy)) {
  1329. // Move the old entry aside so that we'll create a new one.
  1330. Entry->setName(StringRef());
  1331. // Make a new global with the correct type, this is now guaranteed to work.
  1332. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1333. // Replace all uses of the old global with the new global
  1334. llvm::Constant *NewPtrForOldDecl =
  1335. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1336. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1337. // Erase the old global, since it is no longer used.
  1338. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1339. }
  1340. if (D->hasAttr<AnnotateAttr>())
  1341. AddGlobalAnnotations(D, GV);
  1342. GV->setInitializer(Init);
  1343. // If it is safe to mark the global 'constant', do so now.
  1344. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1345. isTypeConstant(D->getType(), true));
  1346. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1347. // Set the llvm linkage type as appropriate.
  1348. llvm::GlobalValue::LinkageTypes Linkage =
  1349. GetLLVMLinkageVarDefinition(D, GV);
  1350. GV->setLinkage(Linkage);
  1351. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1352. // common vars aren't constant even if declared const.
  1353. GV->setConstant(false);
  1354. SetCommonAttributes(D, GV);
  1355. // Emit the initializer function if necessary.
  1356. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1357. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1358. // Emit global variable debug information.
  1359. if (CGDebugInfo *DI = getModuleDebugInfo())
  1360. DI->EmitGlobalVariable(GV, D);
  1361. }
  1362. llvm::GlobalValue::LinkageTypes
  1363. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1364. llvm::GlobalVariable *GV) {
  1365. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1366. if (Linkage == GVA_Internal)
  1367. return llvm::Function::InternalLinkage;
  1368. else if (D->hasAttr<DLLImportAttr>())
  1369. return llvm::Function::DLLImportLinkage;
  1370. else if (D->hasAttr<DLLExportAttr>())
  1371. return llvm::Function::DLLExportLinkage;
  1372. else if (D->hasAttr<WeakAttr>()) {
  1373. if (GV->isConstant())
  1374. return llvm::GlobalVariable::WeakODRLinkage;
  1375. else
  1376. return llvm::GlobalVariable::WeakAnyLinkage;
  1377. } else if (Linkage == GVA_TemplateInstantiation ||
  1378. Linkage == GVA_ExplicitTemplateInstantiation)
  1379. return llvm::GlobalVariable::WeakODRLinkage;
  1380. else if (!getLangOpts().CPlusPlus &&
  1381. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1382. D->getAttr<CommonAttr>()) &&
  1383. !D->hasExternalStorage() && !D->getInit() &&
  1384. !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
  1385. !D->getAttr<WeakImportAttr>()) {
  1386. // Thread local vars aren't considered common linkage.
  1387. return llvm::GlobalVariable::CommonLinkage;
  1388. }
  1389. return llvm::GlobalVariable::ExternalLinkage;
  1390. }
  1391. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1392. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1393. /// existing call uses of the old function in the module, this adjusts them to
  1394. /// call the new function directly.
  1395. ///
  1396. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1397. /// functions to be able to inline them. If there is a bitcast in the way, it
  1398. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1399. /// run at -O0.
  1400. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1401. llvm::Function *NewFn) {
  1402. // If we're redefining a global as a function, don't transform it.
  1403. llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
  1404. if (OldFn == 0) return;
  1405. llvm::Type *NewRetTy = NewFn->getReturnType();
  1406. SmallVector<llvm::Value*, 4> ArgList;
  1407. for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
  1408. UI != E; ) {
  1409. // TODO: Do invokes ever occur in C code? If so, we should handle them too.
  1410. llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
  1411. llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
  1412. if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
  1413. llvm::CallSite CS(CI);
  1414. if (!CI || !CS.isCallee(I)) continue;
  1415. // If the return types don't match exactly, and if the call isn't dead, then
  1416. // we can't transform this call.
  1417. if (CI->getType() != NewRetTy && !CI->use_empty())
  1418. continue;
  1419. // Get the attribute list.
  1420. llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
  1421. llvm::AttrListPtr AttrList = CI->getAttributes();
  1422. // Get any return attributes.
  1423. llvm::Attributes RAttrs = AttrList.getRetAttributes();
  1424. // Add the return attributes.
  1425. if (RAttrs)
  1426. AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
  1427. // If the function was passed too few arguments, don't transform. If extra
  1428. // arguments were passed, we silently drop them. If any of the types
  1429. // mismatch, we don't transform.
  1430. unsigned ArgNo = 0;
  1431. bool DontTransform = false;
  1432. for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
  1433. E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
  1434. if (CS.arg_size() == ArgNo ||
  1435. CS.getArgument(ArgNo)->getType() != AI->getType()) {
  1436. DontTransform = true;
  1437. break;
  1438. }
  1439. // Add any parameter attributes.
  1440. if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
  1441. AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
  1442. }
  1443. if (DontTransform)
  1444. continue;
  1445. if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
  1446. AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
  1447. // Okay, we can transform this. Create the new call instruction and copy
  1448. // over the required information.
  1449. ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
  1450. llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
  1451. ArgList.clear();
  1452. if (!NewCall->getType()->isVoidTy())
  1453. NewCall->takeName(CI);
  1454. NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
  1455. AttrVec.end()));
  1456. NewCall->setCallingConv(CI->getCallingConv());
  1457. // Finally, remove the old call, replacing any uses with the new one.
  1458. if (!CI->use_empty())
  1459. CI->replaceAllUsesWith(NewCall);
  1460. // Copy debug location attached to CI.
  1461. if (!CI->getDebugLoc().isUnknown())
  1462. NewCall->setDebugLoc(CI->getDebugLoc());
  1463. CI->eraseFromParent();
  1464. }
  1465. }
  1466. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1467. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1468. // If we have a definition, this might be a deferred decl. If the
  1469. // instantiation is explicit, make sure we emit it at the end.
  1470. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1471. GetAddrOfGlobalVar(VD);
  1472. }
  1473. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1474. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1475. // Compute the function info and LLVM type.
  1476. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1477. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1478. // Get or create the prototype for the function.
  1479. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1480. // Strip off a bitcast if we got one back.
  1481. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1482. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1483. Entry = CE->getOperand(0);
  1484. }
  1485. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1486. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1487. // If the types mismatch then we have to rewrite the definition.
  1488. assert(OldFn->isDeclaration() &&
  1489. "Shouldn't replace non-declaration");
  1490. // F is the Function* for the one with the wrong type, we must make a new
  1491. // Function* and update everything that used F (a declaration) with the new
  1492. // Function* (which will be a definition).
  1493. //
  1494. // This happens if there is a prototype for a function
  1495. // (e.g. "int f()") and then a definition of a different type
  1496. // (e.g. "int f(int x)"). Move the old function aside so that it
  1497. // doesn't interfere with GetAddrOfFunction.
  1498. OldFn->setName(StringRef());
  1499. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1500. // If this is an implementation of a function without a prototype, try to
  1501. // replace any existing uses of the function (which may be calls) with uses
  1502. // of the new function
  1503. if (D->getType()->isFunctionNoProtoType()) {
  1504. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1505. OldFn->removeDeadConstantUsers();
  1506. }
  1507. // Replace uses of F with the Function we will endow with a body.
  1508. if (!Entry->use_empty()) {
  1509. llvm::Constant *NewPtrForOldDecl =
  1510. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1511. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1512. }
  1513. // Ok, delete the old function now, which is dead.
  1514. OldFn->eraseFromParent();
  1515. Entry = NewFn;
  1516. }
  1517. // We need to set linkage and visibility on the function before
  1518. // generating code for it because various parts of IR generation
  1519. // want to propagate this information down (e.g. to local static
  1520. // declarations).
  1521. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1522. setFunctionLinkage(D, Fn);
  1523. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1524. setGlobalVisibility(Fn, D);
  1525. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1526. SetFunctionDefinitionAttributes(D, Fn);
  1527. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1528. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1529. AddGlobalCtor(Fn, CA->getPriority());
  1530. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1531. AddGlobalDtor(Fn, DA->getPriority());
  1532. if (D->hasAttr<AnnotateAttr>())
  1533. AddGlobalAnnotations(D, Fn);
  1534. }
  1535. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1536. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1537. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1538. assert(AA && "Not an alias?");
  1539. StringRef MangledName = getMangledName(GD);
  1540. // If there is a definition in the module, then it wins over the alias.
  1541. // This is dubious, but allow it to be safe. Just ignore the alias.
  1542. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1543. if (Entry && !Entry->isDeclaration())
  1544. return;
  1545. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1546. // Create a reference to the named value. This ensures that it is emitted
  1547. // if a deferred decl.
  1548. llvm::Constant *Aliasee;
  1549. if (isa<llvm::FunctionType>(DeclTy))
  1550. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  1551. /*ForVTable=*/false);
  1552. else
  1553. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1554. llvm::PointerType::getUnqual(DeclTy), 0);
  1555. // Create the new alias itself, but don't set a name yet.
  1556. llvm::GlobalValue *GA =
  1557. new llvm::GlobalAlias(Aliasee->getType(),
  1558. llvm::Function::ExternalLinkage,
  1559. "", Aliasee, &getModule());
  1560. if (Entry) {
  1561. assert(Entry->isDeclaration());
  1562. // If there is a declaration in the module, then we had an extern followed
  1563. // by the alias, as in:
  1564. // extern int test6();
  1565. // ...
  1566. // int test6() __attribute__((alias("test7")));
  1567. //
  1568. // Remove it and replace uses of it with the alias.
  1569. GA->takeName(Entry);
  1570. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1571. Entry->getType()));
  1572. Entry->eraseFromParent();
  1573. } else {
  1574. GA->setName(MangledName);
  1575. }
  1576. // Set attributes which are particular to an alias; this is a
  1577. // specialization of the attributes which may be set on a global
  1578. // variable/function.
  1579. if (D->hasAttr<DLLExportAttr>()) {
  1580. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1581. // The dllexport attribute is ignored for undefined symbols.
  1582. if (FD->hasBody())
  1583. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1584. } else {
  1585. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1586. }
  1587. } else if (D->hasAttr<WeakAttr>() ||
  1588. D->hasAttr<WeakRefAttr>() ||
  1589. D->isWeakImported()) {
  1590. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1591. }
  1592. SetCommonAttributes(D, GA);
  1593. }
  1594. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1595. ArrayRef<llvm::Type*> Tys) {
  1596. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1597. Tys);
  1598. }
  1599. static llvm::StringMapEntry<llvm::Constant*> &
  1600. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1601. const StringLiteral *Literal,
  1602. bool TargetIsLSB,
  1603. bool &IsUTF16,
  1604. unsigned &StringLength) {
  1605. StringRef String = Literal->getString();
  1606. unsigned NumBytes = String.size();
  1607. // Check for simple case.
  1608. if (!Literal->containsNonAsciiOrNull()) {
  1609. StringLength = NumBytes;
  1610. return Map.GetOrCreateValue(String);
  1611. }
  1612. // Otherwise, convert the UTF8 literals into a string of shorts.
  1613. IsUTF16 = true;
  1614. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1615. const UTF8 *FromPtr = (UTF8 *)String.data();
  1616. UTF16 *ToPtr = &ToBuf[0];
  1617. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1618. &ToPtr, ToPtr + NumBytes,
  1619. strictConversion);
  1620. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1621. StringLength = ToPtr - &ToBuf[0];
  1622. // Add an explicit null.
  1623. *ToPtr = 0;
  1624. return Map.
  1625. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1626. (StringLength + 1) * 2));
  1627. }
  1628. static llvm::StringMapEntry<llvm::Constant*> &
  1629. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1630. const StringLiteral *Literal,
  1631. unsigned &StringLength) {
  1632. StringRef String = Literal->getString();
  1633. StringLength = String.size();
  1634. return Map.GetOrCreateValue(String);
  1635. }
  1636. llvm::Constant *
  1637. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1638. unsigned StringLength = 0;
  1639. bool isUTF16 = false;
  1640. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1641. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1642. getTargetData().isLittleEndian(),
  1643. isUTF16, StringLength);
  1644. if (llvm::Constant *C = Entry.getValue())
  1645. return C;
  1646. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1647. llvm::Constant *Zeros[] = { Zero, Zero };
  1648. // If we don't already have it, get __CFConstantStringClassReference.
  1649. if (!CFConstantStringClassRef) {
  1650. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1651. Ty = llvm::ArrayType::get(Ty, 0);
  1652. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1653. "__CFConstantStringClassReference");
  1654. // Decay array -> ptr
  1655. CFConstantStringClassRef =
  1656. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1657. }
  1658. QualType CFTy = getContext().getCFConstantStringType();
  1659. llvm::StructType *STy =
  1660. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1661. llvm::Constant *Fields[4];
  1662. // Class pointer.
  1663. Fields[0] = CFConstantStringClassRef;
  1664. // Flags.
  1665. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1666. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1667. llvm::ConstantInt::get(Ty, 0x07C8);
  1668. // String pointer.
  1669. llvm::Constant *C = 0;
  1670. if (isUTF16) {
  1671. ArrayRef<uint16_t> Arr =
  1672. llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
  1673. Entry.getKey().size() / 2);
  1674. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1675. } else {
  1676. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1677. }
  1678. llvm::GlobalValue::LinkageTypes Linkage;
  1679. if (isUTF16)
  1680. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1681. Linkage = llvm::GlobalValue::InternalLinkage;
  1682. else
  1683. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1684. // when using private linkage. It is not clear if this is a bug in ld
  1685. // or a reasonable new restriction.
  1686. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1687. // Note: -fwritable-strings doesn't make the backing store strings of
  1688. // CFStrings writable. (See <rdar://problem/10657500>)
  1689. llvm::GlobalVariable *GV =
  1690. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1691. Linkage, C, ".str");
  1692. GV->setUnnamedAddr(true);
  1693. if (isUTF16) {
  1694. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1695. GV->setAlignment(Align.getQuantity());
  1696. } else {
  1697. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1698. GV->setAlignment(Align.getQuantity());
  1699. }
  1700. // String.
  1701. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1702. if (isUTF16)
  1703. // Cast the UTF16 string to the correct type.
  1704. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1705. // String length.
  1706. Ty = getTypes().ConvertType(getContext().LongTy);
  1707. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1708. // The struct.
  1709. C = llvm::ConstantStruct::get(STy, Fields);
  1710. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1711. llvm::GlobalVariable::PrivateLinkage, C,
  1712. "_unnamed_cfstring_");
  1713. if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
  1714. GV->setSection(Sect);
  1715. Entry.setValue(GV);
  1716. return GV;
  1717. }
  1718. static RecordDecl *
  1719. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1720. DeclContext *DC, IdentifierInfo *Id) {
  1721. SourceLocation Loc;
  1722. if (Ctx.getLangOpts().CPlusPlus)
  1723. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1724. else
  1725. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1726. }
  1727. llvm::Constant *
  1728. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1729. unsigned StringLength = 0;
  1730. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1731. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1732. if (llvm::Constant *C = Entry.getValue())
  1733. return C;
  1734. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1735. llvm::Constant *Zeros[] = { Zero, Zero };
  1736. // If we don't already have it, get _NSConstantStringClassReference.
  1737. if (!ConstantStringClassRef) {
  1738. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  1739. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1740. llvm::Constant *GV;
  1741. if (LangOpts.ObjCNonFragileABI) {
  1742. std::string str =
  1743. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  1744. : "OBJC_CLASS_$_" + StringClass;
  1745. GV = getObjCRuntime().GetClassGlobal(str);
  1746. // Make sure the result is of the correct type.
  1747. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1748. ConstantStringClassRef =
  1749. llvm::ConstantExpr::getBitCast(GV, PTy);
  1750. } else {
  1751. std::string str =
  1752. StringClass.empty() ? "_NSConstantStringClassReference"
  1753. : "_" + StringClass + "ClassReference";
  1754. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  1755. GV = CreateRuntimeVariable(PTy, str);
  1756. // Decay array -> ptr
  1757. ConstantStringClassRef =
  1758. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1759. }
  1760. }
  1761. if (!NSConstantStringType) {
  1762. // Construct the type for a constant NSString.
  1763. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1764. Context.getTranslationUnitDecl(),
  1765. &Context.Idents.get("__builtin_NSString"));
  1766. D->startDefinition();
  1767. QualType FieldTypes[3];
  1768. // const int *isa;
  1769. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  1770. // const char *str;
  1771. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  1772. // unsigned int length;
  1773. FieldTypes[2] = Context.UnsignedIntTy;
  1774. // Create fields
  1775. for (unsigned i = 0; i < 3; ++i) {
  1776. FieldDecl *Field = FieldDecl::Create(Context, D,
  1777. SourceLocation(),
  1778. SourceLocation(), 0,
  1779. FieldTypes[i], /*TInfo=*/0,
  1780. /*BitWidth=*/0,
  1781. /*Mutable=*/false,
  1782. /*HasInit=*/false);
  1783. Field->setAccess(AS_public);
  1784. D->addDecl(Field);
  1785. }
  1786. D->completeDefinition();
  1787. QualType NSTy = Context.getTagDeclType(D);
  1788. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1789. }
  1790. llvm::Constant *Fields[3];
  1791. // Class pointer.
  1792. Fields[0] = ConstantStringClassRef;
  1793. // String pointer.
  1794. llvm::Constant *C =
  1795. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1796. llvm::GlobalValue::LinkageTypes Linkage;
  1797. bool isConstant;
  1798. Linkage = llvm::GlobalValue::PrivateLinkage;
  1799. isConstant = !LangOpts.WritableStrings;
  1800. llvm::GlobalVariable *GV =
  1801. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1802. ".str");
  1803. GV->setUnnamedAddr(true);
  1804. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1805. GV->setAlignment(Align.getQuantity());
  1806. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1807. // String length.
  1808. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1809. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1810. // The struct.
  1811. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  1812. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1813. llvm::GlobalVariable::PrivateLinkage, C,
  1814. "_unnamed_nsstring_");
  1815. // FIXME. Fix section.
  1816. if (const char *Sect =
  1817. LangOpts.ObjCNonFragileABI
  1818. ? getContext().getTargetInfo().getNSStringNonFragileABISection()
  1819. : getContext().getTargetInfo().getNSStringSection())
  1820. GV->setSection(Sect);
  1821. Entry.setValue(GV);
  1822. return GV;
  1823. }
  1824. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  1825. if (ObjCFastEnumerationStateType.isNull()) {
  1826. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1827. Context.getTranslationUnitDecl(),
  1828. &Context.Idents.get("__objcFastEnumerationState"));
  1829. D->startDefinition();
  1830. QualType FieldTypes[] = {
  1831. Context.UnsignedLongTy,
  1832. Context.getPointerType(Context.getObjCIdType()),
  1833. Context.getPointerType(Context.UnsignedLongTy),
  1834. Context.getConstantArrayType(Context.UnsignedLongTy,
  1835. llvm::APInt(32, 5), ArrayType::Normal, 0)
  1836. };
  1837. for (size_t i = 0; i < 4; ++i) {
  1838. FieldDecl *Field = FieldDecl::Create(Context,
  1839. D,
  1840. SourceLocation(),
  1841. SourceLocation(), 0,
  1842. FieldTypes[i], /*TInfo=*/0,
  1843. /*BitWidth=*/0,
  1844. /*Mutable=*/false,
  1845. /*HasInit=*/false);
  1846. Field->setAccess(AS_public);
  1847. D->addDecl(Field);
  1848. }
  1849. D->completeDefinition();
  1850. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  1851. }
  1852. return ObjCFastEnumerationStateType;
  1853. }
  1854. llvm::Constant *
  1855. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  1856. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  1857. // Don't emit it as the address of the string, emit the string data itself
  1858. // as an inline array.
  1859. if (E->getCharByteWidth() == 1) {
  1860. SmallString<64> Str(E->getString());
  1861. // Resize the string to the right size, which is indicated by its type.
  1862. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  1863. Str.resize(CAT->getSize().getZExtValue());
  1864. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  1865. }
  1866. llvm::ArrayType *AType =
  1867. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  1868. llvm::Type *ElemTy = AType->getElementType();
  1869. unsigned NumElements = AType->getNumElements();
  1870. // Wide strings have either 2-byte or 4-byte elements.
  1871. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  1872. SmallVector<uint16_t, 32> Elements;
  1873. Elements.reserve(NumElements);
  1874. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1875. Elements.push_back(E->getCodeUnit(i));
  1876. Elements.resize(NumElements);
  1877. return llvm::ConstantDataArray::get(VMContext, Elements);
  1878. }
  1879. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  1880. SmallVector<uint32_t, 32> Elements;
  1881. Elements.reserve(NumElements);
  1882. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1883. Elements.push_back(E->getCodeUnit(i));
  1884. Elements.resize(NumElements);
  1885. return llvm::ConstantDataArray::get(VMContext, Elements);
  1886. }
  1887. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  1888. /// constant array for the given string literal.
  1889. llvm::Constant *
  1890. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  1891. CharUnits Align = getContext().getTypeAlignInChars(S->getType());
  1892. if (S->isAscii() || S->isUTF8()) {
  1893. SmallString<64> Str(S->getString());
  1894. // Resize the string to the right size, which is indicated by its type.
  1895. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  1896. Str.resize(CAT->getSize().getZExtValue());
  1897. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  1898. }
  1899. // FIXME: the following does not memoize wide strings.
  1900. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  1901. llvm::GlobalVariable *GV =
  1902. new llvm::GlobalVariable(getModule(),C->getType(),
  1903. !LangOpts.WritableStrings,
  1904. llvm::GlobalValue::PrivateLinkage,
  1905. C,".str");
  1906. GV->setAlignment(Align.getQuantity());
  1907. GV->setUnnamedAddr(true);
  1908. return GV;
  1909. }
  1910. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  1911. /// array for the given ObjCEncodeExpr node.
  1912. llvm::Constant *
  1913. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  1914. std::string Str;
  1915. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1916. return GetAddrOfConstantCString(Str);
  1917. }
  1918. /// GenerateWritableString -- Creates storage for a string literal.
  1919. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  1920. bool constant,
  1921. CodeGenModule &CGM,
  1922. const char *GlobalName,
  1923. unsigned Alignment) {
  1924. // Create Constant for this string literal. Don't add a '\0'.
  1925. llvm::Constant *C =
  1926. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  1927. // Create a global variable for this string
  1928. llvm::GlobalVariable *GV =
  1929. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  1930. llvm::GlobalValue::PrivateLinkage,
  1931. C, GlobalName);
  1932. GV->setAlignment(Alignment);
  1933. GV->setUnnamedAddr(true);
  1934. return GV;
  1935. }
  1936. /// GetAddrOfConstantString - Returns a pointer to a character array
  1937. /// containing the literal. This contents are exactly that of the
  1938. /// given string, i.e. it will not be null terminated automatically;
  1939. /// see GetAddrOfConstantCString. Note that whether the result is
  1940. /// actually a pointer to an LLVM constant depends on
  1941. /// Feature.WriteableStrings.
  1942. ///
  1943. /// The result has pointer to array type.
  1944. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  1945. const char *GlobalName,
  1946. unsigned Alignment) {
  1947. // Get the default prefix if a name wasn't specified.
  1948. if (!GlobalName)
  1949. GlobalName = ".str";
  1950. // Don't share any string literals if strings aren't constant.
  1951. if (LangOpts.WritableStrings)
  1952. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  1953. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  1954. ConstantStringMap.GetOrCreateValue(Str);
  1955. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  1956. if (Alignment > GV->getAlignment()) {
  1957. GV->setAlignment(Alignment);
  1958. }
  1959. return GV;
  1960. }
  1961. // Create a global variable for this.
  1962. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  1963. Alignment);
  1964. Entry.setValue(GV);
  1965. return GV;
  1966. }
  1967. /// GetAddrOfConstantCString - Returns a pointer to a character
  1968. /// array containing the literal and a terminating '\0'
  1969. /// character. The result has pointer to array type.
  1970. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  1971. const char *GlobalName,
  1972. unsigned Alignment) {
  1973. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  1974. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  1975. }
  1976. /// EmitObjCPropertyImplementations - Emit information for synthesized
  1977. /// properties for an implementation.
  1978. void CodeGenModule::EmitObjCPropertyImplementations(const
  1979. ObjCImplementationDecl *D) {
  1980. for (ObjCImplementationDecl::propimpl_iterator
  1981. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  1982. ObjCPropertyImplDecl *PID = *i;
  1983. // Dynamic is just for type-checking.
  1984. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  1985. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  1986. // Determine which methods need to be implemented, some may have
  1987. // been overridden. Note that ::isSynthesized is not the method
  1988. // we want, that just indicates if the decl came from a
  1989. // property. What we want to know is if the method is defined in
  1990. // this implementation.
  1991. if (!D->getInstanceMethod(PD->getGetterName()))
  1992. CodeGenFunction(*this).GenerateObjCGetter(
  1993. const_cast<ObjCImplementationDecl *>(D), PID);
  1994. if (!PD->isReadOnly() &&
  1995. !D->getInstanceMethod(PD->getSetterName()))
  1996. CodeGenFunction(*this).GenerateObjCSetter(
  1997. const_cast<ObjCImplementationDecl *>(D), PID);
  1998. }
  1999. }
  2000. }
  2001. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2002. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2003. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2004. ivar; ivar = ivar->getNextIvar())
  2005. if (ivar->getType().isDestructedType())
  2006. return true;
  2007. return false;
  2008. }
  2009. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2010. /// for an implementation.
  2011. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2012. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2013. if (needsDestructMethod(D)) {
  2014. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2015. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2016. ObjCMethodDecl *DTORMethod =
  2017. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2018. cxxSelector, getContext().VoidTy, 0, D,
  2019. /*isInstance=*/true, /*isVariadic=*/false,
  2020. /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
  2021. /*isDefined=*/false, ObjCMethodDecl::Required);
  2022. D->addInstanceMethod(DTORMethod);
  2023. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2024. D->setHasCXXStructors(true);
  2025. }
  2026. // If the implementation doesn't have any ivar initializers, we don't need
  2027. // a .cxx_construct.
  2028. if (D->getNumIvarInitializers() == 0)
  2029. return;
  2030. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2031. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2032. // The constructor returns 'self'.
  2033. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2034. D->getLocation(),
  2035. D->getLocation(),
  2036. cxxSelector,
  2037. getContext().getObjCIdType(), 0,
  2038. D, /*isInstance=*/true,
  2039. /*isVariadic=*/false,
  2040. /*isSynthesized=*/true,
  2041. /*isImplicitlyDeclared=*/true,
  2042. /*isDefined=*/false,
  2043. ObjCMethodDecl::Required);
  2044. D->addInstanceMethod(CTORMethod);
  2045. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2046. D->setHasCXXStructors(true);
  2047. }
  2048. /// EmitNamespace - Emit all declarations in a namespace.
  2049. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2050. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2051. I != E; ++I)
  2052. EmitTopLevelDecl(*I);
  2053. }
  2054. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2055. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2056. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2057. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2058. ErrorUnsupported(LSD, "linkage spec");
  2059. return;
  2060. }
  2061. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2062. I != E; ++I)
  2063. EmitTopLevelDecl(*I);
  2064. }
  2065. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2066. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2067. // If an error has occurred, stop code generation, but continue
  2068. // parsing and semantic analysis (to ensure all warnings and errors
  2069. // are emitted).
  2070. if (Diags.hasErrorOccurred())
  2071. return;
  2072. // Ignore dependent declarations.
  2073. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2074. return;
  2075. switch (D->getKind()) {
  2076. case Decl::CXXConversion:
  2077. case Decl::CXXMethod:
  2078. case Decl::Function:
  2079. // Skip function templates
  2080. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2081. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2082. return;
  2083. EmitGlobal(cast<FunctionDecl>(D));
  2084. break;
  2085. case Decl::Var:
  2086. EmitGlobal(cast<VarDecl>(D));
  2087. break;
  2088. // Indirect fields from global anonymous structs and unions can be
  2089. // ignored; only the actual variable requires IR gen support.
  2090. case Decl::IndirectField:
  2091. break;
  2092. // C++ Decls
  2093. case Decl::Namespace:
  2094. EmitNamespace(cast<NamespaceDecl>(D));
  2095. break;
  2096. // No code generation needed.
  2097. case Decl::UsingShadow:
  2098. case Decl::Using:
  2099. case Decl::UsingDirective:
  2100. case Decl::ClassTemplate:
  2101. case Decl::FunctionTemplate:
  2102. case Decl::TypeAliasTemplate:
  2103. case Decl::NamespaceAlias:
  2104. case Decl::Block:
  2105. case Decl::Import:
  2106. break;
  2107. case Decl::CXXConstructor:
  2108. // Skip function templates
  2109. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2110. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2111. return;
  2112. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2113. break;
  2114. case Decl::CXXDestructor:
  2115. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2116. return;
  2117. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2118. break;
  2119. case Decl::StaticAssert:
  2120. // Nothing to do.
  2121. break;
  2122. // Objective-C Decls
  2123. // Forward declarations, no (immediate) code generation.
  2124. case Decl::ObjCInterface:
  2125. break;
  2126. case Decl::ObjCCategory: {
  2127. ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
  2128. if (CD->IsClassExtension() && CD->hasSynthBitfield())
  2129. Context.ResetObjCLayout(CD->getClassInterface());
  2130. break;
  2131. }
  2132. case Decl::ObjCProtocol: {
  2133. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2134. if (Proto->isThisDeclarationADefinition())
  2135. ObjCRuntime->GenerateProtocol(Proto);
  2136. break;
  2137. }
  2138. case Decl::ObjCCategoryImpl:
  2139. // Categories have properties but don't support synthesize so we
  2140. // can ignore them here.
  2141. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2142. break;
  2143. case Decl::ObjCImplementation: {
  2144. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2145. if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
  2146. Context.ResetObjCLayout(OMD->getClassInterface());
  2147. EmitObjCPropertyImplementations(OMD);
  2148. EmitObjCIvarInitializations(OMD);
  2149. ObjCRuntime->GenerateClass(OMD);
  2150. break;
  2151. }
  2152. case Decl::ObjCMethod: {
  2153. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2154. // If this is not a prototype, emit the body.
  2155. if (OMD->getBody())
  2156. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2157. break;
  2158. }
  2159. case Decl::ObjCCompatibleAlias:
  2160. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2161. break;
  2162. case Decl::LinkageSpec:
  2163. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2164. break;
  2165. case Decl::FileScopeAsm: {
  2166. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2167. StringRef AsmString = AD->getAsmString()->getString();
  2168. const std::string &S = getModule().getModuleInlineAsm();
  2169. if (S.empty())
  2170. getModule().setModuleInlineAsm(AsmString);
  2171. else if (*--S.end() == '\n')
  2172. getModule().setModuleInlineAsm(S + AsmString.str());
  2173. else
  2174. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2175. break;
  2176. }
  2177. default:
  2178. // Make sure we handled everything we should, every other kind is a
  2179. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2180. // function. Need to recode Decl::Kind to do that easily.
  2181. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2182. }
  2183. }
  2184. /// Turns the given pointer into a constant.
  2185. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2186. const void *Ptr) {
  2187. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2188. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2189. return llvm::ConstantInt::get(i64, PtrInt);
  2190. }
  2191. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2192. llvm::NamedMDNode *&GlobalMetadata,
  2193. GlobalDecl D,
  2194. llvm::GlobalValue *Addr) {
  2195. if (!GlobalMetadata)
  2196. GlobalMetadata =
  2197. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2198. // TODO: should we report variant information for ctors/dtors?
  2199. llvm::Value *Ops[] = {
  2200. Addr,
  2201. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2202. };
  2203. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2204. }
  2205. /// Emits metadata nodes associating all the global values in the
  2206. /// current module with the Decls they came from. This is useful for
  2207. /// projects using IR gen as a subroutine.
  2208. ///
  2209. /// Since there's currently no way to associate an MDNode directly
  2210. /// with an llvm::GlobalValue, we create a global named metadata
  2211. /// with the name 'clang.global.decl.ptrs'.
  2212. void CodeGenModule::EmitDeclMetadata() {
  2213. llvm::NamedMDNode *GlobalMetadata = 0;
  2214. // StaticLocalDeclMap
  2215. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2216. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2217. I != E; ++I) {
  2218. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2219. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2220. }
  2221. }
  2222. /// Emits metadata nodes for all the local variables in the current
  2223. /// function.
  2224. void CodeGenFunction::EmitDeclMetadata() {
  2225. if (LocalDeclMap.empty()) return;
  2226. llvm::LLVMContext &Context = getLLVMContext();
  2227. // Find the unique metadata ID for this name.
  2228. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2229. llvm::NamedMDNode *GlobalMetadata = 0;
  2230. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2231. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2232. const Decl *D = I->first;
  2233. llvm::Value *Addr = I->second;
  2234. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2235. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2236. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2237. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2238. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2239. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2240. }
  2241. }
  2242. }
  2243. void CodeGenModule::EmitCoverageFile() {
  2244. if (!getCodeGenOpts().CoverageFile.empty()) {
  2245. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2246. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2247. llvm::LLVMContext &Ctx = TheModule.getContext();
  2248. llvm::MDString *CoverageFile =
  2249. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2250. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2251. llvm::MDNode *CU = CUNode->getOperand(i);
  2252. llvm::Value *node[] = { CoverageFile, CU };
  2253. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2254. GCov->addOperand(N);
  2255. }
  2256. }
  2257. }
  2258. }