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