e193dd47a51f89d0dd5a73f40bd74e9b5f7c3e63
[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 {
33   BSSSection = "\t.bss";
34   BSSSection_ = 0;
35   ReadOnlySection = 0;
36   TLSDataSection = 0;
37   TLSBSSSection = 0;
38   ZeroFillDirective = 0;
39   NonexecutableStackDirective = 0;
40   NeedsSet = false;
41   MaxInstLength = 4;
42   PCSymbol = "$";
43   SeparatorChar = ';';
44   CommentColumn = 60;
45   CommentString = "#";
46   FirstOperandColumn = 0;
47   MaxOperandLength = 0;
48   GlobalPrefix = "";
49   PrivateGlobalPrefix = ".";
50   LinkerPrivateGlobalPrefix = "";
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   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   Is_EHSymbolPrivate = true;
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(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())
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 SectionKind::Kind
192 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
193   // Early exit - functions should be always in text sections.
194   if (isa<Function>(GV))
195     return SectionKind::Text;
196
197   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
198   bool isThreadLocal = GVar->isThreadLocal();
199   assert(GVar && "Invalid global value for section selection");
200
201   if (isSuitableForBSS(GVar)) {
202     // Variable can be easily put to BSS section.
203     return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
204   } else if (GVar->isConstant() && !isThreadLocal) {
205     // Now we know, that variable has initializer and it is constant. We need to
206     // check its initializer to decide, which section to output it into. Also
207     // note, there is no thread-local r/o section.
208     Constant *C = GVar->getInitializer();
209     if (C->getRelocationInfo() != 0) {
210       // Decide whether it is still possible to put symbol into r/o section.
211       if (TM.getRelocationModel() != Reloc::Static)
212         return SectionKind::Data;
213       else
214         return SectionKind::ROData;
215     } else {
216       // Check, if initializer is a null-terminated string
217       if (isConstantString(C))
218         return SectionKind::RODataMergeStr;
219       else
220         return SectionKind::RODataMergeConst;
221     }
222   }
223
224   // Variable either is not constant or thread-local - output to data section.
225   return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data;
226 }
227
228 unsigned
229 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
230                                      const char* Name) const {
231   unsigned Flags = SectionFlags::None;
232
233   // Decode flags from global itself.
234   if (GV) {
235     SectionKind::Kind Kind = SectionKindForGlobal(GV);
236     switch (Kind) {
237     case SectionKind::Text:
238       Flags |= SectionFlags::Code;
239       break;
240     case SectionKind::ThreadData:
241     case SectionKind::ThreadBSS:
242       Flags |= SectionFlags::TLS;
243       // FALLS THROUGH
244     case SectionKind::Data:
245     case SectionKind::DataRel:
246     case SectionKind::DataRelLocal:
247     case SectionKind::DataRelRO:
248     case SectionKind::DataRelROLocal:
249     case SectionKind::BSS:
250       Flags |= SectionFlags::Writeable;
251       break;
252     case SectionKind::ROData:
253     case SectionKind::RODataMergeStr:
254     case SectionKind::RODataMergeConst:
255       // No additional flags here
256       break;
257     default:
258       llvm_unreachable("Unexpected section kind!");
259     }
260
261     if (GV->isWeakForLinker())
262       Flags |= SectionFlags::Linkonce;
263   }
264
265   // Add flags from sections, if any.
266   if (Name && *Name) {
267     Flags |= SectionFlags::Named;
268
269     // Some lame default implementation based on some magic section names.
270     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
271         strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
272         strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
273         strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
274       Flags |= SectionFlags::BSS;
275     else if (strcmp(Name, ".tdata") == 0 ||
276              strncmp(Name, ".tdata.", 7) == 0 ||
277              strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
278              strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
279       Flags |= SectionFlags::TLS;
280     else if (strcmp(Name, ".tbss") == 0 ||
281              strncmp(Name, ".tbss.", 6) == 0 ||
282              strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
283              strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
284       Flags |= SectionFlags::BSS | SectionFlags::TLS;
285   }
286
287   return Flags;
288 }
289
290 const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
291   // Select section name
292   if (GV->hasSection()) {
293     // Honour section already set, if any.
294     unsigned Flags = SectionFlagsForGlobal(GV, GV->getSection().c_str());
295     return getNamedSection(GV->getSection().c_str(), Flags);
296   }
297
298   // If this global is linkonce/weak and the target handles this by emitting it
299   // into a 'uniqued' section name, create and return the section now.
300   if (GV->isWeakForLinker()) {
301     if (const char *Prefix =
302           getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) {
303       // FIXME: Use mangler interface (PR4584).
304       std::string Name = Prefix+GV->getName();
305       unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
306       return getNamedSection(Name.c_str(), Flags);
307     }
308   }
309   
310   // Use default section depending on the 'type' of global
311   return SelectSectionForGlobal(GV);
312 }
313
314 // Lame default implementation. Calculate the section name for global.
315 const Section*
316 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
317   SectionKind::Kind Kind = SectionKindForGlobal(GV);
318
319   if (Kind == SectionKind::Text)
320     return getTextSection();
321   
322   if (isBSS(Kind))
323     if (const Section *S = getBSSSection_())
324       return S;
325   
326   if (SectionKind::isReadOnly(Kind))
327     if (const Section *S = getReadOnlySection())
328       return S;
329
330   return getDataSection();
331 }
332
333 /// getSectionForMergableConstant - Given a mergable constant with the
334 /// specified size and relocation information, return a section that it
335 /// should be placed in.
336 const Section *
337 TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
338                                              unsigned ReloInfo) const {
339   // FIXME: Support data.rel stuff someday
340   // Lame default implementation. Calculate the section name for machine const.
341   return getDataSection();
342 }
343
344
345
346
347 const char *
348 TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const {
349   switch (Kind) {
350   default: llvm_unreachable("Unknown section kind");
351   case SectionKind::Text:             return ".gnu.linkonce.t.";
352   case SectionKind::Data:             return ".gnu.linkonce.d.";
353   case SectionKind::DataRel:          return ".gnu.linkonce.d.rel.";
354   case SectionKind::DataRelLocal:     return ".gnu.linkonce.d.rel.local.";
355   case SectionKind::DataRelRO:        return ".gnu.linkonce.d.rel.ro.";
356   case SectionKind::DataRelROLocal:   return ".gnu.linkonce.d.rel.ro.local.";
357   case SectionKind::BSS:              return ".gnu.linkonce.b.";
358   case SectionKind::ROData:
359   case SectionKind::RODataMergeConst:
360   case SectionKind::RODataMergeStr:   return ".gnu.linkonce.r.";
361   case SectionKind::ThreadData:       return ".gnu.linkonce.td.";
362   case SectionKind::ThreadBSS:        return ".gnu.linkonce.tb.";
363   }
364 }
365
366 const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
367                                               bool Override) const {
368   Section &S = Sections[Name];
369
370   // This is newly-created section, set it up properly.
371   if (S.Flags == SectionFlags::Invalid || Override) {
372     S.Flags = Flags | SectionFlags::Named;
373     S.Name = Name;
374   }
375
376   return &S;
377 }
378
379 const Section*
380 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
381                                  bool Override) const {
382   Section& S = Sections[Directive];
383
384   // This is newly-created section, set it up properly.
385   if (S.Flags == SectionFlags::Invalid || Override) {
386     S.Flags = Flags & ~SectionFlags::Named;
387     S.Name = Directive;
388   }
389
390   return &S;
391 }
392
393 const std::string&
394 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
395   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
396
397   // We didn't print these flags yet, print and save them to map. This reduces
398   // amount of heap trashing due to std::string construction / concatenation.
399   if (I == FlagsStrings.end())
400     I = FlagsStrings.insert(std::make_pair(Flags,
401                                            printSectionFlags(Flags))).first;
402
403   return I->second;
404 }
405
406 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
407   unsigned Size = 0;
408   do {
409     Value >>= 7;
410     Size += sizeof(int8_t);
411   } while (Value);
412   return Size;
413 }
414
415 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
416   unsigned Size = 0;
417   int Sign = Value >> (8 * sizeof(Value) - 1);
418   bool IsMore;
419
420   do {
421     unsigned Byte = Value & 0x7f;
422     Value >>= 7;
423     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
424     Size += sizeof(int8_t);
425   } while (IsMore);
426   return Size;
427 }