1 //===-- HexagonTargetObjectFile.cpp ---------------------------------------===//
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 contains the declarations of the HexagonTargetAsmInfo properties.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "hexagon-sdata"
15 
16 #include "HexagonTargetObjectFile.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/GlobalObject.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/SectionKind.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetMachine.h"
34 
35 using namespace llvm;
36 
37 static cl::opt<unsigned> SmallDataThreshold("hexagon-small-data-threshold",
38   cl::init(8), cl::Hidden,
39   cl::desc("The maximum size of an object in the sdata section"));
40 
41 static cl::opt<bool> NoSmallDataSorting("mno-sort-sda", cl::init(false),
42   cl::Hidden, cl::desc("Disable small data sections sorting"));
43 
44 static cl::opt<bool> StaticsInSData("hexagon-statics-in-small-data",
45   cl::init(false), cl::Hidden, cl::ZeroOrMore,
46   cl::desc("Allow static variables in .sdata"));
47 
48 static cl::opt<bool> TraceGVPlacement("trace-gv-placement",
49   cl::Hidden, cl::init(false),
50   cl::desc("Trace global value placement"));
51 
52 static cl::opt<bool>
53     EmitJtInText("hexagon-emit-jt-text", cl::Hidden, cl::init(false),
54                  cl::desc("Emit hexagon jump tables in function section"));
55 
56 // TraceGVPlacement controls messages for all builds. For builds with assertions
57 // (debug or release), messages are also controlled by the usual debug flags
58 // (e.g. -debug and -debug-only=globallayout)
59 #define TRACE_TO(s, X) s << X
60 #ifdef NDEBUG
61 #define TRACE(X)                                                               \
62   do {                                                                         \
63     if (TraceGVPlacement) {                                                    \
64       TRACE_TO(errs(), X);                                                     \
65     }                                                                          \
66   } while (false)
67 #else
68 #define TRACE(X)                                                               \
69   do {                                                                         \
70     if (TraceGVPlacement) {                                                    \
71       TRACE_TO(errs(), X);                                                     \
72     } else {                                                                   \
73       DEBUG(TRACE_TO(dbgs(), X));                                              \
74     }                                                                          \
75   } while (false)
76 #endif
77 
78 // Returns true if the section name is such that the symbol will be put
79 // in a small data section.
80 // For instance, global variables with section attributes such as ".sdata"
81 // ".sdata.*", ".sbss", and ".sbss.*" will go into small data.
82 static bool isSmallDataSection(StringRef Sec) {
83   // sectionName is either ".sdata" or ".sbss". Looking for an exact match
84   // obviates the need for checks for section names such as ".sdatafoo".
85   if (Sec.equals(".sdata") || Sec.equals(".sbss") || Sec.equals(".scommon"))
86     return true;
87   // If either ".sdata." or ".sbss." is a substring of the section name
88   // then put the symbol in small data.
89   return Sec.find(".sdata.") != StringRef::npos ||
90          Sec.find(".sbss.") != StringRef::npos ||
91          Sec.find(".scommon.") != StringRef::npos;
92 }
93 
94 static const char *getSectionSuffixForSize(unsigned Size) {
95   switch (Size) {
96   default:
97     return "";
98   case 1:
99     return ".1";
100   case 2:
101     return ".2";
102   case 4:
103     return ".4";
104   case 8:
105     return ".8";
106   }
107 }
108 
109 void HexagonTargetObjectFile::Initialize(MCContext &Ctx,
110       const TargetMachine &TM) {
111   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
112   InitializeELF(TM.Options.UseInitArray);
113 
114   SmallDataSection =
115     getContext().getELFSection(".sdata", ELF::SHT_PROGBITS,
116                                ELF::SHF_WRITE | ELF::SHF_ALLOC |
117                                ELF::SHF_HEX_GPREL);
118   SmallBSSSection =
119     getContext().getELFSection(".sbss", ELF::SHT_NOBITS,
120                                ELF::SHF_WRITE | ELF::SHF_ALLOC |
121                                ELF::SHF_HEX_GPREL);
122 }
123 
124 MCSection *HexagonTargetObjectFile::SelectSectionForGlobal(
125     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
126   TRACE("[SelectSectionForGlobal] GO(" << GO->getName() << ") ");
127   TRACE("input section(" << GO->getSection() << ") ");
128 
129   TRACE((GO->hasPrivateLinkage() ? "private_linkage " : "")
130          << (GO->hasLocalLinkage() ? "local_linkage " : "")
131          << (GO->hasInternalLinkage() ? "internal " : "")
132          << (GO->hasExternalLinkage() ? "external " : "")
133          << (GO->hasCommonLinkage() ? "common_linkage " : "")
134          << (GO->hasCommonLinkage() ? "common " : "" )
135          << (Kind.isCommon() ? "kind_common " : "" )
136          << (Kind.isBSS() ? "kind_bss " : "" )
137          << (Kind.isBSSLocal() ? "kind_bss_local " : "" ));
138 
139   if (isGlobalInSmallSection(GO, TM))
140     return selectSmallSectionForGlobal(GO, Kind, TM);
141 
142   if (Kind.isCommon()) {
143     // This is purely for LTO+Linker Script because commons don't really have a
144     // section. However, the BitcodeSectionWriter pass will query for the
145     // sections of commons (and the linker expects us to know their section) so
146     // we'll return one here.
147     return BSSSection;
148   }
149 
150   TRACE("default_ELF_section\n");
151   // Otherwise, we work the same as ELF.
152   return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM);
153 }
154 
155 MCSection *HexagonTargetObjectFile::getExplicitSectionGlobal(
156     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
157   TRACE("[getExplicitSectionGlobal] GO(" << GO->getName() << ") from("
158         << GO->getSection() << ") ");
159   TRACE((GO->hasPrivateLinkage() ? "private_linkage " : "")
160          << (GO->hasLocalLinkage() ? "local_linkage " : "")
161          << (GO->hasInternalLinkage() ? "internal " : "")
162          << (GO->hasExternalLinkage() ? "external " : "")
163          << (GO->hasCommonLinkage() ? "common_linkage " : "")
164          << (GO->hasCommonLinkage() ? "common " : "" )
165          << (Kind.isCommon() ? "kind_common " : "" )
166          << (Kind.isBSS() ? "kind_bss " : "" )
167          << (Kind.isBSSLocal() ? "kind_bss_local " : "" ));
168 
169   if (GO->hasSection()) {
170     StringRef Section = GO->getSection();
171     if (Section.find(".access.text.group") != StringRef::npos)
172       return getContext().getELFSection(GO->getSection(), ELF::SHT_PROGBITS,
173                                         ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
174     if (Section.find(".access.data.group") != StringRef::npos)
175       return getContext().getELFSection(GO->getSection(), ELF::SHT_PROGBITS,
176                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
177   }
178 
179   if (isGlobalInSmallSection(GO, TM))
180     return selectSmallSectionForGlobal(GO, Kind, TM);
181 
182   // Otherwise, we work the same as ELF.
183   TRACE("default_ELF_section\n");
184   return TargetLoweringObjectFileELF::getExplicitSectionGlobal(GO, Kind, TM);
185 }
186 
187 /// Return true if this global value should be placed into small data/bss
188 /// section.
189 bool HexagonTargetObjectFile::isGlobalInSmallSection(const GlobalObject *GO,
190       const TargetMachine &TM) const {
191   // Only global variables, not functions.
192   DEBUG(dbgs() << "Checking if value is in small-data, -G"
193                << SmallDataThreshold << ": \"" << GO->getName() << "\": ");
194   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO);
195   if (!GVar) {
196     DEBUG(dbgs() << "no, not a global variable\n");
197     return false;
198   }
199 
200   // Globals with external linkage that have an original section set must be
201   // emitted to that section, regardless of whether we would put them into
202   // small data or not. This is how we can support mixing -G0/-G8 in LTO.
203   if (GVar->hasSection()) {
204     bool IsSmall = isSmallDataSection(GVar->getSection());
205     DEBUG(dbgs() << (IsSmall ? "yes" : "no") << ", has section: "
206                  << GVar->getSection() << '\n');
207     return IsSmall;
208   }
209 
210   if (GVar->isConstant()) {
211     DEBUG(dbgs() << "no, is a constant\n");
212     return false;
213   }
214 
215   bool IsLocal = GVar->hasLocalLinkage();
216   if (!StaticsInSData && IsLocal) {
217     DEBUG(dbgs() << "no, is static\n");
218     return false;
219   }
220 
221   Type *GType = GVar->getType();
222   if (PointerType *PT = dyn_cast<PointerType>(GType))
223     GType = PT->getElementType();
224 
225   if (isa<ArrayType>(GType)) {
226     DEBUG(dbgs() << "no, is an array\n");
227     return false;
228   }
229 
230   // If the type is a struct with no body provided, treat is conservatively.
231   // There cannot be actual definitions of object of such a type in this CU
232   // (only references), so assuming that they are not in sdata is safe. If
233   // these objects end up in the sdata, the references will still be valid.
234   if (StructType *ST = dyn_cast<StructType>(GType)) {
235     if (ST->isOpaque()) {
236       DEBUG(dbgs() << "no, has opaque type\n");
237       return false;
238     }
239   }
240 
241   unsigned Size = GVar->getParent()->getDataLayout().getTypeAllocSize(GType);
242   if (Size == 0) {
243     DEBUG(dbgs() << "no, has size 0\n");
244     return false;
245   }
246   if (Size > SmallDataThreshold) {
247     DEBUG(dbgs() << "no, size exceeds sdata threshold: " << Size << '\n');
248     return false;
249   }
250 
251   DEBUG(dbgs() << "yes\n");
252   return true;
253 }
254 
255 bool HexagonTargetObjectFile::isSmallDataEnabled() const {
256   return SmallDataThreshold > 0;
257 }
258 
259 unsigned HexagonTargetObjectFile::getSmallDataSize() const {
260   return SmallDataThreshold;
261 }
262 
263 bool HexagonTargetObjectFile::shouldPutJumpTableInFunctionSection(
264     bool UsesLabelDifference, const Function &F) const {
265   return EmitJtInText;
266 }
267 
268 /// Descends any type down to "elementary" components,
269 /// discovering the smallest addressable one.
270 /// If zero is returned, declaration will not be modified.
271 unsigned HexagonTargetObjectFile::getSmallestAddressableSize(const Type *Ty,
272       const GlobalValue *GV, const TargetMachine &TM) const {
273   // Assign the smallest element access size to the highest
274   // value which assembler can handle.
275   unsigned SmallestElement = 8;
276 
277   if (!Ty)
278     return 0;
279   switch (Ty->getTypeID()) {
280   case Type::StructTyID: {
281     const StructType *STy = cast<const StructType>(Ty);
282     for (auto &E : STy->elements()) {
283       unsigned AtomicSize = getSmallestAddressableSize(E, GV, TM);
284       if (AtomicSize < SmallestElement)
285         SmallestElement = AtomicSize;
286     }
287     return (STy->getNumElements() == 0) ? 0 : SmallestElement;
288   }
289   case Type::ArrayTyID: {
290     const ArrayType *ATy = cast<const ArrayType>(Ty);
291     return getSmallestAddressableSize(ATy->getElementType(), GV, TM);
292   }
293   case Type::VectorTyID: {
294     const VectorType *PTy = cast<const VectorType>(Ty);
295     return getSmallestAddressableSize(PTy->getElementType(), GV, TM);
296   }
297   case Type::PointerTyID:
298   case Type::HalfTyID:
299   case Type::FloatTyID:
300   case Type::DoubleTyID:
301   case Type::IntegerTyID: {
302     const DataLayout &DL = GV->getParent()->getDataLayout();
303     // It is unfortunate that DL's function take non-const Type*.
304     return DL.getTypeAllocSize(const_cast<Type*>(Ty));
305   }
306   case Type::FunctionTyID:
307   case Type::VoidTyID:
308   case Type::X86_FP80TyID:
309   case Type::FP128TyID:
310   case Type::PPC_FP128TyID:
311   case Type::LabelTyID:
312   case Type::MetadataTyID:
313   case Type::X86_MMXTyID:
314   case Type::TokenTyID:
315     return 0;
316   }
317 
318   return 0;
319 }
320 
321 MCSection *HexagonTargetObjectFile::selectSmallSectionForGlobal(
322     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
323   const Type *GTy = GO->getType()->getElementType();
324   unsigned Size = getSmallestAddressableSize(GTy, GO, TM);
325 
326   // If we have -ffunction-section or -fdata-section then we should emit the
327   // global value to a unique section specifically for it... even for sdata.
328   bool EmitUniquedSection = TM.getDataSections();
329 
330   TRACE("Small data. Size(" << Size << ")");
331   // Handle Small Section classification here.
332   if (Kind.isBSS() || Kind.isBSSLocal()) {
333     // If -mno-sort-sda is not set, find out smallest accessible entity in
334     // declaration and add it to the section name string.
335     // Note. It does not track the actual usage of the value, only its de-
336     // claration. Also, compiler adds explicit pad fields to some struct
337     // declarations - they are currently counted towards smallest addres-
338     // sable entity.
339     if (NoSmallDataSorting) {
340       TRACE(" default sbss\n");
341       return SmallBSSSection;
342     }
343 
344     StringRef Prefix(".sbss");
345     SmallString<128> Name(Prefix);
346     Name.append(getSectionSuffixForSize(Size));
347 
348     if (EmitUniquedSection) {
349       Name.append(".");
350       Name.append(GO->getName());
351     }
352     TRACE(" unique sbss(" << Name << ")\n");
353     return getContext().getELFSection(Name.str(), ELF::SHT_NOBITS,
354                 ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_HEX_GPREL);
355   }
356 
357   if (Kind.isCommon()) {
358     // This is purely for LTO+Linker Script because commons don't really have a
359     // section. However, the BitcodeSectionWriter pass will query for the
360     // sections of commons (and the linker expects us to know their section) so
361     // we'll return one here.
362     if (NoSmallDataSorting)
363       return BSSSection;
364 
365     Twine Name = Twine(".scommon") + getSectionSuffixForSize(Size);
366     TRACE(" small COMMON (" << Name << ")\n");
367 
368     return getContext().getELFSection(Name.str(), ELF::SHT_NOBITS,
369                                       ELF::SHF_WRITE | ELF::SHF_ALLOC |
370                                       ELF::SHF_HEX_GPREL);
371   }
372 
373   // We could have changed sdata object to a constant... in this
374   // case the Kind could be wrong for it.
375   if (Kind.isMergeableConst()) {
376     TRACE(" const_object_as_data ");
377     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO);
378     if (GVar->hasSection() && isSmallDataSection(GVar->getSection()))
379       Kind = SectionKind::getData();
380   }
381 
382   if (Kind.isData()) {
383     if (NoSmallDataSorting) {
384       TRACE(" default sdata\n");
385       return SmallDataSection;
386     }
387 
388     StringRef Prefix(".sdata");
389     SmallString<128> Name(Prefix);
390     Name.append(getSectionSuffixForSize(Size));
391 
392     if (EmitUniquedSection) {
393       Name.append(".");
394       Name.append(GO->getName());
395     }
396     TRACE(" unique sdata(" << Name << ")\n");
397     return getContext().getELFSection(Name.str(), ELF::SHT_PROGBITS,
398                 ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_HEX_GPREL);
399   }
400 
401   TRACE("default ELF section\n");
402   // Otherwise, we work the same as ELF.
403   return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM);
404 }
405