580c3fe4db031d18ad62054c8d1d0a6099e1aafc
[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   FirstOperandColumn = 0;
49   MaxOperandLength = 0;
50   GlobalPrefix = "";
51   PrivateGlobalPrefix = ".";
52   LinkerPrivateGlobalPrefix = "";
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   AllowQuotesInName = false;
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   // FIXME: Flags are ELFish - replace with normal section stuff.
86   StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
87   StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
88   GlobalDirective = "\t.globl\t";
89   SetDirective = 0;
90   LCOMMDirective = 0;
91   COMMDirective = "\t.comm\t";
92   COMMDirectiveTakesAlignment = true;
93   HasDotTypeDotSizeDirective = true;
94   HasSingleParameterDotFile = true;
95   UsedDirective = 0;
96   WeakRefDirective = 0;
97   WeakDefDirective = 0;
98   // FIXME: These are ELFish - move to ELFTAI.
99   HiddenDirective = "\t.hidden\t";
100   ProtectedDirective = "\t.protected\t";
101   AbsoluteDebugSectionOffsets = false;
102   AbsoluteEHSectionOffsets = false;
103   HasLEB128 = false;
104   HasDotLocAndDotFile = false;
105   SupportsDebugInformation = false;
106   SupportsExceptionHandling = false;
107   DwarfRequiresFrameSection = true;
108   DwarfUsesInlineInfoSection = false;
109   Is_EHSymbolPrivate = true;
110   GlobalEHDirective = 0;
111   SupportsWeakOmittedEHFrame = true;
112   DwarfSectionOffsetDirective = 0;
113   DwarfAbbrevSection = ".debug_abbrev";
114   DwarfInfoSection = ".debug_info";
115   DwarfLineSection = ".debug_line";
116   DwarfFrameSection = ".debug_frame";
117   DwarfPubNamesSection = ".debug_pubnames";
118   DwarfPubTypesSection = ".debug_pubtypes";
119   DwarfDebugInlineSection = ".debug_inlined";
120   DwarfStrSection = ".debug_str";
121   DwarfLocSection = ".debug_loc";
122   DwarfARangesSection = ".debug_aranges";
123   DwarfRangesSection = ".debug_ranges";
124   DwarfMacroInfoSection = ".debug_macinfo";
125   DwarfEHFrameSection = ".eh_frame";
126   DwarfExceptionSection = ".gcc_except_table";
127   AsmTransCBE = 0;
128   TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
129   DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
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 static bool isConstantString(const Constant *C) {
176   // First check: is we have constant array of i8 terminated with zero
177   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
178   // Check, if initializer is a null-terminated string
179   if (CVA && CVA->isCString())
180     return true;
181
182   // Another possibility: [1 x i8] zeroinitializer
183   if (isa<ConstantAggregateZero>(C)) {
184     if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
185       return (Ty->getElementType() == Type::Int8Ty &&
186               Ty->getNumElements() == 1);
187     }
188   }
189
190   return false;
191 }
192
193 SectionKind::Kind
194 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
195   // Early exit - functions should be always in text sections.
196   if (isa<Function>(GV))
197     return SectionKind::Text;
198
199   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
200   bool isThreadLocal = GVar->isThreadLocal();
201   assert(GVar && "Invalid global value for section selection");
202
203   if (isSuitableForBSS(GVar)) {
204     // Variable can be easily put to BSS section.
205     return (isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS);
206   } else if (GVar->isConstant() && !isThreadLocal) {
207     // Now we know, that variable has initializer and it is constant. We need to
208     // check its initializer to decide, which section to output it into. Also
209     // note, there is no thread-local r/o section.
210     Constant *C = GVar->getInitializer();
211     if (C->ContainsRelocations(Reloc::LocalOrGlobal)) {
212       // Decide whether it is still possible to put symbol into r/o section.
213       if (TM.getRelocationModel() != Reloc::Static)
214         return SectionKind::Data;
215       else
216         return SectionKind::ROData;
217     } else {
218       // Check, if initializer is a null-terminated string
219       if (isConstantString(C))
220         return SectionKind::RODataMergeStr;
221       else
222         return SectionKind::RODataMergeConst;
223     }
224   }
225
226   // Variable either is not constant or thread-local - output to data section.
227   return (isThreadLocal ? SectionKind::ThreadData : SectionKind::Data);
228 }
229
230 unsigned
231 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
232                                      const char* Name) const {
233   unsigned Flags = SectionFlags::None;
234
235   // Decode flags from global itself.
236   if (GV) {
237     SectionKind::Kind Kind = SectionKindForGlobal(GV);
238     switch (Kind) {
239     case SectionKind::Text:
240       Flags |= SectionFlags::Code;
241       break;
242     case SectionKind::ThreadData:
243     case SectionKind::ThreadBSS:
244       Flags |= SectionFlags::TLS;
245       // FALLS THROUGH
246     case SectionKind::Data:
247     case SectionKind::DataRel:
248     case SectionKind::DataRelLocal:
249     case SectionKind::DataRelRO:
250     case SectionKind::DataRelROLocal:
251     case SectionKind::BSS:
252       Flags |= SectionFlags::Writeable;
253       break;
254     case SectionKind::ROData:
255     case SectionKind::RODataMergeStr:
256     case SectionKind::RODataMergeConst:
257       // No additional flags here
258       break;
259     case SectionKind::SmallData:
260     case SectionKind::SmallBSS:
261       Flags |= SectionFlags::Writeable;
262       // FALLS THROUGH
263     case SectionKind::SmallROData:
264       Flags |= SectionFlags::Small;
265       break;
266     default:
267       llvm_unreachable("Unexpected section kind!");
268     }
269
270     if (GV->isWeakForLinker())
271       Flags |= SectionFlags::Linkonce;
272   }
273
274   // Add flags from sections, if any.
275   if (Name && *Name) {
276     Flags |= SectionFlags::Named;
277
278     // Some lame default implementation based on some magic section names.
279     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
280         strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
281         strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
282         strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
283       Flags |= SectionFlags::BSS;
284     else if (strcmp(Name, ".tdata") == 0 ||
285              strncmp(Name, ".tdata.", 7) == 0 ||
286              strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
287              strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
288       Flags |= SectionFlags::TLS;
289     else if (strcmp(Name, ".tbss") == 0 ||
290              strncmp(Name, ".tbss.", 6) == 0 ||
291              strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
292              strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
293       Flags |= SectionFlags::BSS | SectionFlags::TLS;
294   }
295
296   return Flags;
297 }
298
299 const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
300   // Select section name
301   if (GV->hasSection()) {
302     // Honour section already set, if any.
303     unsigned Flags = SectionFlagsForGlobal(GV, GV->getSection().c_str());
304     return getNamedSection(GV->getSection().c_str(), Flags);
305   }
306   
307   // Use default section depending on the 'type' of global
308   return SelectSectionForGlobal(GV);
309 }
310
311 // Lame default implementation. Calculate the section name for global.
312 const Section*
313 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
314   SectionKind::Kind Kind = SectionKindForGlobal(GV);
315
316   if (GV->isWeakForLinker()) {
317     std::string Name = UniqueSectionForGlobal(GV, Kind);
318     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
319     return getNamedSection(Name.c_str(), Flags);
320   } else {
321     if (Kind == SectionKind::Text)
322       return getTextSection();
323     else if (isBSS(Kind) && getBSSSection_())
324       return getBSSSection_();
325     else if (getReadOnlySection() && SectionKind::isReadOnly(Kind))
326       return getReadOnlySection();
327   }
328
329   return getDataSection();
330 }
331
332 // Lame default implementation. Calculate the section name for machine const.
333 const Section*
334 TargetAsmInfo::SelectSectionForMachineConst(const Type *Ty) const {
335   // FIXME: Support data.rel stuff someday
336   return getDataSection();
337 }
338
339 std::string
340 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
341                                       SectionKind::Kind Kind) const {
342   switch (Kind) {
343    case SectionKind::Text:
344     return ".gnu.linkonce.t." + GV->getName();
345    case SectionKind::Data:
346     return ".gnu.linkonce.d." + GV->getName();
347    case SectionKind::DataRel:
348     return ".gnu.linkonce.d.rel" + GV->getName();
349    case SectionKind::DataRelLocal:
350     return ".gnu.linkonce.d.rel.local" + GV->getName();
351    case SectionKind::DataRelRO:
352     return ".gnu.linkonce.d.rel.ro" + GV->getName();
353    case SectionKind::DataRelROLocal:
354     return ".gnu.linkonce.d.rel.ro.local" + GV->getName();
355    case SectionKind::SmallData:
356     return ".gnu.linkonce.s." + GV->getName();
357    case SectionKind::BSS:
358     return ".gnu.linkonce.b." + GV->getName();
359    case SectionKind::SmallBSS:
360     return ".gnu.linkonce.sb." + GV->getName();
361    case SectionKind::ROData:
362    case SectionKind::RODataMergeConst:
363    case SectionKind::RODataMergeStr:
364     return ".gnu.linkonce.r." + GV->getName();
365    case SectionKind::SmallROData:
366     return ".gnu.linkonce.s2." + GV->getName();
367    case SectionKind::ThreadData:
368     return ".gnu.linkonce.td." + GV->getName();
369    case SectionKind::ThreadBSS:
370     return ".gnu.linkonce.tb." + GV->getName();
371    default:
372     llvm_unreachable("Unknown section kind");
373   }
374   return NULL;
375 }
376
377 const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
378                                               bool Override) const {
379   Section &S = Sections[Name];
380
381   // This is newly-created section, set it up properly.
382   if (S.Flags == SectionFlags::Invalid || Override) {
383     S.Flags = Flags | SectionFlags::Named;
384     S.Name = Name;
385   }
386
387   return &S;
388 }
389
390 const Section*
391 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
392                                  bool Override) const {
393   Section& S = Sections[Directive];
394
395   // This is newly-created section, set it up properly.
396   if (S.Flags == SectionFlags::Invalid || Override) {
397     S.Flags = Flags & ~SectionFlags::Named;
398     S.Name = Directive;
399   }
400
401   return &S;
402 }
403
404 const std::string&
405 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
406   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
407
408   // We didn't print these flags yet, print and save them to map. This reduces
409   // amount of heap trashing due to std::string construction / concatenation.
410   if (I == FlagsStrings.end())
411     I = FlagsStrings.insert(std::make_pair(Flags,
412                                            printSectionFlags(Flags))).first;
413
414   return I->second;
415 }
416
417 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
418   unsigned Size = 0;
419   do {
420     Value >>= 7;
421     Size += sizeof(int8_t);
422   } while (Value);
423   return Size;
424 }
425
426 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
427   unsigned Size = 0;
428   int Sign = Value >> (8 * sizeof(Value) - 1);
429   bool IsMore;
430
431   do {
432     unsigned Byte = Value & 0x7f;
433     Value >>= 7;
434     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
435     Size += sizeof(int8_t);
436   } while (IsMore);
437   return Size;
438 }