Get rid of ReadOnlySection duplicate
[oota-llvm.git] / lib / Target / TargetAsmInfo.cpp
1 //===-- TargetAsmInfo.cpp - Asm 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 defines target asm properties related what form asm statements
11 // should take.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Target/TargetAsmInfo.h"
21 #include "llvm/Target/TargetOptions.h"
22 #include "llvm/Support/Dwarf.h"
23 #include <cctype>
24 #include <cstring>
25
26 using namespace llvm;
27
28 TargetAsmInfo::TargetAsmInfo() :
29   TextSection(0),
30   DataSection(0),
31   BSSSection("\t.bss"),
32   BSSSection_(0),
33   ReadOnlySection(0),
34   SmallDataSection(0),
35   SmallBSSSection(0),
36   SmallRODataSection(0),
37   TLSDataSection(0),
38   TLSBSSSection(0),
39   ZeroFillDirective(0),
40   NonexecutableStackDirective(0),
41   NeedsSet(false),
42   MaxInstLength(4),
43   PCSymbol("$"),
44   SeparatorChar(';'),
45   CommentString("#"),
46   GlobalPrefix(""),
47   PrivateGlobalPrefix("."),
48   LessPrivateGlobalPrefix(""),
49   JumpTableSpecialLabelPrefix(0),
50   GlobalVarAddrPrefix(""),
51   GlobalVarAddrSuffix(""),
52   FunctionAddrPrefix(""),
53   FunctionAddrSuffix(""),
54   PersonalityPrefix(""),
55   PersonalitySuffix(""),
56   NeedsIndirectEncoding(false),
57   InlineAsmStart("#APP"),
58   InlineAsmEnd("#NO_APP"),
59   AssemblerDialect(0),
60   StringConstantPrefix(".str"),
61   ZeroDirective("\t.zero\t"),
62   ZeroDirectiveSuffix(0),
63   AsciiDirective("\t.ascii\t"),
64   AscizDirective("\t.asciz\t"),
65   Data8bitsDirective("\t.byte\t"),
66   Data16bitsDirective("\t.short\t"),
67   Data32bitsDirective("\t.long\t"),
68   Data64bitsDirective("\t.quad\t"),
69   AlignDirective("\t.align\t"),
70   AlignmentIsInBytes(true),
71   TextAlignFillValue(0),
72   SwitchToSectionDirective("\t.section\t"),
73   TextSectionStartSuffix(""),
74   DataSectionStartSuffix(""),
75   SectionEndDirectiveSuffix(0),
76   ConstantPoolSection("\t.section .rodata"),
77   JumpTableDataSection("\t.section .rodata"),
78   JumpTableDirective(0),
79   CStringSection(0),
80   CStringSection_(0),
81   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
82   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
83   GlobalDirective("\t.globl\t"),
84   SetDirective(0),
85   LCOMMDirective(0),
86   COMMDirective("\t.comm\t"),
87   COMMDirectiveTakesAlignment(true),
88   HasDotTypeDotSizeDirective(true),
89   UsedDirective(0),
90   WeakRefDirective(0),
91   WeakDefDirective(0),
92   HiddenDirective("\t.hidden\t"),
93   ProtectedDirective("\t.protected\t"),
94   AbsoluteDebugSectionOffsets(false),
95   AbsoluteEHSectionOffsets(false),
96   HasLEB128(false),
97   HasDotLocAndDotFile(false),
98   SupportsDebugInformation(false),
99   SupportsExceptionHandling(false),
100   DwarfRequiresFrameSection(true),
101   GlobalEHDirective(0),
102   SupportsWeakOmittedEHFrame(true),
103   DwarfSectionOffsetDirective(0),
104   DwarfAbbrevSection(".debug_abbrev"),
105   DwarfInfoSection(".debug_info"),
106   DwarfLineSection(".debug_line"),
107   DwarfFrameSection(".debug_frame"),
108   DwarfPubNamesSection(".debug_pubnames"),
109   DwarfPubTypesSection(".debug_pubtypes"),
110   DwarfStrSection(".debug_str"),
111   DwarfLocSection(".debug_loc"),
112   DwarfARangesSection(".debug_aranges"),
113   DwarfRangesSection(".debug_ranges"),
114   DwarfMacInfoSection(".debug_macinfo"),
115   DwarfEHFrameSection(".eh_frame"),
116   DwarfExceptionSection(".gcc_except_table"),
117   AsmTransCBE(0) {
118   TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
119   DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
120 }
121
122 TargetAsmInfo::~TargetAsmInfo() {
123 }
124
125 /// Measure the specified inline asm to determine an approximation of its
126 /// length.
127 /// Comments (which run till the next SeparatorChar or newline) do not
128 /// count as an instruction.
129 /// Any other non-whitespace text is considered an instruction, with
130 /// multiple instructions separated by SeparatorChar or newlines.
131 /// Variable-length instructions are not handled here; this function
132 /// may be overloaded in the target code to do that.
133 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
134   // Count the number of instructions in the asm.
135   bool atInsnStart = true;
136   unsigned Length = 0;
137   for (; *Str; ++Str) {
138     if (*Str == '\n' || *Str == SeparatorChar)
139       atInsnStart = true;
140     if (atInsnStart && !isspace(*Str)) {
141       Length += MaxInstLength;
142       atInsnStart = false;
143     }
144     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
145       atInsnStart = false;
146   }
147
148   return Length;
149 }
150
151 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
152                                               bool Global) const {
153   return dwarf::DW_EH_PE_absptr;
154 }
155
156 static bool isSuitableForBSS(const GlobalVariable *GV) {
157   if (!GV->hasInitializer())
158     return true;
159
160   // Leave constant zeros in readonly constant sections, so they can be shared
161   Constant *C = GV->getInitializer();
162   return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
163 }
164
165 SectionKind::Kind
166 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
167   // Early exit - functions should be always in text sections.
168   if (isa<Function>(GV))
169     return SectionKind::Text;
170
171   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
172   bool isThreadLocal = GVar->isThreadLocal();
173   assert(GVar && "Invalid global value for section selection");
174
175   if (isSuitableForBSS(GVar)) {
176     // Variable can be easily put to BSS section.
177     return (isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS);
178   } else if (GVar->isConstant() && !isThreadLocal) {
179     // Now we know, that varible has initializer and it is constant. We need to
180     // check its initializer to decide, which section to output it into. Also
181     // note, there is no thread-local r/o section.
182     Constant *C = GVar->getInitializer();
183     if (C->ContainsRelocations())
184       return SectionKind::ROData;
185     else {
186       const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
187       // Check, if initializer is a null-terminated string
188       if (CVA && CVA->isCString())
189         return SectionKind::RODataMergeStr;
190       else
191         return SectionKind::RODataMergeConst;
192     }
193   }
194
195   // Variable is not constant or thread-local - emit to generic data section.
196   return (isThreadLocal ? SectionKind::ThreadData : SectionKind::Data);
197 }
198
199 unsigned
200 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
201                                      const char* Name) const {
202   unsigned Flags = SectionFlags::None;
203
204   // Decode flags from global itself.
205   if (GV) {
206     SectionKind::Kind Kind = SectionKindForGlobal(GV);
207     switch (Kind) {
208      case SectionKind::Text:
209       Flags |= SectionFlags::Code;
210       break;
211      case SectionKind::ThreadData:
212      case SectionKind::ThreadBSS:
213       Flags |= SectionFlags::TLS;
214       // FALLS THROUGH
215      case SectionKind::Data:
216      case SectionKind::BSS:
217       Flags |= SectionFlags::Writeable;
218       break;
219      case SectionKind::ROData:
220      case SectionKind::RODataMergeStr:
221      case SectionKind::RODataMergeConst:
222       // No additional flags here
223       break;
224      case SectionKind::SmallData:
225      case SectionKind::SmallBSS:
226       Flags |= SectionFlags::Writeable;
227       // FALLS THROUGH
228      case SectionKind::SmallROData:
229       Flags |= SectionFlags::Small;
230       break;
231      default:
232       assert(0 && "Unexpected section kind!");
233     }
234
235     if (GV->isWeakForLinker())
236       Flags |= SectionFlags::Linkonce;
237   }
238
239   // Add flags from sections, if any.
240   if (Name && *Name) {
241     Flags |= SectionFlags::Named;
242
243     // Some lame default implementation based on some magic section names.
244     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
245         strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
246         strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
247         strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
248       Flags |= SectionFlags::BSS;
249     else if (strcmp(Name, ".tdata") == 0 ||
250              strncmp(Name, ".tdata.", 7) == 0 ||
251              strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
252              strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
253       Flags |= SectionFlags::TLS;
254     else if (strcmp(Name, ".tbss") == 0 ||
255              strncmp(Name, ".tbss.", 6) == 0 ||
256              strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
257              strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
258       Flags |= SectionFlags::BSS | SectionFlags::TLS;
259   }
260
261   return Flags;
262 }
263
264 const Section*
265 TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
266   const Section* S;
267   // Select section name
268   if (GV->hasSection()) {
269     // Honour section already set, if any
270     unsigned Flags = SectionFlagsForGlobal(GV,
271                                            GV->getSection().c_str());
272     S = getNamedSection(GV->getSection().c_str(), Flags);
273   } else {
274     // Use default section depending on the 'type' of global
275     S = SelectSectionForGlobal(GV);
276   }
277
278   return S;
279 }
280
281 // Lame default implementation. Calculate the section name for global.
282 const Section*
283 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
284   SectionKind::Kind Kind = SectionKindForGlobal(GV);
285
286   if (GV->isWeakForLinker()) {
287     std::string Name = UniqueSectionForGlobal(GV, Kind);
288     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
289     return getNamedSection(Name.c_str(), Flags);
290   } else {
291     if (Kind == SectionKind::Text)
292       return getTextSection();
293     else if (isBSS(Kind) && getBSSSection_())
294       return getBSSSection_();
295     else if (getReadOnlySection() && SectionKind::isReadOnly(Kind))
296       return getReadOnlySection();
297   }
298
299   return getDataSection();
300 }
301
302 // Lame default implementation. Calculate the section name for machine const.
303 const Section*
304 TargetAsmInfo::SelectSectionForMachineConst(const Type *Ty) const {
305   // FIXME: Support data.rel stuff someday
306   return getDataSection();
307 }
308
309 std::string
310 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
311                                       SectionKind::Kind Kind) const {
312   switch (Kind) {
313    case SectionKind::Text:
314     return ".gnu.linkonce.t." + GV->getName();
315    case SectionKind::Data:
316     return ".gnu.linkonce.d." + GV->getName();
317    case SectionKind::SmallData:
318     return ".gnu.linkonce.s." + GV->getName();
319    case SectionKind::BSS:
320     return ".gnu.linkonce.b." + GV->getName();
321    case SectionKind::SmallBSS:
322     return ".gnu.linkonce.sb." + GV->getName();
323    case SectionKind::ROData:
324    case SectionKind::RODataMergeConst:
325    case SectionKind::RODataMergeStr:
326     return ".gnu.linkonce.r." + GV->getName();
327    case SectionKind::SmallROData:
328     return ".gnu.linkonce.s2." + GV->getName();
329    case SectionKind::ThreadData:
330     return ".gnu.linkonce.td." + GV->getName();
331    case SectionKind::ThreadBSS:
332     return ".gnu.linkonce.tb." + GV->getName();
333    default:
334     assert(0 && "Unknown section kind");
335   }
336 }
337
338 const Section*
339 TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
340                                bool Override) const {
341   Section& S = Sections[Name];
342
343   // This is newly-created section, set it up properly.
344   if (S.Flags == SectionFlags::Invalid || Override) {
345     S.Flags = Flags | SectionFlags::Named;
346     S.Name = Name;
347   }
348
349   return &S;
350 }
351
352 const Section*
353 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
354                                  bool Override) const {
355   Section& S = Sections[Directive];
356
357   // This is newly-created section, set it up properly.
358   if (S.Flags == SectionFlags::Invalid || Override) {
359     S.Flags = Flags & ~SectionFlags::Named;
360     S.Name = Directive;
361   }
362
363   return &S;
364 }
365
366 const std::string&
367 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
368   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
369
370   // We didn't print these flags yet, print and save them to map. This reduces
371   // amount of heap trashing due to std::string construction / concatenation.
372   if (I == FlagsStrings.end())
373     I = FlagsStrings.insert(std::make_pair(Flags,
374                                            printSectionFlags(Flags))).first;
375
376   return I->second;
377 }
378
379 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
380   unsigned Size = 0;
381   do {
382     Value >>= 7;
383     Size += sizeof(int8_t);
384   } while (Value);
385   return Size;
386 }
387
388 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
389   unsigned Size = 0;
390   int Sign = Value >> (8 * sizeof(Value) - 1);
391   bool IsMore;
392
393   do {
394     unsigned Byte = Value & 0x7f;
395     Value >>= 7;
396     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
397     Size += sizeof(int8_t);
398   } while (IsMore);
399   return Size;
400 }