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