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 
15 #include "llvm/Target/TargetLoweringObjectFile.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Mangler.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/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 using namespace llvm;
32 
33 //===----------------------------------------------------------------------===//
34 //                              Generic Code
35 //===----------------------------------------------------------------------===//
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   // `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 
50 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
51   delete Mang;
52 }
53 
54 static bool isNullOrUndef(const Constant *C) {
55   // Check that the constant isn't all zeros or undefs.
56   if (C->isNullValue() || isa<UndefValue>(C))
57     return true;
58   if (!isa<ConstantAggregate>(C))
59     return false;
60   for (auto Operand : C->operand_values()) {
61     if (!isNullOrUndef(cast<Constant>(Operand)))
62       return false;
63   }
64   return true;
65 }
66 
67 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
68   const Constant *C = GV->getInitializer();
69 
70   // Must have zero initializer.
71   if (!isNullOrUndef(C))
72     return false;
73 
74   // Leave constant zeros in readonly constant sections, so they can be shared.
75   if (GV->isConstant())
76     return false;
77 
78   // If the global has an explicit section specified, don't put it in BSS.
79   if (GV->hasSection())
80     return false;
81 
82   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
83   if (NoZerosInBSS)
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 Ctx->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 variable.  Given an global variable and information from TM, it
142 /// classifies the global in a variety of ways that make various target
143 /// implementations simpler.  The target implementation is free to ignore this
144 /// extra info of course.
145 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
146                                                        const TargetMachine &TM){
147   assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
148          "Can only be used for global definitions");
149 
150   Reloc::Model ReloModel = TM.getRelocationModel();
151 
152   // Early exit - functions should be always in text sections.
153   const auto *GVar = dyn_cast<GlobalVariable>(GO);
154   if (!GVar)
155     return SectionKind::getText();
156 
157   // Handle thread-local data first.
158   if (GVar->isThreadLocal()) {
159     if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
160       return SectionKind::getThreadBSS();
161     return SectionKind::getThreadData();
162   }
163 
164   // Variables with common linkage always get classified as common.
165   if (GVar->hasCommonLinkage())
166     return SectionKind::getCommon();
167 
168   // Variable can be easily put to BSS section.
169   if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
170     if (GVar->hasLocalLinkage())
171       return SectionKind::getBSSLocal();
172     else if (GVar->hasExternalLinkage())
173       return SectionKind::getBSSExtern();
174     return SectionKind::getBSS();
175   }
176 
177   const Constant *C = GVar->getInitializer();
178 
179   // If the global is marked constant, we can put it into a mergable section,
180   // a mergable string section, or general .data if it contains relocations.
181   if (GVar->isConstant()) {
182     // If the initializer for the global contains something that requires a
183     // relocation, then we may have to drop this into a writable data section
184     // even though it is marked const.
185     if (!C->needsRelocation()) {
186       // If the global is required to have a unique address, it can't be put
187       // into a mergable section: just drop it into the general read-only
188       // section instead.
189       if (!GVar->hasGlobalUnnamedAddr())
190         return SectionKind::getReadOnly();
191 
192       // If initializer is a null-terminated string, put it in a "cstring"
193       // section of the right width.
194       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
195         if (IntegerType *ITy =
196               dyn_cast<IntegerType>(ATy->getElementType())) {
197           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
198                ITy->getBitWidth() == 32) &&
199               IsNullTerminatedString(C)) {
200             if (ITy->getBitWidth() == 8)
201               return SectionKind::getMergeable1ByteCString();
202             if (ITy->getBitWidth() == 16)
203               return SectionKind::getMergeable2ByteCString();
204 
205             assert(ITy->getBitWidth() == 32 && "Unknown width");
206             return SectionKind::getMergeable4ByteCString();
207           }
208         }
209       }
210 
211       // Otherwise, just drop it into a mergable constant section.  If we have
212       // a section for this size, use it, otherwise use the arbitrary sized
213       // mergable section.
214       switch (
215           GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
216       case 4:  return SectionKind::getMergeableConst4();
217       case 8:  return SectionKind::getMergeableConst8();
218       case 16: return SectionKind::getMergeableConst16();
219       case 32: return SectionKind::getMergeableConst32();
220       default:
221         return SectionKind::getReadOnly();
222       }
223 
224     } else {
225       // In static, ROPI and RWPI relocation models, the linker will resolve
226       // all addresses, so the relocation entries will actually be constants by
227       // the time the app starts up.  However, we can't put this into a
228       // mergable section, because the linker doesn't take relocations into
229       // consideration when it tries to merge entries in the section.
230       if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
231           ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
232         return SectionKind::getReadOnly();
233 
234       // Otherwise, the dynamic linker needs to fix it up, put it in the
235       // writable data.rel section.
236       return SectionKind::getReadOnlyWithRel();
237     }
238   }
239 
240   // Okay, this isn't a constant.
241   return SectionKind::getData();
242 }
243 
244 /// This method computes the appropriate section to emit the specified global
245 /// variable or function definition.  This should not be passed external (or
246 /// available externally) globals.
247 MCSection *TargetLoweringObjectFile::SectionForGlobal(
248     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
249   // Select section name.
250   if (GO->hasSection())
251     return getExplicitSectionGlobal(GO, Kind, TM);
252 
253   if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
254     auto Attrs = GVar->getAttributes();
255     if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
256         (Attrs.hasAttribute("data-section") && Kind.isData()) ||
257         (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()))  {
258        return getExplicitSectionGlobal(GO, Kind, TM);
259     }
260   }
261 
262   if (auto *F = dyn_cast<Function>(GO)) {
263     if (F->hasFnAttribute("implicit-section-name"))
264       return getExplicitSectionGlobal(GO, Kind, TM);
265   }
266 
267   // Use default section depending on the 'type' of global
268   return SelectSectionForGlobal(GO, Kind, TM);
269 }
270 
271 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
272     const Function &F, const TargetMachine &TM) const {
273   unsigned Align = 0;
274   return getSectionForConstant(F.getParent()->getDataLayout(),
275                                SectionKind::getReadOnly(), /*C=*/nullptr,
276                                Align);
277 }
278 
279 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
280     bool UsesLabelDifference, const Function &F) const {
281   // In PIC mode, we need to emit the jump table to the same section as the
282   // function body itself, otherwise the label differences won't make sense.
283   // FIXME: Need a better predicate for this: what about custom entries?
284   if (UsesLabelDifference)
285     return true;
286 
287   // We should also do if the section name is NULL or function is declared
288   // in discardable section
289   // FIXME: this isn't the right predicate, should be based on the MCSection
290   // for the function.
291   return F.isWeakForLinker();
292 }
293 
294 /// Given a mergable constant with the specified size and relocation
295 /// information, return a section that it should be placed in.
296 MCSection *TargetLoweringObjectFile::getSectionForConstant(
297     const DataLayout &DL, SectionKind Kind, const Constant *C,
298     unsigned &Align) const {
299   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
300     return ReadOnlySection;
301 
302   return DataSection;
303 }
304 
305 /// getTTypeGlobalReference - Return an MCExpr to use for a
306 /// reference to the specified global variable from exception
307 /// handling information.
308 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
309     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
310     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
311   const MCSymbolRefExpr *Ref =
312       MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
313 
314   return getTTypeReference(Ref, Encoding, Streamer);
315 }
316 
317 const MCExpr *TargetLoweringObjectFile::
318 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
319                   MCStreamer &Streamer) const {
320   switch (Encoding & 0x70) {
321   default:
322     report_fatal_error("We do not support this DWARF encoding yet!");
323   case dwarf::DW_EH_PE_absptr:
324     // Do nothing special
325     return Sym;
326   case dwarf::DW_EH_PE_pcrel: {
327     // Emit a label to the streamer for the current position.  This gives us
328     // .-foo addressing.
329     MCSymbol *PCSym = getContext().createTempSymbol();
330     Streamer.EmitLabel(PCSym);
331     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
332     return MCBinaryExpr::createSub(Sym, PC, getContext());
333   }
334   }
335 }
336 
337 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
338   // FIXME: It's not clear what, if any, default this should have - perhaps a
339   // null return could mean 'no location' & we should just do that here.
340   return MCSymbolRefExpr::create(Sym, *Ctx);
341 }
342 
343 void TargetLoweringObjectFile::getNameWithPrefix(
344     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
345     const TargetMachine &TM) const {
346   Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
347 }
348