1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements classes used to handle lowerings specific to common 10 // object file formats. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Target/TargetLoweringObjectFile.h" 15 #include "llvm/BinaryFormat/Dwarf.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/MCContext.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCStreamer.h" 25 #include "llvm/MC/MCSymbol.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include "llvm/Target/TargetMachine.h" 29 #include "llvm/Target/TargetOptions.h" 30 using namespace llvm; 31 32 //===----------------------------------------------------------------------===// 33 // Generic Code 34 //===----------------------------------------------------------------------===// 35 36 /// Initialize - this method must be called before any actual lowering is 37 /// done. This specifies the current context for codegen, and gives the 38 /// lowering implementations a chance to set up their default sections. 39 void TargetLoweringObjectFile::Initialize(MCContext &ctx, 40 const TargetMachine &TM) { 41 // `Initialize` can be called more than once. 42 delete Mang; 43 Mang = new Mangler(); 44 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), ctx, 45 TM.getCodeModel() == CodeModel::Large); 46 47 // Reset various EH DWARF encodings. 48 PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr; 49 CallSiteEncoding = dwarf::DW_EH_PE_uleb128; 50 } 51 52 TargetLoweringObjectFile::~TargetLoweringObjectFile() { 53 delete Mang; 54 } 55 56 static bool isNullOrUndef(const Constant *C) { 57 // Check that the constant isn't all zeros or undefs. 58 if (C->isNullValue() || isa<UndefValue>(C)) 59 return true; 60 if (!isa<ConstantAggregate>(C)) 61 return false; 62 for (auto Operand : C->operand_values()) { 63 if (!isNullOrUndef(cast<Constant>(Operand))) 64 return false; 65 } 66 return true; 67 } 68 69 static bool isSuitableForBSS(const GlobalVariable *GV) { 70 const Constant *C = GV->getInitializer(); 71 72 // Must have zero initializer. 73 if (!isNullOrUndef(C)) 74 return false; 75 76 // Leave constant zeros in readonly constant sections, so they can be shared. 77 if (GV->isConstant()) 78 return false; 79 80 // If the global has an explicit section specified, don't put it in BSS. 81 if (GV->hasSection()) 82 return false; 83 84 // Otherwise, put it in BSS! 85 return true; 86 } 87 88 /// IsNullTerminatedString - Return true if the specified constant (which is 89 /// known to have a type that is an array of 1/2/4 byte elements) ends with a 90 /// nul value and contains no other nuls in it. Note that this is more general 91 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings. 92 static bool IsNullTerminatedString(const Constant *C) { 93 // First check: is we have constant array terminated with zero 94 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) { 95 unsigned NumElts = CDS->getNumElements(); 96 assert(NumElts != 0 && "Can't have an empty CDS"); 97 98 if (CDS->getElementAsInteger(NumElts-1) != 0) 99 return false; // Not null terminated. 100 101 // Verify that the null doesn't occur anywhere else in the string. 102 for (unsigned i = 0; i != NumElts-1; ++i) 103 if (CDS->getElementAsInteger(i) == 0) 104 return false; 105 return true; 106 } 107 108 // Another possibility: [1 x i8] zeroinitializer 109 if (isa<ConstantAggregateZero>(C)) 110 return cast<ArrayType>(C->getType())->getNumElements() == 1; 111 112 return false; 113 } 114 115 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase( 116 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const { 117 assert(!Suffix.empty()); 118 119 SmallString<60> NameStr; 120 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix(); 121 TM.getNameWithPrefix(NameStr, GV, *Mang); 122 NameStr.append(Suffix.begin(), Suffix.end()); 123 return getContext().getOrCreateSymbol(NameStr); 124 } 125 126 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol( 127 const GlobalValue *GV, const TargetMachine &TM, 128 MachineModuleInfo *MMI) const { 129 return TM.getSymbol(GV); 130 } 131 132 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer, 133 const DataLayout &, 134 const MCSymbol *Sym) const { 135 } 136 137 138 /// getKindForGlobal - This is a top-level target-independent classifier for 139 /// a global object. Given a global variable and information from the TM, this 140 /// function classifies the global in a target independent manner. This function 141 /// may be overridden by the target implementation. 142 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO, 143 const TargetMachine &TM){ 144 assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() && 145 "Can only be used for global definitions"); 146 147 // Functions are classified as text sections. 148 if (isa<Function>(GO)) 149 return SectionKind::getText(); 150 151 // Basic blocks are classified as text sections. 152 if (isa<BasicBlock>(GO)) 153 return SectionKind::getText(); 154 155 // Global variables require more detailed analysis. 156 const auto *GVar = cast<GlobalVariable>(GO); 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 // Most non-mergeable zero data can be put in the BSS section unless otherwise 170 // specified. 171 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) { 172 if (GVar->hasLocalLinkage()) 173 return SectionKind::getBSSLocal(); 174 else if (GVar->hasExternalLinkage()) 175 return SectionKind::getBSSExtern(); 176 return SectionKind::getBSS(); 177 } 178 179 // If the global is marked constant, we can put it into a mergable section, 180 // a mergable string section, or general .data if it contains relocations. 181 if (GVar->isConstant()) { 182 // If the initializer for the global contains something that requires a 183 // relocation, then we may have to drop this into a writable data section 184 // even though it is marked const. 185 const Constant *C = GVar->getInitializer(); 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 Reloc::Model ReloModel = TM.getRelocationModel(); 232 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI || 233 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI) 234 return SectionKind::getReadOnly(); 235 236 // Otherwise, the dynamic linker needs to fix it up, put it in the 237 // writable data.rel section. 238 return SectionKind::getReadOnlyWithRel(); 239 } 240 } 241 242 // Okay, this isn't a constant. 243 return SectionKind::getData(); 244 } 245 246 /// This method computes the appropriate section to emit the specified global 247 /// variable or function definition. This should not be passed external (or 248 /// available externally) globals. 249 MCSection *TargetLoweringObjectFile::SectionForGlobal( 250 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 251 // Select section name. 252 if (GO->hasSection()) 253 return getExplicitSectionGlobal(GO, Kind, TM); 254 255 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 256 auto Attrs = GVar->getAttributes(); 257 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) || 258 (Attrs.hasAttribute("data-section") && Kind.isData()) || 259 (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) || 260 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) { 261 return getExplicitSectionGlobal(GO, Kind, TM); 262 } 263 } 264 265 if (auto *F = dyn_cast<Function>(GO)) { 266 if (F->hasFnAttribute("implicit-section-name")) 267 return getExplicitSectionGlobal(GO, Kind, TM); 268 } 269 270 // Use default section depending on the 'type' of global 271 return SelectSectionForGlobal(GO, Kind, TM); 272 } 273 274 MCSection *TargetLoweringObjectFile::getSectionForJumpTable( 275 const Function &F, const TargetMachine &TM) const { 276 unsigned Align = 0; 277 return getSectionForConstant(F.getParent()->getDataLayout(), 278 SectionKind::getReadOnly(), /*C=*/nullptr, 279 Align); 280 } 281 282 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection( 283 bool UsesLabelDifference, const Function &F) const { 284 // In PIC mode, we need to emit the jump table to the same section as the 285 // function body itself, otherwise the label differences won't make sense. 286 // FIXME: Need a better predicate for this: what about custom entries? 287 if (UsesLabelDifference) 288 return true; 289 290 // We should also do if the section name is NULL or function is declared 291 // in discardable section 292 // FIXME: this isn't the right predicate, should be based on the MCSection 293 // for the function. 294 return F.isWeakForLinker(); 295 } 296 297 /// Given a mergable constant with the specified size and relocation 298 /// information, return a section that it should be placed in. 299 MCSection *TargetLoweringObjectFile::getSectionForConstant( 300 const DataLayout &DL, SectionKind Kind, const Constant *C, 301 unsigned &Align) const { 302 if (Kind.isReadOnly() && ReadOnlySection != nullptr) 303 return ReadOnlySection; 304 305 return DataSection; 306 } 307 308 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock( 309 const Function &F, const MachineBasicBlock &MBB, 310 const TargetMachine &TM) const { 311 return nullptr; 312 } 313 314 /// getTTypeGlobalReference - Return an MCExpr to use for a 315 /// reference to the specified global variable from exception 316 /// handling information. 317 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference( 318 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 319 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 320 const MCSymbolRefExpr *Ref = 321 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); 322 323 return getTTypeReference(Ref, Encoding, Streamer); 324 } 325 326 const MCExpr *TargetLoweringObjectFile:: 327 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, 328 MCStreamer &Streamer) const { 329 switch (Encoding & 0x70) { 330 default: 331 report_fatal_error("We do not support this DWARF encoding yet!"); 332 case dwarf::DW_EH_PE_absptr: 333 // Do nothing special 334 return Sym; 335 case dwarf::DW_EH_PE_pcrel: { 336 // Emit a label to the streamer for the current position. This gives us 337 // .-foo addressing. 338 MCSymbol *PCSym = getContext().createTempSymbol(); 339 Streamer.emitLabel(PCSym); 340 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext()); 341 return MCBinaryExpr::createSub(Sym, PC, getContext()); 342 } 343 } 344 } 345 346 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const { 347 // FIXME: It's not clear what, if any, default this should have - perhaps a 348 // null return could mean 'no location' & we should just do that here. 349 return MCSymbolRefExpr::create(Sym, getContext()); 350 } 351 352 void TargetLoweringObjectFile::getNameWithPrefix( 353 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 354 const TargetMachine &TM) const { 355 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false); 356 } 357