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