LLVM  9.0.0svn
TargetLoweringObjectFile.cpp
Go to the documentation of this file.
1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSymbol.h"
30 using namespace llvm;
31 
32 //===----------------------------------------------------------------------===//
33 // Generic Code
34 //===----------------------------------------------------------------------===//
35 
36 /// Initialize - this method must be called before any actual lowering is
37 /// done. This specifies the current context for codegen, and gives the
38 /// lowering implementations a chance to set up their default sections.
40  const TargetMachine &TM) {
41  Ctx = &ctx;
42  // `Initialize` can be called more than once.
43  delete Mang;
44  Mang = new Mangler();
47 
48  // Reset various EH DWARF encodings.
50 }
51 
53  delete Mang;
54 }
55 
56 static bool isNullOrUndef(const Constant *C) {
57  // Check that the constant isn't all zeros or undefs.
58  if (C->isNullValue() || isa<UndefValue>(C))
59  return true;
60  if (!isa<ConstantAggregate>(C))
61  return false;
62  for (auto Operand : C->operand_values()) {
63  if (!isNullOrUndef(cast<Constant>(Operand)))
64  return false;
65  }
66  return true;
67 }
68 
69 static bool isSuitableForBSS(const GlobalVariable *GV) {
70  const Constant *C = GV->getInitializer();
71 
72  // Must have zero initializer.
73  if (!isNullOrUndef(C))
74  return false;
75 
76  // Leave constant zeros in readonly constant sections, so they can be shared.
77  if (GV->isConstant())
78  return false;
79 
80  // If the global has an explicit section specified, don't put it in BSS.
81  if (GV->hasSection())
82  return false;
83 
84  // Otherwise, put it in BSS!
85  return true;
86 }
87 
88 /// IsNullTerminatedString - Return true if the specified constant (which is
89 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
90 /// nul value and contains no other nuls in it. Note that this is more general
91 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
92 static bool IsNullTerminatedString(const Constant *C) {
93  // First check: is we have constant array terminated with zero
94  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
95  unsigned NumElts = CDS->getNumElements();
96  assert(NumElts != 0 && "Can't have an empty CDS");
97 
98  if (CDS->getElementAsInteger(NumElts-1) != 0)
99  return false; // Not null terminated.
100 
101  // Verify that the null doesn't occur anywhere else in the string.
102  for (unsigned i = 0; i != NumElts-1; ++i)
103  if (CDS->getElementAsInteger(i) == 0)
104  return false;
105  return true;
106  }
107 
108  // Another possibility: [1 x i8] zeroinitializer
109  if (isa<ConstantAggregateZero>(C))
110  return cast<ArrayType>(C->getType())->getNumElements() == 1;
111 
112  return false;
113 }
114 
116  const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
117  assert(!Suffix.empty());
118 
119  SmallString<60> NameStr;
120  NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
121  TM.getNameWithPrefix(NameStr, GV, *Mang);
122  NameStr.append(Suffix.begin(), Suffix.end());
123  return Ctx->getOrCreateSymbol(NameStr);
124 }
125 
127  const GlobalValue *GV, const TargetMachine &TM,
128  MachineModuleInfo *MMI) const {
129  return TM.getSymbol(GV);
130 }
131 
133  const DataLayout &,
134  const MCSymbol *Sym) const {
135 }
136 
137 
138 /// getKindForGlobal - This is a top-level target-independent classifier for
139 /// a global object. Given a global variable and information from the TM, this
140 /// function classifies the global in a target independent manner. This function
141 /// may be overridden by the target implementation.
143  const TargetMachine &TM){
145  "Can only be used for global definitions");
146 
147  // Functions are classified as text sections.
148  if (isa<Function>(GO))
149  return SectionKind::getText();
150 
151  // Global variables require more detailed analysis.
152  const auto *GVar = cast<GlobalVariable>(GO);
153 
154  // Handle thread-local data first.
155  if (GVar->isThreadLocal()) {
156  if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
157  return SectionKind::getThreadBSS();
159  }
160 
161  // Variables with common linkage always get classified as common.
162  if (GVar->hasCommonLinkage())
163  return SectionKind::getCommon();
164 
165  // Most non-mergeable zero data can be put in the BSS section unless otherwise
166  // specified.
167  if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
168  if (GVar->hasLocalLinkage())
169  return SectionKind::getBSSLocal();
170  else if (GVar->hasExternalLinkage())
171  return SectionKind::getBSSExtern();
172  return SectionKind::getBSS();
173  }
174 
175  // If the global is marked constant, we can put it into a mergable section,
176  // a mergable string section, or general .data if it contains relocations.
177  if (GVar->isConstant()) {
178  // If the initializer for the global contains something that requires a
179  // relocation, then we may have to drop this into a writable data section
180  // even though it is marked const.
181  const Constant *C = GVar->getInitializer();
182  if (!C->needsRelocation()) {
183  // If the global is required to have a unique address, it can't be put
184  // into a mergable section: just drop it into the general read-only
185  // section instead.
186  if (!GVar->hasGlobalUnnamedAddr())
187  return SectionKind::getReadOnly();
188 
189  // If initializer is a null-terminated string, put it in a "cstring"
190  // section of the right width.
191  if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
192  if (IntegerType *ITy =
193  dyn_cast<IntegerType>(ATy->getElementType())) {
194  if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
195  ITy->getBitWidth() == 32) &&
197  if (ITy->getBitWidth() == 8)
199  if (ITy->getBitWidth() == 16)
201 
202  assert(ITy->getBitWidth() == 32 && "Unknown width");
204  }
205  }
206  }
207 
208  // Otherwise, just drop it into a mergable constant section. If we have
209  // a section for this size, use it, otherwise use the arbitrary sized
210  // mergable section.
211  switch (
212  GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
213  case 4: return SectionKind::getMergeableConst4();
214  case 8: return SectionKind::getMergeableConst8();
215  case 16: return SectionKind::getMergeableConst16();
216  case 32: return SectionKind::getMergeableConst32();
217  default:
218  return SectionKind::getReadOnly();
219  }
220 
221  } else {
222  // In static, ROPI and RWPI relocation models, the linker will resolve
223  // all addresses, so the relocation entries will actually be constants by
224  // the time the app starts up. However, we can't put this into a
225  // mergable section, because the linker doesn't take relocations into
226  // consideration when it tries to merge entries in the section.
227  Reloc::Model ReloModel = TM.getRelocationModel();
228  if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
229  ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
230  return SectionKind::getReadOnly();
231 
232  // Otherwise, the dynamic linker needs to fix it up, put it in the
233  // writable data.rel section.
235  }
236  }
237 
238  // Okay, this isn't a constant.
239  return SectionKind::getData();
240 }
241 
242 /// This method computes the appropriate section to emit the specified global
243 /// variable or function definition. This should not be passed external (or
244 /// available externally) globals.
246  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
247  // Select section name.
248  if (GO->hasSection())
249  return getExplicitSectionGlobal(GO, Kind, TM);
250 
251  if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
252  auto Attrs = GVar->getAttributes();
253  if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
254  (Attrs.hasAttribute("data-section") && Kind.isData()) ||
255  (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) {
256  return getExplicitSectionGlobal(GO, Kind, TM);
257  }
258  }
259 
260  if (auto *F = dyn_cast<Function>(GO)) {
261  if (F->hasFnAttribute("implicit-section-name"))
262  return getExplicitSectionGlobal(GO, Kind, TM);
263  }
264 
265  // Use default section depending on the 'type' of global
266  return SelectSectionForGlobal(GO, Kind, TM);
267 }
268 
270  const Function &F, const TargetMachine &TM) const {
271  unsigned Align = 0;
273  SectionKind::getReadOnly(), /*C=*/nullptr,
274  Align);
275 }
276 
278  bool UsesLabelDifference, const Function &F) const {
279  // In PIC mode, we need to emit the jump table to the same section as the
280  // function body itself, otherwise the label differences won't make sense.
281  // FIXME: Need a better predicate for this: what about custom entries?
282  if (UsesLabelDifference)
283  return true;
284 
285  // We should also do if the section name is NULL or function is declared
286  // in discardable section
287  // FIXME: this isn't the right predicate, should be based on the MCSection
288  // for the function.
289  return F.isWeakForLinker();
290 }
291 
292 /// Given a mergable constant with the specified size and relocation
293 /// information, return a section that it should be placed in.
295  const DataLayout &DL, SectionKind Kind, const Constant *C,
296  unsigned &Align) const {
297  if (Kind.isReadOnly() && ReadOnlySection != nullptr)
298  return ReadOnlySection;
299 
300  return DataSection;
301 }
302 
303 /// getTTypeGlobalReference - Return an MCExpr to use for a
304 /// reference to the specified global variable from exception
305 /// handling information.
307  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
308  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
309  const MCSymbolRefExpr *Ref =
311 
312  return getTTypeReference(Ref, Encoding, Streamer);
313 }
314 
316 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
317  MCStreamer &Streamer) const {
318  switch (Encoding & 0x70) {
319  default:
320  report_fatal_error("We do not support this DWARF encoding yet!");
322  // Do nothing special
323  return Sym;
324  case dwarf::DW_EH_PE_pcrel: {
325  // Emit a label to the streamer for the current position. This gives us
326  // .-foo addressing.
327  MCSymbol *PCSym = getContext().createTempSymbol();
328  Streamer.EmitLabel(PCSym);
329  const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
330  return MCBinaryExpr::createSub(Sym, PC, getContext());
331  }
332  }
333 }
334 
336  // FIXME: It's not clear what, if any, default this should have - perhaps a
337  // null return could mean 'no location' & we should just do that here.
338  return MCSymbolRefExpr::create(Sym, *Ctx);
339 }
340 
342  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
343  const TargetMachine &TM) const {
344  Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
345 }
uint64_t CallInst * C
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static SectionKind getData()
Definition: SectionKind.h:201
static bool isNullOrUndef(const Constant *C)
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:323
static SectionKind getMergeableConst32()
Definition: SectionKind.h:194
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym) const
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:316
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry...
Definition: Constants.cpp:498
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:432
static SectionKind getMergeableConst8()
Definition: SectionKind.h:192
static SectionKind getMergeableConst16()
Definition: SectionKind.h:193
static SectionKind getMergeable1ByteCString()
Definition: SectionKind.h:182
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
static SectionKind getCommon()
Definition: SectionKind.h:200
F(f)
static SectionKind getMergeableConst4()
Definition: SectionKind.h:191
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
static SectionKind getBSS()
Definition: SectionKind.h:197
static SectionKind getMergeable4ByteCString()
Definition: SectionKind.h:188
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
The access may reference the value stored in memory.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:165
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
Context object for machine code objects.
Definition: MCContext.h:62
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:546
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:573
Class to represent array types.
Definition: DerivedTypes.h:403
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
static SectionKind getThreadData()
Definition: SectionKind.h:196
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
MCSection * DataSection
Section directive for standard data.
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:379
static SectionKind getBSSLocal()
Definition: SectionKind.h:198
Streaming machine code generation interface.
Definition: MCStreamer.h:188
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:220
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getSymbol(const GlobalValue *GV) const
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
const Triple & getTargetTriple() const
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
Class to represent integer types.
Definition: DerivedTypes.h:40
unsigned NoZerosInBSS
NoZerosInBSS - By default some codegens place zero-initialized data to .bss section.
bool isBSS() const
Definition: SectionKind.h:159
static SectionKind getThreadBSS()
Definition: SectionKind.h:195
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:81
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:202
static bool isSuitableForBSS(const GlobalVariable *GV)
This file contains constants used for implementing Dwarf debug support.
CodeModel::Model getCodeModel() const
Returns the code model.
iterator begin() const
Definition: StringRef.h:101
static bool IsNullTerminatedString(const Constant *C)
IsNullTerminatedString - Return true if the specified constant (which is known to have a type that is...
bool isReadOnly() const
Definition: SectionKind.h:122
static SectionKind getMergeable2ByteCString()
Definition: SectionKind.h:185
void InitMCObjectFileInfo(const Triple &TT, bool PIC, MCContext &ctx, bool LargeCodeModel=false)
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:124
bool isPositionIndependent() const
TargetOptions Options
iterator_range< value_op_iterator > operand_values()
Definition: User.h:261
static SectionKind getBSSExtern()
Definition: SectionKind.h:199
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
virtual MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
Targets should implement this method to assign a section to globals with an explicit section specfied...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:227
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
bool isData() const
Definition: SectionKind.h:165
virtual MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:351
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const
virtual const MCExpr * getDebugThreadLocalSymbol(const MCSymbol *Sym) const
Create a symbol reference to describe the given TLS variable when emitting the address in debug info...
iterator end() const
Definition: StringRef.h:103
static SectionKind getReadOnly()
Definition: SectionKind.h:181
This class contains meta information specific to a module.
static SectionKind getText()
Definition: SectionKind.h:179