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