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