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