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.
Initialize(MCContext & ctx,const TargetMachine & TM)41 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
42 const TargetMachine &TM) {
43 Ctx = &ctx;
44 InitMCObjectFileInfo(TM.getTargetTriple(), TM.getRelocationModel(), *Ctx);
45 }
46
~TargetLoweringObjectFile()47 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
48 }
49
isSuitableForBSS(const GlobalVariable * GV)50 static bool isSuitableForBSS(const GlobalVariable *GV) {
51 const Constant *C = GV->getInitializer();
52
53 // Must have zero initializer.
54 if (!C->isNullValue())
55 return false;
56
57 // Leave constant zeros in readonly constant sections, so they can be shared.
58 if (GV->isConstant())
59 return false;
60
61 // If the global has an explicit section specified, don't put it in BSS.
62 if (!GV->getSection().empty())
63 return false;
64
65 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
66 if (NoZerosInBSS)
67 return false;
68
69 // Otherwise, put it in BSS!
70 return true;
71 }
72
73 /// IsNullTerminatedString - Return true if the specified constant (which is
74 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
75 /// nul value and contains no other nuls in it.
IsNullTerminatedString(const Constant * C)76 static bool IsNullTerminatedString(const Constant *C) {
77 ArrayType *ATy = cast<ArrayType>(C->getType());
78
79 // First check: is we have constant array of i8 terminated with zero
80 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
81 if (ATy->getNumElements() == 0) return false;
82
83 ConstantInt *Null =
84 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
85 if (Null == 0 || !Null->isZero())
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, e = ATy->getNumElements()-1; i != e; ++i)
90 // Reject constantexpr elements etc.
91 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
92 CVA->getOperand(i) == Null)
93 return false;
94 return true;
95 }
96
97 // Another possibility: [1 x i8] zeroinitializer
98 if (isa<ConstantAggregateZero>(C))
99 return ATy->getNumElements() == 1;
100
101 return false;
102 }
103
104 MCSymbol *TargetLoweringObjectFile::
getCFIPersonalitySymbol(const GlobalValue * GV,Mangler * Mang,MachineModuleInfo * MMI) const105 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
106 MachineModuleInfo *MMI) const {
107 return Mang->getSymbol(GV);
108 }
109
emitPersonalityValue(MCStreamer & Streamer,const TargetMachine & TM,const MCSymbol * Sym) const110 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
111 const TargetMachine &TM,
112 const MCSymbol *Sym) const {
113 }
114
115
116 /// getKindForGlobal - This is a top-level target-independent classifier for
117 /// a global variable. Given an global variable and information from TM, it
118 /// classifies the global in a variety of ways that make various target
119 /// implementations simpler. The target implementation is free to ignore this
120 /// extra info of course.
getKindForGlobal(const GlobalValue * GV,const TargetMachine & TM)121 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
122 const TargetMachine &TM){
123 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
124 "Can only be used for global definitions");
125
126 Reloc::Model ReloModel = TM.getRelocationModel();
127
128 // Early exit - functions should be always in text sections.
129 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
130 if (GVar == 0)
131 return SectionKind::getText();
132
133 // Handle thread-local data first.
134 if (GVar->isThreadLocal()) {
135 if (isSuitableForBSS(GVar))
136 return SectionKind::getThreadBSS();
137 return SectionKind::getThreadData();
138 }
139
140 // Variables with common linkage always get classified as common.
141 if (GVar->hasCommonLinkage())
142 return SectionKind::getCommon();
143
144 // Variable can be easily put to BSS section.
145 if (isSuitableForBSS(GVar)) {
146 if (GVar->hasLocalLinkage())
147 return SectionKind::getBSSLocal();
148 else if (GVar->hasExternalLinkage())
149 return SectionKind::getBSSExtern();
150 return SectionKind::getBSS();
151 }
152
153 const Constant *C = GVar->getInitializer();
154
155 // If the global is marked constant, we can put it into a mergable section,
156 // a mergable string section, or general .data if it contains relocations.
157 if (GVar->isConstant()) {
158 // If the initializer for the global contains something that requires a
159 // relocation, then we may have to drop this into a wriable data section
160 // even though it is marked const.
161 switch (C->getRelocationInfo()) {
162 default: assert(0 && "unknown relocation info kind");
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 default: assert(0 && "unknown relocation info kind");
237 case Constant::NoRelocation:
238 return SectionKind::getDataNoRel();
239 case Constant::LocalRelocation:
240 return SectionKind::getDataRelLocal();
241 case Constant::GlobalRelocations:
242 return SectionKind::getDataRel();
243 }
244 }
245
246 /// SectionForGlobal - This method computes the appropriate section to emit
247 /// the specified global variable or function definition. This should not
248 /// be passed external (or available externally) globals.
249 const MCSection *TargetLoweringObjectFile::
SectionForGlobal(const GlobalValue * GV,SectionKind Kind,Mangler * Mang,const TargetMachine & TM) const250 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
251 const TargetMachine &TM) const {
252 // Select section name.
253 if (GV->hasSection())
254 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
255
256
257 // Use default section depending on the 'type' of global
258 return SelectSectionForGlobal(GV, Kind, Mang, TM);
259 }
260
261
262 // Lame default implementation. Calculate the section name for global.
263 const MCSection *
SelectSectionForGlobal(const GlobalValue * GV,SectionKind Kind,Mangler * Mang,const TargetMachine & TM) const264 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
265 SectionKind Kind,
266 Mangler *Mang,
267 const TargetMachine &TM) const{
268 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
269
270 if (Kind.isText())
271 return getTextSection();
272
273 if (Kind.isBSS() && BSSSection != 0)
274 return BSSSection;
275
276 if (Kind.isReadOnly() && ReadOnlySection != 0)
277 return ReadOnlySection;
278
279 return getDataSection();
280 }
281
282 /// getSectionForConstant - Given a mergable constant with the
283 /// specified size and relocation information, return a section that it
284 /// should be placed in.
285 const MCSection *
getSectionForConstant(SectionKind Kind) const286 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
287 if (Kind.isReadOnly() && ReadOnlySection != 0)
288 return ReadOnlySection;
289
290 return DataSection;
291 }
292
293 /// getExprForDwarfGlobalReference - Return an MCExpr to use for a
294 /// reference to the specified global variable from exception
295 /// handling information.
296 const MCExpr *TargetLoweringObjectFile::
getExprForDwarfGlobalReference(const GlobalValue * GV,Mangler * Mang,MachineModuleInfo * MMI,unsigned Encoding,MCStreamer & Streamer) const297 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
298 MachineModuleInfo *MMI, unsigned Encoding,
299 MCStreamer &Streamer) const {
300 const MCSymbol *Sym = Mang->getSymbol(GV);
301 return getExprForDwarfReference(Sym, Encoding, Streamer);
302 }
303
304 const MCExpr *TargetLoweringObjectFile::
getExprForDwarfReference(const MCSymbol * Sym,unsigned Encoding,MCStreamer & Streamer) const305 getExprForDwarfReference(const MCSymbol *Sym, unsigned Encoding,
306 MCStreamer &Streamer) const {
307 const MCExpr *Res = MCSymbolRefExpr::Create(Sym, getContext());
308
309 switch (Encoding & 0x70) {
310 default:
311 report_fatal_error("We do not support this DWARF encoding yet!");
312 case dwarf::DW_EH_PE_absptr:
313 // Do nothing special
314 return Res;
315 case dwarf::DW_EH_PE_pcrel: {
316 // Emit a label to the streamer for the current position. This gives us
317 // .-foo addressing.
318 MCSymbol *PCSym = getContext().CreateTempSymbol();
319 Streamer.EmitLabel(PCSym);
320 const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
321 return MCBinaryExpr::CreateSub(Res, PC, getContext());
322 }
323 }
324 }
325
getPersonalityEncoding() const326 unsigned TargetLoweringObjectFile::getPersonalityEncoding() const {
327 return dwarf::DW_EH_PE_absptr;
328 }
329
getLSDAEncoding() const330 unsigned TargetLoweringObjectFile::getLSDAEncoding() const {
331 return dwarf::DW_EH_PE_absptr;
332 }
333
getFDEEncoding(bool CFI) const334 unsigned TargetLoweringObjectFile::getFDEEncoding(bool CFI) const {
335 return dwarf::DW_EH_PE_absptr;
336 }
337
getTTypeEncoding() const338 unsigned TargetLoweringObjectFile::getTTypeEncoding() const {
339 return dwarf::DW_EH_PE_absptr;
340 }
341
342