CodeGenModule.cpp 98 KB

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