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 
14 #include "llvm/Target/TargetLoweringObjectFile.h"
15 #include "llvm/BinaryFormat/Dwarf.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/IR/Module.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/MC/SectionKind.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 using namespace llvm;
33 
34 //===----------------------------------------------------------------------===//
35 //                              Generic Code
36 //===----------------------------------------------------------------------===//
37 
38 /// Initialize - this method must be called before any actual lowering is
39 /// done.  This specifies the current context for codegen, and gives the
40 /// lowering implementations a chance to set up their default sections.
41 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
42                                           const TargetMachine &TM) {
43   // `Initialize` can be called more than once.
44   delete Mang;
45   Mang = new Mangler();
46   InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), ctx,
47                        TM.getCodeModel() == CodeModel::Large);
48 
49   // Reset various EH DWARF encodings.
50   PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
51   CallSiteEncoding = dwarf::DW_EH_PE_uleb128;
52 }
53 
54 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
55   delete Mang;
56 }
57 
58 static bool isNullOrUndef(const Constant *C) {
59   // Check that the constant isn't all zeros or undefs.
60   if (C->isNullValue() || isa<UndefValue>(C))
61     return true;
62   if (!isa<ConstantAggregate>(C))
63     return false;
64   for (auto Operand : C->operand_values()) {
65     if (!isNullOrUndef(cast<Constant>(Operand)))
66       return false;
67   }
68   return true;
69 }
70 
71 static bool isSuitableForBSS(const GlobalVariable *GV) {
72   const Constant *C = GV->getInitializer();
73 
74   // Must have zero initializer.
75   if (!isNullOrUndef(C))
76     return false;
77 
78   // Leave constant zeros in readonly constant sections, so they can be shared.
79   if (GV->isConstant())
80     return false;
81 
82   // If the global has an explicit section specified, don't put it in BSS.
83   if (GV->hasSection())
84     return false;
85 
86   // Otherwise, put it in BSS!
87   return true;
88 }
89 
90 /// IsNullTerminatedString - Return true if the specified constant (which is
91 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
92 /// nul value and contains no other nuls in it.  Note that this is more general
93 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
94 static bool IsNullTerminatedString(const Constant *C) {
95   // First check: is we have constant array terminated with zero
96   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
97     unsigned NumElts = CDS->getNumElements();
98     assert(NumElts != 0 && "Can't have an empty CDS");
99 
100     if (CDS->getElementAsInteger(NumElts-1) != 0)
101       return false; // Not null terminated.
102 
103     // Verify that the null doesn't occur anywhere else in the string.
104     for (unsigned i = 0; i != NumElts-1; ++i)
105       if (CDS->getElementAsInteger(i) == 0)
106         return false;
107     return true;
108   }
109 
110   // Another possibility: [1 x i8] zeroinitializer
111   if (isa<ConstantAggregateZero>(C))
112     return cast<ArrayType>(C->getType())->getNumElements() == 1;
113 
114   return false;
115 }
116 
117 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
118     const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
119   assert(!Suffix.empty());
120 
121   SmallString<60> NameStr;
122   NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
123   TM.getNameWithPrefix(NameStr, GV, *Mang);
124   NameStr.append(Suffix.begin(), Suffix.end());
125   return getContext().getOrCreateSymbol(NameStr);
126 }
127 
128 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
129     const GlobalValue *GV, const TargetMachine &TM,
130     MachineModuleInfo *MMI) const {
131   return TM.getSymbol(GV);
132 }
133 
134 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
135                                                     const DataLayout &,
136                                                     const MCSymbol *Sym) const {
137 }
138 
139 
140 /// getKindForGlobal - This is a top-level target-independent classifier for
141 /// a global object.  Given a global variable and information from the TM, this
142 /// function classifies the global in a target independent manner. This function
143 /// may be overridden by the target implementation.
144 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
145                                                        const TargetMachine &TM){
146   assert(!GO->isDeclarationForLinker() &&
147          "Can only be used for global definitions");
148 
149   // Functions are classified as text sections.
150   if (isa<Function>(GO))
151     return SectionKind::getText();
152 
153   // Basic blocks are classified as text sections.
154   if (isa<BasicBlock>(GO))
155     return SectionKind::getText();
156 
157   // Global variables require more detailed analysis.
158   const auto *GVar = cast<GlobalVariable>(GO);
159 
160   // Handle thread-local data first.
161   if (GVar->isThreadLocal()) {
162     if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
163       return SectionKind::getThreadBSS();
164     return SectionKind::getThreadData();
165   }
166 
167   // Variables with common linkage always get classified as common.
168   if (GVar->hasCommonLinkage())
169     return SectionKind::getCommon();
170 
171   // Most non-mergeable zero data can be put in the BSS section unless otherwise
172   // specified.
173   if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
174     if (GVar->hasLocalLinkage())
175       return SectionKind::getBSSLocal();
176     else if (GVar->hasExternalLinkage())
177       return SectionKind::getBSSExtern();
178     return SectionKind::getBSS();
179   }
180 
181   // If the global is marked constant, we can put it into a mergable section,
182   // a mergable string section, or general .data if it contains relocations.
183   if (GVar->isConstant()) {
184     // If the initializer for the global contains something that requires a
185     // relocation, then we may have to drop this into a writable data section
186     // even though it is marked const.
187     const Constant *C = GVar->getInitializer();
188     if (!C->needsRelocation()) {
189       // If the global is required to have a unique address, it can't be put
190       // into a mergable section: just drop it into the general read-only
191       // section instead.
192       if (!GVar->hasGlobalUnnamedAddr())
193         return SectionKind::getReadOnly();
194 
195       // If initializer is a null-terminated string, put it in a "cstring"
196       // section of the right width.
197       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
198         if (IntegerType *ITy =
199               dyn_cast<IntegerType>(ATy->getElementType())) {
200           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
201                ITy->getBitWidth() == 32) &&
202               IsNullTerminatedString(C)) {
203             if (ITy->getBitWidth() == 8)
204               return SectionKind::getMergeable1ByteCString();
205             if (ITy->getBitWidth() == 16)
206               return SectionKind::getMergeable2ByteCString();
207 
208             assert(ITy->getBitWidth() == 32 && "Unknown width");
209             return SectionKind::getMergeable4ByteCString();
210           }
211         }
212       }
213 
214       // Otherwise, just drop it into a mergable constant section.  If we have
215       // a section for this size, use it, otherwise use the arbitrary sized
216       // mergable section.
217       switch (
218           GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
219       case 4:  return SectionKind::getMergeableConst4();
220       case 8:  return SectionKind::getMergeableConst8();
221       case 16: return SectionKind::getMergeableConst16();
222       case 32: return SectionKind::getMergeableConst32();
223       default:
224         return SectionKind::getReadOnly();
225       }
226 
227     } else {
228       // In static, ROPI and RWPI relocation models, the linker will resolve
229       // all addresses, so the relocation entries will actually be constants by
230       // the time the app starts up.  However, we can't put this into a
231       // mergable section, because the linker doesn't take relocations into
232       // consideration when it tries to merge entries in the section.
233       Reloc::Model ReloModel = TM.getRelocationModel();
234       if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
235           ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
236         return SectionKind::getReadOnly();
237 
238       // Otherwise, the dynamic linker needs to fix it up, put it in the
239       // writable data.rel section.
240       return SectionKind::getReadOnlyWithRel();
241     }
242   }
243 
244   // Okay, this isn't a constant.
245   return SectionKind::getData();
246 }
247 
248 /// This method computes the appropriate section to emit the specified global
249 /// variable or function definition.  This should not be passed external (or
250 /// available externally) globals.
251 MCSection *TargetLoweringObjectFile::SectionForGlobal(
252     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
253   // Select section name.
254   if (GO->hasSection())
255     return getExplicitSectionGlobal(GO, Kind, TM);
256 
257   if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
258     auto Attrs = GVar->getAttributes();
259     if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
260         (Attrs.hasAttribute("data-section") && Kind.isData()) ||
261         (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) ||
262         (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()))  {
263        return getExplicitSectionGlobal(GO, Kind, TM);
264     }
265   }
266 
267   if (auto *F = dyn_cast<Function>(GO)) {
268     if (F->hasFnAttribute("implicit-section-name"))
269       return getExplicitSectionGlobal(GO, Kind, TM);
270   }
271 
272   // Use default section depending on the 'type' of global
273   return SelectSectionForGlobal(GO, Kind, TM);
274 }
275 
276 /// This method computes the appropriate section to emit the specified global
277 /// variable or function definition. This should not be passed external (or
278 /// available externally) globals.
279 MCSection *
280 TargetLoweringObjectFile::SectionForGlobal(const GlobalObject *GO,
281                                            const TargetMachine &TM) const {
282   return SectionForGlobal(GO, getKindForGlobal(GO, TM), TM);
283 }
284 
285 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
286     const Function &F, const TargetMachine &TM) const {
287   Align Alignment(1);
288   return getSectionForConstant(F.getParent()->getDataLayout(),
289                                SectionKind::getReadOnly(), /*C=*/nullptr,
290                                Alignment);
291 }
292 
293 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
294     bool UsesLabelDifference, const Function &F) const {
295   // In PIC mode, we need to emit the jump table to the same section as the
296   // function body itself, otherwise the label differences won't make sense.
297   // FIXME: Need a better predicate for this: what about custom entries?
298   if (UsesLabelDifference)
299     return true;
300 
301   // We should also do if the section name is NULL or function is declared
302   // in discardable section
303   // FIXME: this isn't the right predicate, should be based on the MCSection
304   // for the function.
305   return F.isWeakForLinker();
306 }
307 
308 /// Given a mergable constant with the specified size and relocation
309 /// information, return a section that it should be placed in.
310 MCSection *TargetLoweringObjectFile::getSectionForConstant(
311     const DataLayout &DL, SectionKind Kind, const Constant *C,
312     Align &Alignment) const {
313   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
314     return ReadOnlySection;
315 
316   return DataSection;
317 }
318 
319 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock(
320     const Function &F, const MachineBasicBlock &MBB,
321     const TargetMachine &TM) const {
322   return nullptr;
323 }
324 
325 /// getTTypeGlobalReference - Return an MCExpr to use for a
326 /// reference to the specified global variable from exception
327 /// handling information.
328 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
329     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
330     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
331   const MCSymbolRefExpr *Ref =
332       MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
333 
334   return getTTypeReference(Ref, Encoding, Streamer);
335 }
336 
337 const MCExpr *TargetLoweringObjectFile::
338 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
339                   MCStreamer &Streamer) const {
340   switch (Encoding & 0x70) {
341   default:
342     report_fatal_error("We do not support this DWARF encoding yet!");
343   case dwarf::DW_EH_PE_absptr:
344     // Do nothing special
345     return Sym;
346   case dwarf::DW_EH_PE_pcrel: {
347     // Emit a label to the streamer for the current position.  This gives us
348     // .-foo addressing.
349     MCSymbol *PCSym = getContext().createTempSymbol();
350     Streamer.emitLabel(PCSym);
351     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
352     return MCBinaryExpr::createSub(Sym, PC, getContext());
353   }
354   }
355 }
356 
357 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
358   // FIXME: It's not clear what, if any, default this should have - perhaps a
359   // null return could mean 'no location' & we should just do that here.
360   return MCSymbolRefExpr::create(Sym, getContext());
361 }
362 
363 void TargetLoweringObjectFile::getNameWithPrefix(
364     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
365     const TargetMachine &TM) const {
366   Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
367 }
368