TargetLoweringObjectFile.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/GlobalVariable.h"
  20. #include "llvm/IR/Mangler.h"
  21. #include "llvm/MC/MCAsmInfo.h"
  22. #include "llvm/MC/MCContext.h"
  23. #include "llvm/MC/MCExpr.h"
  24. #include "llvm/MC/MCStreamer.h"
  25. #include "llvm/MC/MCSymbol.h"
  26. #include "llvm/Support/Dwarf.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetLowering.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetOptions.h"
  32. #include "llvm/Target/TargetSubtargetInfo.h"
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Generic Code
  36. //===----------------------------------------------------------------------===//
  37. /// Initialize - this method must be called before any actual lowering is
  38. /// done. This specifies the current context for codegen, and gives the
  39. /// lowering implementations a chance to set up their default sections.
  40. void TargetLoweringObjectFile::Initialize(MCContext &ctx,
  41. const TargetMachine &TM) {
  42. Ctx = &ctx;
  43. DL = TM.getDataLayout();
  44. InitMCObjectFileInfo(TM.getTargetTriple(), TM.getRelocationModel(),
  45. TM.getCodeModel(), *Ctx);
  46. }
  47. TargetLoweringObjectFile::~TargetLoweringObjectFile() {
  48. }
  49. static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
  50. const Constant *C = GV->getInitializer();
  51. // Must have zero initializer.
  52. if (!C->isNullValue())
  53. return false;
  54. // Leave constant zeros in readonly constant sections, so they can be shared.
  55. if (GV->isConstant())
  56. return false;
  57. // If the global has an explicit section specified, don't put it in BSS.
  58. if (GV->hasSection())
  59. return false;
  60. // If -nozero-initialized-in-bss is specified, don't ever use BSS.
  61. if (NoZerosInBSS)
  62. return false;
  63. // Otherwise, put it in BSS!
  64. return true;
  65. }
  66. /// IsNullTerminatedString - Return true if the specified constant (which is
  67. /// known to have a type that is an array of 1/2/4 byte elements) ends with a
  68. /// nul value and contains no other nuls in it. Note that this is more general
  69. /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
  70. static bool IsNullTerminatedString(const Constant *C) {
  71. // First check: is we have constant array terminated with zero
  72. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
  73. unsigned NumElts = CDS->getNumElements();
  74. assert(NumElts != 0 && "Can't have an empty CDS");
  75. if (CDS->getElementAsInteger(NumElts-1) != 0)
  76. return false; // Not null terminated.
  77. // Verify that the null doesn't occur anywhere else in the string.
  78. for (unsigned i = 0; i != NumElts-1; ++i)
  79. if (CDS->getElementAsInteger(i) == 0)
  80. return false;
  81. return true;
  82. }
  83. // Another possibility: [1 x i8] zeroinitializer
  84. if (isa<ConstantAggregateZero>(C))
  85. return cast<ArrayType>(C->getType())->getNumElements() == 1;
  86. return false;
  87. }
  88. MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
  89. const GlobalValue *GV, StringRef Suffix, Mangler &Mang,
  90. const TargetMachine &TM) const {
  91. assert(!Suffix.empty());
  92. SmallString<60> NameStr;
  93. NameStr += DL->getPrivateGlobalPrefix();
  94. TM.getNameWithPrefix(NameStr, GV, Mang);
  95. NameStr.append(Suffix.begin(), Suffix.end());
  96. return Ctx->getOrCreateSymbol(NameStr);
  97. }
  98. MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
  99. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  100. MachineModuleInfo *MMI) const {
  101. return TM.getSymbol(GV, Mang);
  102. }
  103. void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
  104. const TargetMachine &TM,
  105. const MCSymbol *Sym) const {
  106. }
  107. /// getKindForGlobal - This is a top-level target-independent classifier for
  108. /// a global variable. Given an global variable and information from TM, it
  109. /// classifies the global in a variety of ways that make various target
  110. /// implementations simpler. The target implementation is free to ignore this
  111. /// extra info of course.
  112. SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
  113. const TargetMachine &TM){
  114. assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
  115. "Can only be used for global definitions");
  116. Reloc::Model ReloModel = TM.getRelocationModel();
  117. // Early exit - functions should be always in text sections.
  118. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
  119. if (!GVar)
  120. return SectionKind::getText();
  121. // Handle thread-local data first.
  122. if (GVar->isThreadLocal()) {
  123. if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
  124. return SectionKind::getThreadBSS();
  125. return SectionKind::getThreadData();
  126. }
  127. // Variables with common linkage always get classified as common.
  128. if (GVar->hasCommonLinkage())
  129. return SectionKind::getCommon();
  130. // Variable can be easily put to BSS section.
  131. if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
  132. if (GVar->hasLocalLinkage())
  133. return SectionKind::getBSSLocal();
  134. else if (GVar->hasExternalLinkage())
  135. return SectionKind::getBSSExtern();
  136. return SectionKind::getBSS();
  137. }
  138. const Constant *C = GVar->getInitializer();
  139. // If the global is marked constant, we can put it into a mergable section,
  140. // a mergable string section, or general .data if it contains relocations.
  141. if (GVar->isConstant()) {
  142. // If the initializer for the global contains something that requires a
  143. // relocation, then we may have to drop this into a writable data section
  144. // even though it is marked const.
  145. switch (C->getRelocationInfo()) {
  146. case Constant::NoRelocation:
  147. // If the global is required to have a unique address, it can't be put
  148. // into a mergable section: just drop it into the general read-only
  149. // section instead.
  150. if (!GVar->hasUnnamedAddr())
  151. return SectionKind::getReadOnly();
  152. // If initializer is a null-terminated string, put it in a "cstring"
  153. // section of the right width.
  154. if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
  155. if (IntegerType *ITy =
  156. dyn_cast<IntegerType>(ATy->getElementType())) {
  157. if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
  158. ITy->getBitWidth() == 32) &&
  159. IsNullTerminatedString(C)) {
  160. if (ITy->getBitWidth() == 8)
  161. return SectionKind::getMergeable1ByteCString();
  162. if (ITy->getBitWidth() == 16)
  163. return SectionKind::getMergeable2ByteCString();
  164. assert(ITy->getBitWidth() == 32 && "Unknown width");
  165. return SectionKind::getMergeable4ByteCString();
  166. }
  167. }
  168. }
  169. // Otherwise, just drop it into a mergable constant section. If we have
  170. // a section for this size, use it, otherwise use the arbitrary sized
  171. // mergable section.
  172. switch (TM.getDataLayout()->getTypeAllocSize(C->getType())) {
  173. case 4: return SectionKind::getMergeableConst4();
  174. case 8: return SectionKind::getMergeableConst8();
  175. case 16: return SectionKind::getMergeableConst16();
  176. default:
  177. return SectionKind::getReadOnly();
  178. }
  179. case Constant::LocalRelocation:
  180. // In static relocation model, the linker will resolve all addresses, so
  181. // the relocation entries will actually be constants by the time the app
  182. // starts up. However, we can't put this into a mergable section, because
  183. // the linker doesn't take relocations into consideration when it tries to
  184. // merge entries in the section.
  185. if (ReloModel == Reloc::Static)
  186. return SectionKind::getReadOnly();
  187. // Otherwise, the dynamic linker needs to fix it up, put it in the
  188. // writable data.rel.local section.
  189. return SectionKind::getReadOnlyWithRelLocal();
  190. case Constant::GlobalRelocations:
  191. // In static relocation model, the linker will resolve all addresses, so
  192. // the relocation entries will actually be constants by the time the app
  193. // starts up. However, we can't put this into a mergable section, because
  194. // the linker doesn't take relocations into consideration when it tries to
  195. // merge entries in the section.
  196. if (ReloModel == Reloc::Static)
  197. return SectionKind::getReadOnly();
  198. // Otherwise, the dynamic linker needs to fix it up, put it in the
  199. // writable data.rel section.
  200. return SectionKind::getReadOnlyWithRel();
  201. }
  202. }
  203. // Okay, this isn't a constant. If the initializer for the global is going
  204. // to require a runtime relocation by the dynamic linker, put it into a more
  205. // specific section to improve startup time of the app. This coalesces these
  206. // globals together onto fewer pages, improving the locality of the dynamic
  207. // linker.
  208. if (ReloModel == Reloc::Static)
  209. return SectionKind::getDataNoRel();
  210. switch (C->getRelocationInfo()) {
  211. case Constant::NoRelocation:
  212. return SectionKind::getDataNoRel();
  213. case Constant::LocalRelocation:
  214. return SectionKind::getDataRelLocal();
  215. case Constant::GlobalRelocations:
  216. return SectionKind::getDataRel();
  217. }
  218. llvm_unreachable("Invalid relocation");
  219. }
  220. /// This method computes the appropriate section to emit the specified global
  221. /// variable or function definition. This should not be passed external (or
  222. /// available externally) globals.
  223. MCSection *
  224. TargetLoweringObjectFile::SectionForGlobal(const GlobalValue *GV,
  225. SectionKind Kind, Mangler &Mang,
  226. const TargetMachine &TM) const {
  227. // Select section name.
  228. if (GV->hasSection())
  229. return getExplicitSectionGlobal(GV, Kind, Mang, TM);
  230. // Use default section depending on the 'type' of global
  231. return SelectSectionForGlobal(GV, Kind, Mang, TM);
  232. }
  233. MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
  234. const Function &F, Mangler &Mang, const TargetMachine &TM) const {
  235. return getSectionForConstant(SectionKind::getReadOnly(), /*C=*/nullptr);
  236. }
  237. bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
  238. bool UsesLabelDifference, const Function &F) const {
  239. // In PIC mode, we need to emit the jump table to the same section as the
  240. // function body itself, otherwise the label differences won't make sense.
  241. // FIXME: Need a better predicate for this: what about custom entries?
  242. if (UsesLabelDifference)
  243. return true;
  244. // We should also do if the section name is NULL or function is declared
  245. // in discardable section
  246. // FIXME: this isn't the right predicate, should be based on the MCSection
  247. // for the function.
  248. if (F.isWeakForLinker())
  249. return true;
  250. return false;
  251. }
  252. /// Given a mergable constant with the specified size and relocation
  253. /// information, return a section that it should be placed in.
  254. MCSection *
  255. TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind,
  256. const Constant *C) const {
  257. if (Kind.isReadOnly() && ReadOnlySection != nullptr)
  258. return ReadOnlySection;
  259. return DataSection;
  260. }
  261. /// getTTypeGlobalReference - Return an MCExpr to use for a
  262. /// reference to the specified global variable from exception
  263. /// handling information.
  264. const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
  265. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  266. const TargetMachine &TM, MachineModuleInfo *MMI,
  267. MCStreamer &Streamer) const {
  268. const MCSymbolRefExpr *Ref =
  269. MCSymbolRefExpr::create(TM.getSymbol(GV, Mang), getContext());
  270. return getTTypeReference(Ref, Encoding, Streamer);
  271. }
  272. const MCExpr *TargetLoweringObjectFile::
  273. getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
  274. MCStreamer &Streamer) const {
  275. switch (Encoding & 0x70) {
  276. default:
  277. report_fatal_error("We do not support this DWARF encoding yet!");
  278. case dwarf::DW_EH_PE_absptr:
  279. // Do nothing special
  280. return Sym;
  281. case dwarf::DW_EH_PE_pcrel: {
  282. // Emit a label to the streamer for the current position. This gives us
  283. // .-foo addressing.
  284. MCSymbol *PCSym = getContext().createTempSymbol();
  285. Streamer.EmitLabel(PCSym);
  286. const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
  287. return MCBinaryExpr::createSub(Sym, PC, getContext());
  288. }
  289. }
  290. }
  291. const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
  292. // FIXME: It's not clear what, if any, default this should have - perhaps a
  293. // null return could mean 'no location' & we should just do that here.
  294. return MCSymbolRefExpr::create(Sym, *Ctx);
  295. }
  296. void TargetLoweringObjectFile::getNameWithPrefix(
  297. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  298. bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
  299. Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  300. }