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/CodeGen/TargetLoweringObjectFile.h" 16 #include "llvm/BinaryFormat/Dwarf.h" 17 #include "llvm/CodeGen/TargetLowering.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/DataLayout.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/GlobalVariable.h" 23 #include "llvm/IR/Mangler.h" 24 #include "llvm/MC/MCContext.h" 25 #include "llvm/MC/MCExpr.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/MC/MCSymbol.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 // `Initialize` can be called more than once. 45 delete Mang; 46 Mang = new Mangler(); 47 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx, 48 TM.getCodeModel() == CodeModel::Large); 49 } 50 51 TargetLoweringObjectFile::~TargetLoweringObjectFile() { 52 delete Mang; 53 } 54 55 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) { 56 const Constant *C = GV->getInitializer(); 57 58 // Must have zero initializer. 59 if (!C->isNullValue()) 60 return false; 61 62 // Leave constant zeros in readonly constant sections, so they can be shared. 63 if (GV->isConstant()) 64 return false; 65 66 // If the global has an explicit section specified, don't put it in BSS. 67 if (GV->hasSection()) 68 return false; 69 70 // If -nozero-initialized-in-bss is specified, don't ever use BSS. 71 if (NoZerosInBSS) 72 return false; 73 74 // Otherwise, put it in BSS! 75 return true; 76 } 77 78 /// IsNullTerminatedString - Return true if the specified constant (which is 79 /// known to have a type that is an array of 1/2/4 byte elements) ends with a 80 /// nul value and contains no other nuls in it. Note that this is more general 81 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings. 82 static bool IsNullTerminatedString(const Constant *C) { 83 // First check: is we have constant array terminated with zero 84 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) { 85 unsigned NumElts = CDS->getNumElements(); 86 assert(NumElts != 0 && "Can't have an empty CDS"); 87 88 if (CDS->getElementAsInteger(NumElts-1) != 0) 89 return false; // Not null terminated. 90 91 // Verify that the null doesn't occur anywhere else in the string. 92 for (unsigned i = 0; i != NumElts-1; ++i) 93 if (CDS->getElementAsInteger(i) == 0) 94 return false; 95 return true; 96 } 97 98 // Another possibility: [1 x i8] zeroinitializer 99 if (isa<ConstantAggregateZero>(C)) 100 return cast<ArrayType>(C->getType())->getNumElements() == 1; 101 102 return false; 103 } 104 105 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase( 106 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const { 107 assert(!Suffix.empty()); 108 109 SmallString<60> NameStr; 110 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix(); 111 TM.getNameWithPrefix(NameStr, GV, *Mang); 112 NameStr.append(Suffix.begin(), Suffix.end()); 113 return Ctx->getOrCreateSymbol(NameStr); 114 } 115 116 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol( 117 const GlobalValue *GV, const TargetMachine &TM, 118 MachineModuleInfo *MMI) const { 119 return TM.getSymbol(GV); 120 } 121 122 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer, 123 const DataLayout &, 124 const MCSymbol *Sym) const { 125 } 126 127 128 /// getKindForGlobal - This is a top-level target-independent classifier for 129 /// a global variable. Given an global variable and information from TM, it 130 /// classifies the global in a variety of ways that make various target 131 /// implementations simpler. The target implementation is free to ignore this 132 /// extra info of course. 133 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO, 134 const TargetMachine &TM){ 135 assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() && 136 "Can only be used for global definitions"); 137 138 Reloc::Model ReloModel = TM.getRelocationModel(); 139 140 // Early exit - functions should be always in text sections. 141 const auto *GVar = dyn_cast<GlobalVariable>(GO); 142 if (!GVar) 143 return SectionKind::getText(); 144 145 // Handle thread-local data first. 146 if (GVar->isThreadLocal()) { 147 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) 148 return SectionKind::getThreadBSS(); 149 return SectionKind::getThreadData(); 150 } 151 152 // Variables with common linkage always get classified as common. 153 if (GVar->hasCommonLinkage()) 154 return SectionKind::getCommon(); 155 156 // Variable can be easily put to BSS section. 157 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) { 158 if (GVar->hasLocalLinkage()) 159 return SectionKind::getBSSLocal(); 160 else if (GVar->hasExternalLinkage()) 161 return SectionKind::getBSSExtern(); 162 return SectionKind::getBSS(); 163 } 164 165 const Constant *C = GVar->getInitializer(); 166 167 // If the global is marked constant, we can put it into a mergable section, 168 // a mergable string section, or general .data if it contains relocations. 169 if (GVar->isConstant()) { 170 // If the initializer for the global contains something that requires a 171 // relocation, then we may have to drop this into a writable data section 172 // even though it is marked const. 173 if (!C->needsRelocation()) { 174 // If the global is required to have a unique address, it can't be put 175 // into a mergable section: just drop it into the general read-only 176 // section instead. 177 if (!GVar->hasGlobalUnnamedAddr()) 178 return SectionKind::getReadOnly(); 179 180 // If initializer is a null-terminated string, put it in a "cstring" 181 // section of the right width. 182 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) { 183 if (IntegerType *ITy = 184 dyn_cast<IntegerType>(ATy->getElementType())) { 185 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 || 186 ITy->getBitWidth() == 32) && 187 IsNullTerminatedString(C)) { 188 if (ITy->getBitWidth() == 8) 189 return SectionKind::getMergeable1ByteCString(); 190 if (ITy->getBitWidth() == 16) 191 return SectionKind::getMergeable2ByteCString(); 192 193 assert(ITy->getBitWidth() == 32 && "Unknown width"); 194 return SectionKind::getMergeable4ByteCString(); 195 } 196 } 197 } 198 199 // Otherwise, just drop it into a mergable constant section. If we have 200 // a section for this size, use it, otherwise use the arbitrary sized 201 // mergable section. 202 switch ( 203 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) { 204 case 4: return SectionKind::getMergeableConst4(); 205 case 8: return SectionKind::getMergeableConst8(); 206 case 16: return SectionKind::getMergeableConst16(); 207 case 32: return SectionKind::getMergeableConst32(); 208 default: 209 return SectionKind::getReadOnly(); 210 } 211 212 } else { 213 // In static, ROPI and RWPI relocation models, the linker will resolve 214 // all addresses, so the relocation entries will actually be constants by 215 // the time the app starts up. However, we can't put this into a 216 // mergable section, because the linker doesn't take relocations into 217 // consideration when it tries to merge entries in the section. 218 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI || 219 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI) 220 return SectionKind::getReadOnly(); 221 222 // Otherwise, the dynamic linker needs to fix it up, put it in the 223 // writable data.rel section. 224 return SectionKind::getReadOnlyWithRel(); 225 } 226 } 227 228 // Okay, this isn't a constant. 229 return SectionKind::getData(); 230 } 231 232 /// This method computes the appropriate section to emit the specified global 233 /// variable or function definition. This should not be passed external (or 234 /// available externally) globals. 235 MCSection *TargetLoweringObjectFile::SectionForGlobal( 236 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 237 // Select section name. 238 if (GO->hasSection()) 239 return getExplicitSectionGlobal(GO, Kind, TM); 240 241 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 242 auto Attrs = GVar->getAttributes(); 243 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) || 244 (Attrs.hasAttribute("data-section") && Kind.isData()) || 245 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) { 246 return getExplicitSectionGlobal(GO, Kind, TM); 247 } 248 } 249 250 if (auto *F = dyn_cast<Function>(GO)) { 251 if (F->hasFnAttribute("implicit-section-name")) 252 return getExplicitSectionGlobal(GO, Kind, TM); 253 } 254 255 // Use default section depending on the 'type' of global 256 return SelectSectionForGlobal(GO, Kind, TM); 257 } 258 259 MCSection *TargetLoweringObjectFile::getSectionForJumpTable( 260 const Function &F, const TargetMachine &TM) const { 261 unsigned Align = 0; 262 return getSectionForConstant(F.getParent()->getDataLayout(), 263 SectionKind::getReadOnly(), /*C=*/nullptr, 264 Align); 265 } 266 267 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection( 268 bool UsesLabelDifference, const Function &F) const { 269 // In PIC mode, we need to emit the jump table to the same section as the 270 // function body itself, otherwise the label differences won't make sense. 271 // FIXME: Need a better predicate for this: what about custom entries? 272 if (UsesLabelDifference) 273 return true; 274 275 // We should also do if the section name is NULL or function is declared 276 // in discardable section 277 // FIXME: this isn't the right predicate, should be based on the MCSection 278 // for the function. 279 return F.isWeakForLinker(); 280 } 281 282 /// Given a mergable constant with the specified size and relocation 283 /// information, return a section that it should be placed in. 284 MCSection *TargetLoweringObjectFile::getSectionForConstant( 285 const DataLayout &DL, SectionKind Kind, const Constant *C, 286 unsigned &Align) const { 287 if (Kind.isReadOnly() && ReadOnlySection != nullptr) 288 return ReadOnlySection; 289 290 return DataSection; 291 } 292 293 /// getTTypeGlobalReference - Return an MCExpr to use for a 294 /// reference to the specified global variable from exception 295 /// handling information. 296 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference( 297 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 298 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 299 const MCSymbolRefExpr *Ref = 300 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); 301 302 return getTTypeReference(Ref, Encoding, Streamer); 303 } 304 305 const MCExpr *TargetLoweringObjectFile:: 306 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, 307 MCStreamer &Streamer) const { 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 Sym; 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(Sym, PC, getContext()); 321 } 322 } 323 } 324 325 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const { 326 // FIXME: It's not clear what, if any, default this should have - perhaps a 327 // null return could mean 'no location' & we should just do that here. 328 return MCSymbolRefExpr::create(Sym, *Ctx); 329 } 330 331 void TargetLoweringObjectFile::getNameWithPrefix( 332 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 333 const TargetMachine &TM) const { 334 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false); 335 } 336