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