1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Target/TargetLoweringObjectFile.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Mangler.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 /// Initialize - this method must be called before any actual lowering is
41 /// done. This specifies the current context for codegen, and gives the
42 /// lowering implementations a chance to set up their default sections.
43 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
44 const TargetMachine &TM) {
46 // `Initialize` can be called more than once.
47 if (Mang != nullptr) delete Mang;
49 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(),
50 TM.getCodeModel(), *Ctx);
53 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
57 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
58 const Constant *C = GV->getInitializer();
60 // Must have zero initializer.
61 if (!C->isNullValue())
64 // Leave constant zeros in readonly constant sections, so they can be shared.
68 // If the global has an explicit section specified, don't put it in BSS.
72 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
76 // Otherwise, put it in BSS!
80 /// IsNullTerminatedString - Return true if the specified constant (which is
81 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
82 /// nul value and contains no other nuls in it. Note that this is more general
83 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
84 static bool IsNullTerminatedString(const Constant *C) {
85 // First check: is we have constant array terminated with zero
86 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
87 unsigned NumElts = CDS->getNumElements();
88 assert(NumElts != 0 && "Can't have an empty CDS");
90 if (CDS->getElementAsInteger(NumElts-1) != 0)
91 return false; // Not null terminated.
93 // Verify that the null doesn't occur anywhere else in the string.
94 for (unsigned i = 0; i != NumElts-1; ++i)
95 if (CDS->getElementAsInteger(i) == 0)
100 // Another possibility: [1 x i8] zeroinitializer
101 if (isa<ConstantAggregateZero>(C))
102 return cast<ArrayType>(C->getType())->getNumElements() == 1;
107 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
108 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
109 assert(!Suffix.empty());
111 SmallString<60> NameStr;
112 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
113 TM.getNameWithPrefix(NameStr, GV, *Mang);
114 NameStr.append(Suffix.begin(), Suffix.end());
115 return Ctx->getOrCreateSymbol(NameStr);
118 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
119 const GlobalValue *GV, const TargetMachine &TM,
120 MachineModuleInfo *MMI) const {
121 return TM.getSymbol(GV);
124 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
126 const MCSymbol *Sym) const {
130 /// getKindForGlobal - This is a top-level target-independent classifier for
131 /// a global variable. Given an global variable and information from TM, it
132 /// classifies the global in a variety of ways that make various target
133 /// implementations simpler. The target implementation is free to ignore this
134 /// extra info of course.
135 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
136 const TargetMachine &TM){
137 assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
138 "Can only be used for global definitions");
140 Reloc::Model ReloModel = TM.getRelocationModel();
142 // Early exit - functions should be always in text sections.
143 const auto *GVar = dyn_cast<GlobalVariable>(GO);
145 return SectionKind::getText();
147 // Handle thread-local data first.
148 if (GVar->isThreadLocal()) {
149 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
150 return SectionKind::getThreadBSS();
151 return SectionKind::getThreadData();
154 // Variables with common linkage always get classified as common.
155 if (GVar->hasCommonLinkage())
156 return SectionKind::getCommon();
158 // Variable can be easily put to BSS section.
159 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
160 if (GVar->hasLocalLinkage())
161 return SectionKind::getBSSLocal();
162 else if (GVar->hasExternalLinkage())
163 return SectionKind::getBSSExtern();
164 return SectionKind::getBSS();
167 const Constant *C = GVar->getInitializer();
169 // If the global is marked constant, we can put it into a mergable section,
170 // a mergable string section, or general .data if it contains relocations.
171 if (GVar->isConstant()) {
172 // If the initializer for the global contains something that requires a
173 // relocation, then we may have to drop this into a writable data section
174 // even though it is marked const.
175 if (!C->needsRelocation()) {
176 // If the global is required to have a unique address, it can't be put
177 // into a mergable section: just drop it into the general read-only
179 if (!GVar->hasGlobalUnnamedAddr())
180 return SectionKind::getReadOnly();
182 // If initializer is a null-terminated string, put it in a "cstring"
183 // section of the right width.
184 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
185 if (IntegerType *ITy =
186 dyn_cast<IntegerType>(ATy->getElementType())) {
187 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
188 ITy->getBitWidth() == 32) &&
189 IsNullTerminatedString(C)) {
190 if (ITy->getBitWidth() == 8)
191 return SectionKind::getMergeable1ByteCString();
192 if (ITy->getBitWidth() == 16)
193 return SectionKind::getMergeable2ByteCString();
195 assert(ITy->getBitWidth() == 32 && "Unknown width");
196 return SectionKind::getMergeable4ByteCString();
201 // Otherwise, just drop it into a mergable constant section. If we have
202 // a section for this size, use it, otherwise use the arbitrary sized
205 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
206 case 4: return SectionKind::getMergeableConst4();
207 case 8: return SectionKind::getMergeableConst8();
208 case 16: return SectionKind::getMergeableConst16();
209 case 32: return SectionKind::getMergeableConst32();
211 return SectionKind::getReadOnly();
215 // In static, ROPI and RWPI relocation models, the linker will resolve
216 // all addresses, so the relocation entries will actually be constants by
217 // the time the app starts up. However, we can't put this into a
218 // mergable section, because the linker doesn't take relocations into
219 // consideration when it tries to merge entries in the section.
220 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
221 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
222 return SectionKind::getReadOnly();
224 // Otherwise, the dynamic linker needs to fix it up, put it in the
225 // writable data.rel section.
226 return SectionKind::getReadOnlyWithRel();
230 // Okay, this isn't a constant.
231 return SectionKind::getData();
234 /// This method computes the appropriate section to emit the specified global
235 /// variable or function definition. This should not be passed external (or
236 /// available externally) globals.
237 MCSection *TargetLoweringObjectFile::SectionForGlobal(
238 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
239 // Select section name.
240 if (GO->hasSection())
241 return getExplicitSectionGlobal(GO, Kind, TM);
243 // Use default section depending on the 'type' of global
244 return SelectSectionForGlobal(GO, Kind, TM);
247 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
248 const Function &F, const TargetMachine &TM) const {
250 return getSectionForConstant(F.getParent()->getDataLayout(),
251 SectionKind::getReadOnly(), /*C=*/nullptr,
255 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
256 bool UsesLabelDifference, const Function &F) const {
257 // In PIC mode, we need to emit the jump table to the same section as the
258 // function body itself, otherwise the label differences won't make sense.
259 // FIXME: Need a better predicate for this: what about custom entries?
260 if (UsesLabelDifference)
263 // We should also do if the section name is NULL or function is declared
264 // in discardable section
265 // FIXME: this isn't the right predicate, should be based on the MCSection
267 if (F.isWeakForLinker())
273 /// Given a mergable constant with the specified size and relocation
274 /// information, return a section that it should be placed in.
275 MCSection *TargetLoweringObjectFile::getSectionForConstant(
276 const DataLayout &DL, SectionKind Kind, const Constant *C,
277 unsigned &Align) const {
278 if (Kind.isReadOnly() && ReadOnlySection != nullptr)
279 return ReadOnlySection;
284 /// getTTypeGlobalReference - Return an MCExpr to use for a
285 /// reference to the specified global variable from exception
286 /// handling information.
287 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
288 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
289 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
290 const MCSymbolRefExpr *Ref =
291 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
293 return getTTypeReference(Ref, Encoding, Streamer);
296 const MCExpr *TargetLoweringObjectFile::
297 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
298 MCStreamer &Streamer) const {
299 switch (Encoding & 0x70) {
301 report_fatal_error("We do not support this DWARF encoding yet!");
302 case dwarf::DW_EH_PE_absptr:
303 // Do nothing special
305 case dwarf::DW_EH_PE_pcrel: {
306 // Emit a label to the streamer for the current position. This gives us
308 MCSymbol *PCSym = getContext().createTempSymbol();
309 Streamer.EmitLabel(PCSym);
310 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
311 return MCBinaryExpr::createSub(Sym, PC, getContext());
316 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
317 // FIXME: It's not clear what, if any, default this should have - perhaps a
318 // null return could mean 'no location' & we should just do that here.
319 return MCSymbolRefExpr::create(Sym, *Ctx);
322 void TargetLoweringObjectFile::getNameWithPrefix(
323 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
324 const TargetMachine &TM) const {
325 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);