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