cc0745f680a25d8dc4c2ad5a1fa722329918f438
[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("\t.text"),
30   TextSection_(0),
31   DataSection("\t.data"),
32   DataSection_(0),
33   BSSSection("\t.bss"),
34   BSSSection_(0),
35   ReadOnlySection(0),
36   ReadOnlySection_(0),
37   SmallDataSection(0),
38   SmallBSSSection(0),
39   SmallRODataSection(0),
40   TLSDataSection("\t.section .tdata,\"awT\",@progbits"),
41   TLSDataSection_(0),
42   TLSBSSSection("\t.section .tbss,\"awT\",@nobits"),
43   TLSBSSSection_(0),
44   ZeroFillDirective(0),
45   NonexecutableStackDirective(0),
46   NeedsSet(false),
47   MaxInstLength(4),
48   PCSymbol("$"),
49   SeparatorChar(';'),
50   CommentString("#"),
51   GlobalPrefix(""),
52   PrivateGlobalPrefix("."),
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(TextSection);
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 std::string
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   if (!S->isNamed())
289     return S->Name;
290
291   // If section is named we need to switch into it via special '.section'
292   // directive and also append funky flags. Otherwise - section name is just
293   // some magic assembler directive.
294   return getSwitchToSectionDirective() + S->Name + getSectionFlags(S->Flags);
295 }
296
297 // Lame default implementation. Calculate the section name for global.
298 const Section*
299 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
300   SectionKind::Kind Kind = SectionKindForGlobal(GV);
301
302   if (GV->isWeakForLinker()) {
303     std::string Name = UniqueSectionForGlobal(GV, Kind);
304     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
305     return getNamedSection(Name.c_str(), Flags);
306   } else {
307     if (Kind == SectionKind::Text)
308       return getTextSection_();
309     else if (isBSS(Kind) && getBSSSection_())
310       return getBSSSection_();
311     else if (getReadOnlySection_() && SectionKind::isReadOnly(Kind))
312       return getReadOnlySection_();
313   }
314
315   return getDataSection_();
316 }
317
318 // Lame default implementation. Calculate the section name for machine const.
319 const Section*
320 TargetAsmInfo::SelectSectionForMachineConst(const Type *Ty) const {
321   // FIXME: Support data.rel stuff someday
322   return getDataSection_();
323 }
324
325 std::string
326 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
327                                       SectionKind::Kind Kind) const {
328   switch (Kind) {
329    case SectionKind::Text:
330     return ".gnu.linkonce.t." + GV->getName();
331    case SectionKind::Data:
332     return ".gnu.linkonce.d." + GV->getName();
333    case SectionKind::SmallData:
334     return ".gnu.linkonce.s." + GV->getName();
335    case SectionKind::BSS:
336     return ".gnu.linkonce.b." + GV->getName();
337    case SectionKind::SmallBSS:
338     return ".gnu.linkonce.sb." + GV->getName();
339    case SectionKind::ROData:
340    case SectionKind::RODataMergeConst:
341    case SectionKind::RODataMergeStr:
342     return ".gnu.linkonce.r." + GV->getName();
343    case SectionKind::SmallROData:
344     return ".gnu.linkonce.s2." + GV->getName();
345    case SectionKind::ThreadData:
346     return ".gnu.linkonce.td." + GV->getName();
347    case SectionKind::ThreadBSS:
348     return ".gnu.linkonce.tb." + GV->getName();
349    default:
350     assert(0 && "Unknown section kind");
351   }
352 }
353
354 const Section*
355 TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags) const {
356   Section& S = Sections[Name];
357
358   // This is newly-created section, set it up properly.
359   if (S.Flags == SectionFlags::Invalid) {
360     S.Flags = Flags | SectionFlags::Named;
361     S.Name = Name;
362   }
363
364   return &S;
365 }
366
367 const Section*
368 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags) const {
369   Section& S = Sections[Directive];
370
371   // This is newly-created section, set it up properly.
372   if (S.Flags == SectionFlags::Invalid) {
373     S.Flags = Flags & ~SectionFlags::Named;
374     S.Name = Directive;
375   }
376
377   return &S;
378 }
379
380 const std::string&
381 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
382   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
383
384   // We didn't print these flags yet, print and save them to map. This reduces
385   // amount of heap trashing due to std::string construction / concatenation.
386   if (I == FlagsStrings.end())
387     I = FlagsStrings.insert(std::make_pair(Flags,
388                                            printSectionFlags(Flags))).first;
389
390   return I->second;
391 }
392
393 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
394   unsigned Size = 0;
395   do {
396     Value >>= 7;
397     Size += sizeof(int8_t);
398   } while (Value);
399   return Size;
400 }
401
402 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
403   unsigned Size = 0;
404   int Sign = Value >> (8 * sizeof(Value) - 1);
405   bool IsMore;
406
407   do {
408     unsigned Byte = Value & 0x7f;
409     Value >>= 7;
410     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
411     Size += sizeof(int8_t);
412   } while (IsMore);
413   return Size;
414 }