Sink getSectionPrefixForUniqueGlobal down into the TAI
[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/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <cctype>
28 #include <cstring>
29 using namespace llvm;
30
31 TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) {
32   BSSSection = "\t.bss";
33   BSSSection_ = 0;
34   ReadOnlySection = 0;
35   TLSDataSection = 0;
36   TLSBSSSection = 0;
37   ZeroFillDirective = 0;
38   NonexecutableStackDirective = 0;
39   NeedsSet = false;
40   MaxInstLength = 4;
41   PCSymbol = "$";
42   SeparatorChar = ';';
43   CommentColumn = 60;
44   CommentString = "#";
45   FirstOperandColumn = 0;
46   MaxOperandLength = 0;
47   GlobalPrefix = "";
48   PrivateGlobalPrefix = ".";
49   LinkerPrivateGlobalPrefix = "";
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   AllowQuotesInName = false;
62   ZeroDirective = "\t.zero\t";
63   ZeroDirectiveSuffix = 0;
64   AsciiDirective = "\t.ascii\t";
65   AscizDirective = "\t.asciz\t";
66   Data8bitsDirective = "\t.byte\t";
67   Data16bitsDirective = "\t.short\t";
68   Data32bitsDirective = "\t.long\t";
69   Data64bitsDirective = "\t.quad\t";
70   AlignDirective = "\t.align\t";
71   AlignmentIsInBytes = true;
72   TextAlignFillValue = 0;
73   SwitchToSectionDirective = "\t.section\t";
74   TextSectionStartSuffix = "";
75   DataSectionStartSuffix = "";
76   SectionEndDirectiveSuffix = 0;
77   ConstantPoolSection = "\t.section .rodata";
78   JumpTableDataSection = "\t.section .rodata";
79   JumpTableDirective = 0;
80   CStringSection = 0;
81   CStringSection_ = 0;
82   // FIXME: Flags are ELFish - replace with normal section stuff.
83   StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
84   StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
85   GlobalDirective = "\t.globl\t";
86   SetDirective = 0;
87   LCOMMDirective = 0;
88   COMMDirective = "\t.comm\t";
89   COMMDirectiveTakesAlignment = true;
90   HasDotTypeDotSizeDirective = true;
91   HasSingleParameterDotFile = true;
92   UsedDirective = 0;
93   WeakRefDirective = 0;
94   WeakDefDirective = 0;
95   // FIXME: These are ELFish - move to ELFTAI.
96   HiddenDirective = "\t.hidden\t";
97   ProtectedDirective = "\t.protected\t";
98   AbsoluteDebugSectionOffsets = false;
99   AbsoluteEHSectionOffsets = false;
100   HasLEB128 = false;
101   HasDotLocAndDotFile = false;
102   SupportsDebugInformation = false;
103   SupportsExceptionHandling = false;
104   DwarfRequiresFrameSection = true;
105   DwarfUsesInlineInfoSection = false;
106   Is_EHSymbolPrivate = true;
107   GlobalEHDirective = 0;
108   SupportsWeakOmittedEHFrame = true;
109   DwarfSectionOffsetDirective = 0;
110   DwarfAbbrevSection = ".debug_abbrev";
111   DwarfInfoSection = ".debug_info";
112   DwarfLineSection = ".debug_line";
113   DwarfFrameSection = ".debug_frame";
114   DwarfPubNamesSection = ".debug_pubnames";
115   DwarfPubTypesSection = ".debug_pubtypes";
116   DwarfDebugInlineSection = ".debug_inlined";
117   DwarfStrSection = ".debug_str";
118   DwarfLocSection = ".debug_loc";
119   DwarfARangesSection = ".debug_aranges";
120   DwarfRangesSection = ".debug_ranges";
121   DwarfMacroInfoSection = ".debug_macinfo";
122   DwarfEHFrameSection = ".eh_frame";
123   DwarfExceptionSection = ".gcc_except_table";
124   AsmTransCBE = 0;
125 }
126
127 TargetAsmInfo::~TargetAsmInfo() {
128 }
129
130 /// Measure the specified inline asm to determine an approximation of its
131 /// length.
132 /// Comments (which run till the next SeparatorChar or newline) do not
133 /// count as an instruction.
134 /// Any other non-whitespace text is considered an instruction, with
135 /// multiple instructions separated by SeparatorChar or newlines.
136 /// Variable-length instructions are not handled here; this function
137 /// may be overloaded in the target code to do that.
138 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
139   // Count the number of instructions in the asm.
140   bool atInsnStart = true;
141   unsigned Length = 0;
142   for (; *Str; ++Str) {
143     if (*Str == '\n' || *Str == SeparatorChar)
144       atInsnStart = true;
145     if (atInsnStart && !isspace(*Str)) {
146       Length += MaxInstLength;
147       atInsnStart = false;
148     }
149     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
150       atInsnStart = false;
151   }
152
153   return Length;
154 }
155
156 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
157                                               bool Global) const {
158   return dwarf::DW_EH_PE_absptr;
159 }
160
161 static bool isSuitableForBSS(const GlobalVariable *GV) {
162   Constant *C = GV->getInitializer();
163   
164   // Must have zero initializer.
165   if (!C->isNullValue())
166     return false;
167   
168   // Leave constant zeros in readonly constant sections, so they can be shared.
169   if (GV->isConstant())
170     return false;
171   
172   // If the global has an explicit section specified, don't put it in BSS.
173   if (!GV->getSection().empty())
174     return false;
175   
176   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
177   if (NoZerosInBSS)
178     return false;
179   
180   // Otherwise, put it in BSS!
181   return true;
182 }
183
184 static bool isConstantString(const Constant *C) {
185   // First check: is we have constant array of i8 terminated with zero
186   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
187   // Check, if initializer is a null-terminated string
188   if (CVA && CVA->isCString())
189     return true;
190
191   // Another possibility: [1 x i8] zeroinitializer
192   if (isa<ConstantAggregateZero>(C))
193     if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
194       return (Ty->getElementType() == Type::Int8Ty &&
195               Ty->getNumElements() == 1);
196
197   return false;
198 }
199
200 static SectionKind::Kind SectionKindForGlobal(const GlobalValue *GV,
201                                               const TargetMachine &TM) {
202   Reloc::Model ReloModel = TM.getRelocationModel();
203   
204   // Early exit - functions should be always in text sections.
205   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
206   if (GVar == 0)
207     return SectionKind::Text;
208
209   
210   // Handle thread-local data first.
211   if (GVar->isThreadLocal()) {
212     if (isSuitableForBSS(GVar))
213       return SectionKind::ThreadBSS;
214     return SectionKind::ThreadData;
215   }
216
217   // Variable can be easily put to BSS section.
218   if (isSuitableForBSS(GVar))
219     return SectionKind::BSS;
220
221   Constant *C = GVar->getInitializer();
222   
223   // If the global is marked constant, we can put it into a mergable section,
224   // a mergable string section, or general .data if it contains relocations.
225   if (GVar->isConstant()) {
226     // If the initializer for the global contains something that requires a
227     // relocation, then we may have to drop this into a wriable data section
228     // even though it is marked const.
229     switch (C->getRelocationInfo()) {
230     default: llvm_unreachable("unknown relocation info kind");
231     case Constant::NoRelocation:
232       // If initializer is a null-terminated string, put it in a "cstring"
233       // section if the target has it.
234       if (isConstantString(C))
235         return SectionKind::MergeableCString;
236       
237       // Otherwise, just drop it into a mergable constant section.  If we have
238       // a section for this size, use it, otherwise use the arbitrary sized
239       // mergable section.
240       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
241       case 4:  return SectionKind::MergeableConst4;
242       case 8:  return SectionKind::MergeableConst8;
243       case 16: return SectionKind::MergeableConst16;
244       default: return SectionKind::MergeableConst;
245       }
246       
247     case Constant::LocalRelocation:
248       // In static relocation model, the linker will resolve all addresses, so
249       // the relocation entries will actually be constants by the time the app
250       // starts up.  However, we can't put this into a mergable section, because
251       // the linker doesn't take relocations into consideration when it tries to
252       // merge entries in the section.
253       if (ReloModel == Reloc::Static)
254         return SectionKind::ReadOnly;
255               
256       // Otherwise, the dynamic linker needs to fix it up, put it in the
257       // writable data.rel.local section.
258       return SectionKind::ReadOnlyWithRelLocal;
259               
260     case Constant::GlobalRelocations:
261       // In static relocation model, the linker will resolve all addresses, so
262       // the relocation entries will actually be constants by the time the app
263       // starts up.  However, we can't put this into a mergable section, because
264       // the linker doesn't take relocations into consideration when it tries to
265       // merge entries in the section.
266       if (ReloModel == Reloc::Static)
267         return SectionKind::ReadOnly;
268       
269       // Otherwise, the dynamic linker needs to fix it up, put it in the
270       // writable data.rel section.
271       return SectionKind::ReadOnlyWithRel;
272     }
273   }
274
275   // Okay, this isn't a constant.  If the initializer for the global is going
276   // to require a runtime relocation by the dynamic linker, put it into a more
277   // specific section to improve startup time of the app.  This coalesces these
278   // globals together onto fewer pages, improving the locality of the dynamic
279   // linker.
280   if (ReloModel == Reloc::Static)
281     return SectionKind::DataNoRel;
282
283   switch (C->getRelocationInfo()) {
284   default: llvm_unreachable("unknown relocation info kind");
285   case Constant::NoRelocation:
286     return SectionKind::DataNoRel;
287   case Constant::LocalRelocation:
288     return SectionKind::DataRelLocal;
289   case Constant::GlobalRelocations:
290     return SectionKind::DataRel;
291   }
292 }
293
294 /// SectionForGlobal - This method computes the appropriate section to emit
295 /// the specified global variable or function definition.  This should not
296 /// be passed external (or available externally) globals.
297 const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
298   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
299          "Can only be used for global definitions");
300   
301   SectionKind::Kind GVKind = SectionKindForGlobal(GV, TM);
302   
303   SectionKind Kind = SectionKind::get(GVKind, GV->isWeakForLinker(),
304                                       GV->hasSection());
305
306
307   // Select section name.
308   if (GV->hasSection()) {
309     // If the target has special section hacks for specifically named globals,
310     // return them now.
311     if (const Section *TS = getSpecialCasedSectionGlobals(GV, Kind))
312       return TS;
313     
314     // If the target has magic semantics for certain section names, make sure to
315     // pick up the flags.  This allows the user to write things with attribute
316     // section and still get the appropriate section flags printed.
317     GVKind = getKindForNamedSection(GV->getSection().c_str(), GVKind);
318     
319     return getOrCreateSection(GV->getSection().c_str(), false, GVKind);
320   }
321
322   
323   // Use default section depending on the 'type' of global
324   return SelectSectionForGlobal(GV, Kind);
325 }
326
327 // Lame default implementation. Calculate the section name for global.
328 const Section*
329 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV,
330                                       SectionKind Kind) const {
331   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
332   
333   if (Kind.isText())
334     return getTextSection();
335   
336   if (Kind.isBSS())
337     if (const Section *S = getBSSSection_())
338       return S;
339   
340   if (Kind.isReadOnly())
341     if (const Section *S = getReadOnlySection())
342       return S;
343
344   return getDataSection();
345 }
346
347 /// getSectionForMergableConstant - Given a mergable constant with the
348 /// specified size and relocation information, return a section that it
349 /// should be placed in.
350 const Section *
351 TargetAsmInfo::getSectionForMergeableConstant(SectionKind Kind) const {
352   if (Kind.isReadOnly())
353     if (const Section *S = getReadOnlySection())
354       return S;
355   
356   return getDataSection();
357 }
358
359
360 const Section *TargetAsmInfo::getOrCreateSection(const char *Name,
361                                                  bool isDirective,
362                                                  SectionKind::Kind Kind) const {
363   Section &S = Sections[Name];
364
365   // This is newly-created section, set it up properly.
366   if (S.Name.empty()) {
367     S.Kind = SectionKind::get(Kind, false /*weak*/, !isDirective);
368     S.Name = Name;
369   }
370
371   return &S;
372 }
373
374 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
375   unsigned Size = 0;
376   do {
377     Value >>= 7;
378     Size += sizeof(int8_t);
379   } while (Value);
380   return Size;
381 }
382
383 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
384   unsigned Size = 0;
385   int Sign = Value >> (8 * sizeof(Value) - 1);
386   bool IsMore;
387
388   do {
389     unsigned Byte = Value & 0x7f;
390     Value >>= 7;
391     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
392     Size += sizeof(int8_t);
393   } while (IsMore);
394   return Size;
395 }