CodeGenModule.cpp 98 KB

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