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