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