TargetLoweringObjectFileImpl.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
  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 file implements classes used to handle lowerings specific to common
  11. // object file formats.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/MC/MCExpr.h"
  27. #include "llvm/MC/MCSectionCOFF.h"
  28. #include "llvm/MC/MCSectionELF.h"
  29. #include "llvm/MC/MCSectionMachO.h"
  30. #include "llvm/MC/MCStreamer.h"
  31. #include "llvm/MC/MCSymbol.h"
  32. #include "llvm/Support/Dwarf.h"
  33. #include "llvm/Support/ELF.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/Mangler.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. using namespace llvm;
  39. using namespace dwarf;
  40. //===----------------------------------------------------------------------===//
  41. // ELF
  42. //===----------------------------------------------------------------------===//
  43. MCSymbol *
  44. TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV,
  45. Mangler *Mang,
  46. MachineModuleInfo *MMI) const {
  47. unsigned Encoding = getPersonalityEncoding();
  48. switch (Encoding & 0x70) {
  49. default:
  50. report_fatal_error("We do not support this DWARF encoding yet!");
  51. case dwarf::DW_EH_PE_absptr:
  52. return Mang->getSymbol(GV);
  53. case dwarf::DW_EH_PE_pcrel: {
  54. return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
  55. Mang->getSymbol(GV)->getName());
  56. }
  57. }
  58. }
  59. void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
  60. const TargetMachine &TM,
  61. const MCSymbol *Sym) const {
  62. SmallString<64> NameData("DW.ref.");
  63. NameData += Sym->getName();
  64. MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
  65. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  66. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  67. StringRef Prefix = ".data.";
  68. NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
  69. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  70. const MCSection *Sec = getContext().getELFSection(NameData,
  71. ELF::SHT_PROGBITS,
  72. Flags,
  73. SectionKind::getDataRel(),
  74. 0, Label->getName());
  75. unsigned Size = TM.getDataLayout()->getPointerSize();
  76. Streamer.SwitchSection(Sec);
  77. Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
  78. Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  79. const MCExpr *E = MCConstantExpr::Create(Size, getContext());
  80. Streamer.EmitELFSize(Label, E);
  81. Streamer.EmitLabel(Label);
  82. Streamer.EmitSymbolValue(Sym, Size);
  83. }
  84. const MCExpr *TargetLoweringObjectFileELF::
  85. getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang,
  86. MachineModuleInfo *MMI, unsigned Encoding,
  87. MCStreamer &Streamer) const {
  88. if (Encoding & dwarf::DW_EH_PE_indirect) {
  89. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  90. SmallString<128> Name;
  91. Mang->getNameWithPrefix(Name, GV, true);
  92. Name += ".DW.stub";
  93. // Add information about the stub reference to ELFMMI so that the stub
  94. // gets emitted by the asmprinter.
  95. MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
  96. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  97. if (StubSym.getPointer() == 0) {
  98. MCSymbol *Sym = Mang->getSymbol(GV);
  99. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  100. }
  101. return TargetLoweringObjectFile::
  102. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  103. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  104. }
  105. return TargetLoweringObjectFile::
  106. getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
  107. }
  108. static SectionKind
  109. getELFKindForNamedSection(StringRef Name, SectionKind K) {
  110. // N.B.: The defaults used in here are no the same ones used in MC.
  111. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  112. // both gas and MC will produce a section with no flags. Given
  113. // section(".eh_frame") gcc will produce:
  114. //
  115. // .section .eh_frame,"a",@progbits
  116. if (Name.empty() || Name[0] != '.') return K;
  117. // Some lame default implementation based on some magic section names.
  118. if (Name == ".bss" ||
  119. Name.startswith(".bss.") ||
  120. Name.startswith(".gnu.linkonce.b.") ||
  121. Name.startswith(".llvm.linkonce.b.") ||
  122. Name == ".sbss" ||
  123. Name.startswith(".sbss.") ||
  124. Name.startswith(".gnu.linkonce.sb.") ||
  125. Name.startswith(".llvm.linkonce.sb."))
  126. return SectionKind::getBSS();
  127. if (Name == ".tdata" ||
  128. Name.startswith(".tdata.") ||
  129. Name.startswith(".gnu.linkonce.td.") ||
  130. Name.startswith(".llvm.linkonce.td."))
  131. return SectionKind::getThreadData();
  132. if (Name == ".tbss" ||
  133. Name.startswith(".tbss.") ||
  134. Name.startswith(".gnu.linkonce.tb.") ||
  135. Name.startswith(".llvm.linkonce.tb."))
  136. return SectionKind::getThreadBSS();
  137. return K;
  138. }
  139. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  140. if (Name == ".init_array")
  141. return ELF::SHT_INIT_ARRAY;
  142. if (Name == ".fini_array")
  143. return ELF::SHT_FINI_ARRAY;
  144. if (Name == ".preinit_array")
  145. return ELF::SHT_PREINIT_ARRAY;
  146. if (K.isBSS() || K.isThreadBSS())
  147. return ELF::SHT_NOBITS;
  148. return ELF::SHT_PROGBITS;
  149. }
  150. static unsigned
  151. getELFSectionFlags(SectionKind K) {
  152. unsigned Flags = 0;
  153. if (!K.isMetadata())
  154. Flags |= ELF::SHF_ALLOC;
  155. if (K.isText())
  156. Flags |= ELF::SHF_EXECINSTR;
  157. if (K.isWriteable())
  158. Flags |= ELF::SHF_WRITE;
  159. if (K.isThreadLocal())
  160. Flags |= ELF::SHF_TLS;
  161. // K.isMergeableConst() is left out to honour PR4650
  162. if (K.isMergeableCString() || K.isMergeableConst4() ||
  163. K.isMergeableConst8() || K.isMergeableConst16())
  164. Flags |= ELF::SHF_MERGE;
  165. if (K.isMergeableCString())
  166. Flags |= ELF::SHF_STRINGS;
  167. return Flags;
  168. }
  169. const MCSection *TargetLoweringObjectFileELF::
  170. getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
  171. Mangler *Mang, const TargetMachine &TM) const {
  172. StringRef SectionName = GV->getSection();
  173. // Infer section flags from the section name if we can.
  174. Kind = getELFKindForNamedSection(SectionName, Kind);
  175. return getContext().getELFSection(SectionName,
  176. getELFSectionType(SectionName, Kind),
  177. getELFSectionFlags(Kind), Kind);
  178. }
  179. /// getSectionPrefixForGlobal - Return the section prefix name used by options
  180. /// FunctionsSections and DataSections.
  181. static const char *getSectionPrefixForGlobal(SectionKind Kind) {
  182. if (Kind.isText()) return ".text.";
  183. if (Kind.isReadOnly()) return ".rodata.";
  184. if (Kind.isBSS()) return ".bss.";
  185. if (Kind.isThreadData()) return ".tdata.";
  186. if (Kind.isThreadBSS()) return ".tbss.";
  187. if (Kind.isDataNoRel()) return ".data.";
  188. if (Kind.isDataRelLocal()) return ".data.rel.local.";
  189. if (Kind.isDataRel()) return ".data.rel.";
  190. if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
  191. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  192. return ".data.rel.ro.";
  193. }
  194. const MCSection *TargetLoweringObjectFileELF::
  195. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  196. Mangler *Mang, const TargetMachine &TM) const {
  197. // If we have -ffunction-section or -fdata-section then we should emit the
  198. // global value to a uniqued section specifically for it.
  199. bool EmitUniquedSection;
  200. if (Kind.isText())
  201. EmitUniquedSection = TM.getFunctionSections();
  202. else
  203. EmitUniquedSection = TM.getDataSections();
  204. // If this global is linkonce/weak and the target handles this by emitting it
  205. // into a 'uniqued' section name, create and return the section now.
  206. if ((GV->isWeakForLinker() || EmitUniquedSection) &&
  207. !Kind.isCommon()) {
  208. const char *Prefix;
  209. Prefix = getSectionPrefixForGlobal(Kind);
  210. SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
  211. MCSymbol *Sym = Mang->getSymbol(GV);
  212. Name.append(Sym->getName().begin(), Sym->getName().end());
  213. StringRef Group = "";
  214. unsigned Flags = getELFSectionFlags(Kind);
  215. if (GV->isWeakForLinker()) {
  216. Group = Sym->getName();
  217. Flags |= ELF::SHF_GROUP;
  218. }
  219. return getContext().getELFSection(Name.str(),
  220. getELFSectionType(Name.str(), Kind),
  221. Flags, Kind, 0, Group);
  222. }
  223. if (Kind.isText()) return TextSection;
  224. if (Kind.isMergeable1ByteCString() ||
  225. Kind.isMergeable2ByteCString() ||
  226. Kind.isMergeable4ByteCString()) {
  227. // We also need alignment here.
  228. // FIXME: this is getting the alignment of the character, not the
  229. // alignment of the global!
  230. unsigned Align =
  231. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
  232. const char *SizeSpec = ".rodata.str1.";
  233. if (Kind.isMergeable2ByteCString())
  234. SizeSpec = ".rodata.str2.";
  235. else if (Kind.isMergeable4ByteCString())
  236. SizeSpec = ".rodata.str4.";
  237. else
  238. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  239. std::string Name = SizeSpec + utostr(Align);
  240. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  241. ELF::SHF_ALLOC |
  242. ELF::SHF_MERGE |
  243. ELF::SHF_STRINGS,
  244. Kind);
  245. }
  246. if (Kind.isMergeableConst()) {
  247. if (Kind.isMergeableConst4() && MergeableConst4Section)
  248. return MergeableConst4Section;
  249. if (Kind.isMergeableConst8() && MergeableConst8Section)
  250. return MergeableConst8Section;
  251. if (Kind.isMergeableConst16() && MergeableConst16Section)
  252. return MergeableConst16Section;
  253. return ReadOnlySection; // .const
  254. }
  255. if (Kind.isReadOnly()) return ReadOnlySection;
  256. if (Kind.isThreadData()) return TLSDataSection;
  257. if (Kind.isThreadBSS()) return TLSBSSSection;
  258. // Note: we claim that common symbols are put in BSSSection, but they are
  259. // really emitted with the magic .comm directive, which creates a symbol table
  260. // entry but not a section.
  261. if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
  262. if (Kind.isDataNoRel()) return DataSection;
  263. if (Kind.isDataRelLocal()) return DataRelLocalSection;
  264. if (Kind.isDataRel()) return DataRelSection;
  265. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  266. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  267. return DataRelROSection;
  268. }
  269. /// getSectionForConstant - Given a mergeable constant with the
  270. /// specified size and relocation information, return a section that it
  271. /// should be placed in.
  272. const MCSection *TargetLoweringObjectFileELF::
  273. getSectionForConstant(SectionKind Kind) const {
  274. if (Kind.isMergeableConst4() && MergeableConst4Section)
  275. return MergeableConst4Section;
  276. if (Kind.isMergeableConst8() && MergeableConst8Section)
  277. return MergeableConst8Section;
  278. if (Kind.isMergeableConst16() && MergeableConst16Section)
  279. return MergeableConst16Section;
  280. if (Kind.isReadOnly())
  281. return ReadOnlySection;
  282. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  283. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  284. return DataRelROSection;
  285. }
  286. const MCSection *
  287. TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
  288. // The default scheme is .ctor / .dtor, so we have to invert the priority
  289. // numbering.
  290. if (Priority == 65535)
  291. return StaticCtorSection;
  292. if (UseInitArray) {
  293. std::string Name = std::string(".init_array.") + utostr(Priority);
  294. return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
  295. ELF::SHF_ALLOC | ELF::SHF_WRITE,
  296. SectionKind::getDataRel());
  297. } else {
  298. std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
  299. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  300. ELF::SHF_ALLOC |ELF::SHF_WRITE,
  301. SectionKind::getDataRel());
  302. }
  303. }
  304. const MCSection *
  305. TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
  306. // The default scheme is .ctor / .dtor, so we have to invert the priority
  307. // numbering.
  308. if (Priority == 65535)
  309. return StaticDtorSection;
  310. if (UseInitArray) {
  311. std::string Name = std::string(".fini_array.") + utostr(Priority);
  312. return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
  313. ELF::SHF_ALLOC | ELF::SHF_WRITE,
  314. SectionKind::getDataRel());
  315. } else {
  316. std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
  317. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  318. ELF::SHF_ALLOC |ELF::SHF_WRITE,
  319. SectionKind::getDataRel());
  320. }
  321. }
  322. void
  323. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  324. UseInitArray = UseInitArray_;
  325. if (!UseInitArray)
  326. return;
  327. StaticCtorSection =
  328. getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  329. ELF::SHF_WRITE |
  330. ELF::SHF_ALLOC,
  331. SectionKind::getDataRel());
  332. StaticDtorSection =
  333. getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  334. ELF::SHF_WRITE |
  335. ELF::SHF_ALLOC,
  336. SectionKind::getDataRel());
  337. }
  338. //===----------------------------------------------------------------------===//
  339. // MachO
  340. //===----------------------------------------------------------------------===//
  341. /// emitModuleFlags - Perform code emission for module flags.
  342. void TargetLoweringObjectFileMachO::
  343. emitModuleFlags(MCStreamer &Streamer,
  344. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  345. Mangler *Mang, const TargetMachine &TM) const {
  346. unsigned VersionVal = 0;
  347. unsigned ImageInfoFlags = 0;
  348. MDNode *LinkerOptions = 0;
  349. StringRef SectionVal;
  350. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  351. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  352. const Module::ModuleFlagEntry &MFE = *i;
  353. // Ignore flags with 'Require' behavior.
  354. if (MFE.Behavior == Module::Require)
  355. continue;
  356. StringRef Key = MFE.Key->getString();
  357. Value *Val = MFE.Val;
  358. if (Key == "Objective-C Image Info Version") {
  359. VersionVal = cast<ConstantInt>(Val)->getZExtValue();
  360. } else if (Key == "Objective-C Garbage Collection" ||
  361. Key == "Objective-C GC Only" ||
  362. Key == "Objective-C Is Simulated") {
  363. ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
  364. } else if (Key == "Objective-C Image Info Section") {
  365. SectionVal = cast<MDString>(Val)->getString();
  366. } else if (Key == "Linker Options") {
  367. LinkerOptions = cast<MDNode>(Val);
  368. }
  369. }
  370. // Emit the linker options if present.
  371. if (LinkerOptions) {
  372. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  373. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  374. SmallVector<std::string, 4> StrOptions;
  375. // Convert to strings.
  376. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  377. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  378. StrOptions.push_back(MDOption->getString());
  379. }
  380. Streamer.EmitLinkerOptions(StrOptions);
  381. }
  382. }
  383. // The section is mandatory. If we don't have it, then we don't have GC info.
  384. if (SectionVal.empty()) return;
  385. StringRef Segment, Section;
  386. unsigned TAA = 0, StubSize = 0;
  387. bool TAAParsed;
  388. std::string ErrorCode =
  389. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  390. TAA, TAAParsed, StubSize);
  391. if (!ErrorCode.empty())
  392. // If invalid, report the error with report_fatal_error.
  393. report_fatal_error("Invalid section specifier '" + Section + "': " +
  394. ErrorCode + ".");
  395. // Get the section.
  396. const MCSectionMachO *S =
  397. getContext().getMachOSection(Segment, Section, TAA, StubSize,
  398. SectionKind::getDataNoRel());
  399. Streamer.SwitchSection(S);
  400. Streamer.EmitLabel(getContext().
  401. GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  402. Streamer.EmitIntValue(VersionVal, 4);
  403. Streamer.EmitIntValue(ImageInfoFlags, 4);
  404. Streamer.AddBlankLine();
  405. }
  406. const MCSection *TargetLoweringObjectFileMachO::
  407. getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
  408. Mangler *Mang, const TargetMachine &TM) const {
  409. // Parse the section specifier and create it if valid.
  410. StringRef Segment, Section;
  411. unsigned TAA = 0, StubSize = 0;
  412. bool TAAParsed;
  413. std::string ErrorCode =
  414. MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
  415. TAA, TAAParsed, StubSize);
  416. if (!ErrorCode.empty()) {
  417. // If invalid, report the error with report_fatal_error.
  418. report_fatal_error("Global variable '" + GV->getName() +
  419. "' has an invalid section specifier '" +
  420. GV->getSection() + "': " + ErrorCode + ".");
  421. }
  422. // Get the section.
  423. const MCSectionMachO *S =
  424. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  425. // If TAA wasn't set by ParseSectionSpecifier() above,
  426. // use the value returned by getMachOSection() as a default.
  427. if (!TAAParsed)
  428. TAA = S->getTypeAndAttributes();
  429. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  430. // If the user declared multiple globals with different section flags, we need
  431. // to reject it here.
  432. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  433. // If invalid, report the error with report_fatal_error.
  434. report_fatal_error("Global variable '" + GV->getName() +
  435. "' section type or attributes does not match previous"
  436. " section specifier");
  437. }
  438. return S;
  439. }
  440. const MCSection *TargetLoweringObjectFileMachO::
  441. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  442. Mangler *Mang, const TargetMachine &TM) const {
  443. // Handle thread local data.
  444. if (Kind.isThreadBSS()) return TLSBSSSection;
  445. if (Kind.isThreadData()) return TLSDataSection;
  446. if (Kind.isText())
  447. return GV->isWeakForLinker() ? TextCoalSection : TextSection;
  448. // If this is weak/linkonce, put this in a coalescable section, either in text
  449. // or data depending on if it is writable.
  450. if (GV->isWeakForLinker()) {
  451. if (Kind.isReadOnly())
  452. return ConstTextCoalSection;
  453. return DataCoalSection;
  454. }
  455. // FIXME: Alignment check should be handled by section classifier.
  456. if (Kind.isMergeable1ByteCString() &&
  457. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
  458. return CStringSection;
  459. // Do not put 16-bit arrays in the UString section if they have an
  460. // externally visible label, this runs into issues with certain linker
  461. // versions.
  462. if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
  463. TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
  464. return UStringSection;
  465. if (Kind.isMergeableConst()) {
  466. if (Kind.isMergeableConst4())
  467. return FourByteConstantSection;
  468. if (Kind.isMergeableConst8())
  469. return EightByteConstantSection;
  470. if (Kind.isMergeableConst16() && SixteenByteConstantSection)
  471. return SixteenByteConstantSection;
  472. }
  473. // Otherwise, if it is readonly, but not something we can specially optimize,
  474. // just drop it in .const.
  475. if (Kind.isReadOnly())
  476. return ReadOnlySection;
  477. // If this is marked const, put it into a const section. But if the dynamic
  478. // linker needs to write to it, put it in the data segment.
  479. if (Kind.isReadOnlyWithRel())
  480. return ConstDataSection;
  481. // Put zero initialized globals with strong external linkage in the
  482. // DATA, __common section with the .zerofill directive.
  483. if (Kind.isBSSExtern())
  484. return DataCommonSection;
  485. // Put zero initialized globals with local linkage in __DATA,__bss directive
  486. // with the .zerofill directive (aka .lcomm).
  487. if (Kind.isBSSLocal())
  488. return DataBSSSection;
  489. // Otherwise, just drop the variable in the normal data section.
  490. return DataSection;
  491. }
  492. const MCSection *
  493. TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
  494. // If this constant requires a relocation, we have to put it in the data
  495. // segment, not in the text segment.
  496. if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
  497. return ConstDataSection;
  498. if (Kind.isMergeableConst4())
  499. return FourByteConstantSection;
  500. if (Kind.isMergeableConst8())
  501. return EightByteConstantSection;
  502. if (Kind.isMergeableConst16() && SixteenByteConstantSection)
  503. return SixteenByteConstantSection;
  504. return ReadOnlySection; // .const
  505. }
  506. /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
  507. /// not to emit the UsedDirective for some symbols in llvm.used.
  508. // FIXME: REMOVE this (rdar://7071300)
  509. bool TargetLoweringObjectFileMachO::
  510. shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
  511. /// On Darwin, internally linked data beginning with "L" or "l" does not have
  512. /// the directive emitted (this occurs in ObjC metadata).
  513. if (!GV) return false;
  514. // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
  515. if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
  516. // FIXME: ObjC metadata is currently emitted as internal symbols that have
  517. // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
  518. // this horrible hack can go away.
  519. MCSymbol *Sym = Mang->getSymbol(GV);
  520. if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
  521. return false;
  522. }
  523. return true;
  524. }
  525. const MCExpr *TargetLoweringObjectFileMachO::
  526. getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang,
  527. MachineModuleInfo *MMI, unsigned Encoding,
  528. MCStreamer &Streamer) const {
  529. // The mach-o version of this method defaults to returning a stub reference.
  530. if (Encoding & DW_EH_PE_indirect) {
  531. MachineModuleInfoMachO &MachOMMI =
  532. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  533. SmallString<128> Name;
  534. Mang->getNameWithPrefix(Name, GV, true);
  535. Name += "$non_lazy_ptr";
  536. // Add information about the stub reference to MachOMMI so that the stub
  537. // gets emitted by the asmprinter.
  538. MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
  539. MachineModuleInfoImpl::StubValueTy &StubSym =
  540. GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
  541. MachOMMI.getGVStubEntry(SSym);
  542. if (StubSym.getPointer() == 0) {
  543. MCSymbol *Sym = Mang->getSymbol(GV);
  544. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  545. }
  546. return TargetLoweringObjectFile::
  547. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  548. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  549. }
  550. return TargetLoweringObjectFile::
  551. getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
  552. }
  553. MCSymbol *TargetLoweringObjectFileMachO::
  554. getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
  555. MachineModuleInfo *MMI) const {
  556. // The mach-o version of this method defaults to returning a stub reference.
  557. MachineModuleInfoMachO &MachOMMI =
  558. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  559. SmallString<128> Name;
  560. Mang->getNameWithPrefix(Name, GV, true);
  561. Name += "$non_lazy_ptr";
  562. // Add information about the stub reference to MachOMMI so that the stub
  563. // gets emitted by the asmprinter.
  564. MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
  565. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  566. if (StubSym.getPointer() == 0) {
  567. MCSymbol *Sym = Mang->getSymbol(GV);
  568. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  569. }
  570. return SSym;
  571. }
  572. //===----------------------------------------------------------------------===//
  573. // COFF
  574. //===----------------------------------------------------------------------===//
  575. static unsigned
  576. getCOFFSectionFlags(SectionKind K) {
  577. unsigned Flags = 0;
  578. if (K.isMetadata())
  579. Flags |=
  580. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  581. else if (K.isText())
  582. Flags |=
  583. COFF::IMAGE_SCN_MEM_EXECUTE |
  584. COFF::IMAGE_SCN_MEM_READ |
  585. COFF::IMAGE_SCN_CNT_CODE;
  586. else if (K.isBSS ())
  587. Flags |=
  588. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  589. COFF::IMAGE_SCN_MEM_READ |
  590. COFF::IMAGE_SCN_MEM_WRITE;
  591. else if (K.isThreadLocal())
  592. Flags |=
  593. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  594. COFF::IMAGE_SCN_MEM_READ |
  595. COFF::IMAGE_SCN_MEM_WRITE;
  596. else if (K.isReadOnly())
  597. Flags |=
  598. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  599. COFF::IMAGE_SCN_MEM_READ;
  600. else if (K.isWriteable())
  601. Flags |=
  602. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  603. COFF::IMAGE_SCN_MEM_READ |
  604. COFF::IMAGE_SCN_MEM_WRITE;
  605. return Flags;
  606. }
  607. const MCSection *TargetLoweringObjectFileCOFF::
  608. getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
  609. Mangler *Mang, const TargetMachine &TM) const {
  610. int Selection = 0;
  611. unsigned Characteristics = getCOFFSectionFlags(Kind);
  612. SmallString<128> Name(GV->getSection().c_str());
  613. if (GV->isWeakForLinker()) {
  614. Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
  615. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  616. MCSymbol *Sym = Mang->getSymbol(GV);
  617. Name.append("$");
  618. Name.append(Sym->getName().begin() + 1, Sym->getName().end());
  619. }
  620. return getContext().getCOFFSection(Name,
  621. Characteristics,
  622. Selection,
  623. Kind);
  624. }
  625. static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
  626. if (Kind.isText())
  627. return ".text$";
  628. if (Kind.isBSS ())
  629. return ".bss$";
  630. if (Kind.isThreadLocal())
  631. return ".tls$";
  632. if (Kind.isWriteable())
  633. return ".data$";
  634. return ".rdata$";
  635. }
  636. const MCSection *TargetLoweringObjectFileCOFF::
  637. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  638. Mangler *Mang, const TargetMachine &TM) const {
  639. // If this global is linkonce/weak and the target handles this by emitting it
  640. // into a 'uniqued' section name, create and return the section now.
  641. if (GV->isWeakForLinker()) {
  642. const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
  643. SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
  644. MCSymbol *Sym = Mang->getSymbol(GV);
  645. Name.append(Sym->getName().begin() + 1, Sym->getName().end());
  646. unsigned Characteristics = getCOFFSectionFlags(Kind);
  647. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  648. return getContext().getCOFFSection(Name.str(), Characteristics,
  649. COFF::IMAGE_COMDAT_SELECT_ANY, Kind);
  650. }
  651. if (Kind.isText())
  652. return getTextSection();
  653. if (Kind.isThreadLocal())
  654. return getTLSDataSection();
  655. return getDataSection();
  656. }