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