Fix a FIXME by making GlobalVariable::getInitializer() return a
[oota-llvm.git] / lib / Target / TargetLoweringObjectFile.cpp
1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File 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 implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Target/Mangler.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallString.h"
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 //                              Generic Code
36 //===----------------------------------------------------------------------===//
37
38 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
39   TextSection = 0;
40   DataSection = 0;
41   BSSSection = 0;
42   ReadOnlySection = 0;
43   StaticCtorSection = 0;
44   StaticDtorSection = 0;
45   LSDASection = 0;
46
47   CommDirectiveSupportsAlignment = true;
48   DwarfAbbrevSection = 0;
49   DwarfInfoSection = 0;
50   DwarfLineSection = 0;
51   DwarfFrameSection = 0;
52   DwarfPubNamesSection = 0;
53   DwarfPubTypesSection = 0;
54   DwarfDebugInlineSection = 0;
55   DwarfStrSection = 0;
56   DwarfLocSection = 0;
57   DwarfARangesSection = 0;
58   DwarfRangesSection = 0;
59   DwarfMacroInfoSection = 0;
60   
61   IsFunctionEHFrameSymbolPrivate = true;
62   SupportsWeakOmittedEHFrame = true;
63 }
64
65 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
66 }
67
68 static bool isSuitableForBSS(const GlobalVariable *GV) {
69   const Constant *C = GV->getInitializer();
70
71   // Must have zero initializer.
72   if (!C->isNullValue())
73     return false;
74
75   // Leave constant zeros in readonly constant sections, so they can be shared.
76   if (GV->isConstant())
77     return false;
78
79   // If the global has an explicit section specified, don't put it in BSS.
80   if (!GV->getSection().empty())
81     return false;
82
83   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
84   if (NoZerosInBSS)
85     return false;
86
87   // Otherwise, put it in BSS!
88   return true;
89 }
90
91 /// IsNullTerminatedString - Return true if the specified constant (which is
92 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
93 /// nul value and contains no other nuls in it.
94 static bool IsNullTerminatedString(const Constant *C) {
95   const ArrayType *ATy = cast<ArrayType>(C->getType());
96
97   // First check: is we have constant array of i8 terminated with zero
98   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
99     if (ATy->getNumElements() == 0) return false;
100
101     ConstantInt *Null =
102       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
103     if (Null == 0 || !Null->isZero())
104       return false; // Not null terminated.
105
106     // Verify that the null doesn't occur anywhere else in the string.
107     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
108       // Reject constantexpr elements etc.
109       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
110           CVA->getOperand(i) == Null)
111         return false;
112     return true;
113   }
114
115   // Another possibility: [1 x i8] zeroinitializer
116   if (isa<ConstantAggregateZero>(C))
117     return ATy->getNumElements() == 1;
118
119   return false;
120 }
121
122 MCSymbol *TargetLoweringObjectFile::
123 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
124                         MachineModuleInfo *MMI) const {
125   return Mang->getSymbol(GV);
126 }
127
128 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
129                                                     const TargetMachine &TM,
130                                                     const MCSymbol *Sym) const {
131 }
132
133
134 /// getKindForGlobal - This is a top-level target-independent classifier for
135 /// a global variable.  Given an global variable and information from TM, it
136 /// classifies the global in a variety of ways that make various target
137 /// implementations simpler.  The target implementation is free to ignore this
138 /// extra info of course.
139 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
140                                                        const TargetMachine &TM){
141   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
142          "Can only be used for global definitions");
143
144   Reloc::Model ReloModel = TM.getRelocationModel();
145
146   // Early exit - functions should be always in text sections.
147   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
148   if (GVar == 0)
149     return SectionKind::getText();
150
151   // Handle thread-local data first.
152   if (GVar->isThreadLocal()) {
153     if (isSuitableForBSS(GVar))
154       return SectionKind::getThreadBSS();
155     return SectionKind::getThreadData();
156   }
157
158   // Variables with common linkage always get classified as common.
159   if (GVar->hasCommonLinkage())
160     return SectionKind::getCommon();
161
162   // Variable can be easily put to BSS section.
163   if (isSuitableForBSS(GVar)) {
164     if (GVar->hasLocalLinkage())
165       return SectionKind::getBSSLocal();
166     else if (GVar->hasExternalLinkage())
167       return SectionKind::getBSSExtern();
168     return SectionKind::getBSS();
169   }
170
171   const Constant *C = GVar->getInitializer();
172
173   // If the global is marked constant, we can put it into a mergable section,
174   // a mergable string section, or general .data if it contains relocations.
175   if (GVar->isConstant()) {
176     // If the initializer for the global contains something that requires a
177     // relocation, then we may have to drop this into a wriable data section
178     // even though it is marked const.
179     switch (C->getRelocationInfo()) {
180     default: assert(0 && "unknown relocation info kind");
181     case Constant::NoRelocation:
182       // If the global is required to have a unique address, it can't be put
183       // into a mergable section: just drop it into the general read-only
184       // section instead.
185       if (!GVar->hasUnnamedAddr())
186         return SectionKind::getReadOnly();
187         
188       // If initializer is a null-terminated string, put it in a "cstring"
189       // section of the right width.
190       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
191         if (const IntegerType *ITy =
192               dyn_cast<IntegerType>(ATy->getElementType())) {
193           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
194                ITy->getBitWidth() == 32) &&
195               IsNullTerminatedString(C)) {
196             if (ITy->getBitWidth() == 8)
197               return SectionKind::getMergeable1ByteCString();
198             if (ITy->getBitWidth() == 16)
199               return SectionKind::getMergeable2ByteCString();
200
201             assert(ITy->getBitWidth() == 32 && "Unknown width");
202             return SectionKind::getMergeable4ByteCString();
203           }
204         }
205       }
206
207       // Otherwise, just drop it into a mergable constant section.  If we have
208       // a section for this size, use it, otherwise use the arbitrary sized
209       // mergable section.
210       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
211       case 4:  return SectionKind::getMergeableConst4();
212       case 8:  return SectionKind::getMergeableConst8();
213       case 16: return SectionKind::getMergeableConst16();
214       default: return SectionKind::getMergeableConst();
215       }
216
217     case Constant::LocalRelocation:
218       // In static relocation model, the linker will resolve all addresses, so
219       // the relocation entries will actually be constants by the time the app
220       // starts up.  However, we can't put this into a mergable section, because
221       // the linker doesn't take relocations into consideration when it tries to
222       // merge entries in the section.
223       if (ReloModel == Reloc::Static)
224         return SectionKind::getReadOnly();
225
226       // Otherwise, the dynamic linker needs to fix it up, put it in the
227       // writable data.rel.local section.
228       return SectionKind::getReadOnlyWithRelLocal();
229
230     case Constant::GlobalRelocations:
231       // In static relocation model, the linker will resolve all addresses, so
232       // the relocation entries will actually be constants by the time the app
233       // starts up.  However, we can't put this into a mergable section, because
234       // the linker doesn't take relocations into consideration when it tries to
235       // merge entries in the section.
236       if (ReloModel == Reloc::Static)
237         return SectionKind::getReadOnly();
238
239       // Otherwise, the dynamic linker needs to fix it up, put it in the
240       // writable data.rel section.
241       return SectionKind::getReadOnlyWithRel();
242     }
243   }
244
245   // Okay, this isn't a constant.  If the initializer for the global is going
246   // to require a runtime relocation by the dynamic linker, put it into a more
247   // specific section to improve startup time of the app.  This coalesces these
248   // globals together onto fewer pages, improving the locality of the dynamic
249   // linker.
250   if (ReloModel == Reloc::Static)
251     return SectionKind::getDataNoRel();
252
253   switch (C->getRelocationInfo()) {
254   default: assert(0 && "unknown relocation info kind");
255   case Constant::NoRelocation:
256     return SectionKind::getDataNoRel();
257   case Constant::LocalRelocation:
258     return SectionKind::getDataRelLocal();
259   case Constant::GlobalRelocations:
260     return SectionKind::getDataRel();
261   }
262 }
263
264 /// SectionForGlobal - This method computes the appropriate section to emit
265 /// the specified global variable or function definition.  This should not
266 /// be passed external (or available externally) globals.
267 const MCSection *TargetLoweringObjectFile::
268 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
269                  const TargetMachine &TM) const {
270   // Select section name.
271   if (GV->hasSection())
272     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
273
274
275   // Use default section depending on the 'type' of global
276   return SelectSectionForGlobal(GV, Kind, Mang, TM);
277 }
278
279
280 // Lame default implementation. Calculate the section name for global.
281 const MCSection *
282 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
283                                                  SectionKind Kind,
284                                                  Mangler *Mang,
285                                                  const TargetMachine &TM) const{
286   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
287
288   if (Kind.isText())
289     return getTextSection();
290
291   if (Kind.isBSS() && BSSSection != 0)
292     return BSSSection;
293
294   if (Kind.isReadOnly() && ReadOnlySection != 0)
295     return ReadOnlySection;
296
297   return getDataSection();
298 }
299
300 /// getSectionForConstant - Given a mergable constant with the
301 /// specified size and relocation information, return a section that it
302 /// should be placed in.
303 const MCSection *
304 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
305   if (Kind.isReadOnly() && ReadOnlySection != 0)
306     return ReadOnlySection;
307
308   return DataSection;
309 }
310
311 /// getExprForDwarfGlobalReference - Return an MCExpr to use for a
312 /// reference to the specified global variable from exception
313 /// handling information.
314 const MCExpr *TargetLoweringObjectFile::
315 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
316                                MachineModuleInfo *MMI, unsigned Encoding,
317                                MCStreamer &Streamer) const {
318   const MCSymbol *Sym = Mang->getSymbol(GV);
319   return getExprForDwarfReference(Sym, Encoding, Streamer);
320 }
321
322 const MCExpr *TargetLoweringObjectFile::
323 getExprForDwarfReference(const MCSymbol *Sym, unsigned Encoding,
324                          MCStreamer &Streamer) const {
325   const MCExpr *Res = MCSymbolRefExpr::Create(Sym, getContext());
326
327   switch (Encoding & 0x70) {
328   default:
329     report_fatal_error("We do not support this DWARF encoding yet!");
330   case dwarf::DW_EH_PE_absptr:
331     // Do nothing special
332     return Res;
333   case dwarf::DW_EH_PE_pcrel: {
334     // Emit a label to the streamer for the current position.  This gives us
335     // .-foo addressing.
336     MCSymbol *PCSym = getContext().CreateTempSymbol();
337     Streamer.EmitLabel(PCSym);
338     const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
339     return MCBinaryExpr::CreateSub(Res, PC, getContext());
340   }
341   }
342 }
343
344 unsigned TargetLoweringObjectFile::getPersonalityEncoding() const {
345   return dwarf::DW_EH_PE_absptr;
346 }
347
348 unsigned TargetLoweringObjectFile::getLSDAEncoding() const {
349   return dwarf::DW_EH_PE_absptr;
350 }
351
352 unsigned TargetLoweringObjectFile::getFDEEncoding(bool CFI) const {
353   return dwarf::DW_EH_PE_absptr;
354 }
355
356 unsigned TargetLoweringObjectFile::getTTypeEncoding() const {
357   return dwarf::DW_EH_PE_absptr;
358 }
359