| 1 | //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// |
| 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 | #include "llvm/MC/MCContext.h" |
| 10 | #include "llvm/ADT/SmallString.h" |
| 11 | #include "llvm/ADT/SmallVector.h" |
| 12 | #include "llvm/ADT/StringMap.h" |
| 13 | #include "llvm/ADT/StringRef.h" |
| 14 | #include "llvm/ADT/Twine.h" |
| 15 | #include "llvm/BinaryFormat/COFF.h" |
| 16 | #include "llvm/BinaryFormat/ELF.h" |
| 17 | #include "llvm/BinaryFormat/GOFF.h" |
| 18 | #include "llvm/BinaryFormat/Wasm.h" |
| 19 | #include "llvm/BinaryFormat/XCOFF.h" |
| 20 | #include "llvm/MC/MCAsmInfo.h" |
| 21 | #include "llvm/MC/MCCodeView.h" |
| 22 | #include "llvm/MC/MCDwarf.h" |
| 23 | #include "llvm/MC/MCExpr.h" |
| 24 | #include "llvm/MC/MCInst.h" |
| 25 | #include "llvm/MC/MCLabel.h" |
| 26 | #include "llvm/MC/MCSectionCOFF.h" |
| 27 | #include "llvm/MC/MCSectionDXContainer.h" |
| 28 | #include "llvm/MC/MCSectionELF.h" |
| 29 | #include "llvm/MC/MCSectionGOFF.h" |
| 30 | #include "llvm/MC/MCSectionMachO.h" |
| 31 | #include "llvm/MC/MCSectionSPIRV.h" |
| 32 | #include "llvm/MC/MCSectionWasm.h" |
| 33 | #include "llvm/MC/MCSectionXCOFF.h" |
| 34 | #include "llvm/MC/MCStreamer.h" |
| 35 | #include "llvm/MC/MCSubtargetInfo.h" |
| 36 | #include "llvm/MC/MCSymbol.h" |
| 37 | #include "llvm/MC/MCSymbolCOFF.h" |
| 38 | #include "llvm/MC/MCSymbolELF.h" |
| 39 | #include "llvm/MC/MCSymbolGOFF.h" |
| 40 | #include "llvm/MC/MCSymbolMachO.h" |
| 41 | #include "llvm/MC/MCSymbolWasm.h" |
| 42 | #include "llvm/MC/MCSymbolXCOFF.h" |
| 43 | #include "llvm/MC/MCTargetOptions.h" |
| 44 | #include "llvm/MC/SectionKind.h" |
| 45 | #include "llvm/Support/EndianStream.h" |
| 46 | #include "llvm/Support/ErrorHandling.h" |
| 47 | #include "llvm/Support/MemoryBuffer.h" |
| 48 | #include "llvm/Support/Path.h" |
| 49 | #include "llvm/Support/SMLoc.h" |
| 50 | #include "llvm/Support/SourceMgr.h" |
| 51 | #include "llvm/Support/raw_ostream.h" |
| 52 | #include <cassert> |
| 53 | #include <cstdlib> |
| 54 | #include <optional> |
| 55 | #include <tuple> |
| 56 | #include <utility> |
| 57 | |
| 58 | using namespace llvm; |
| 59 | |
| 60 | static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &, |
| 61 | std::vector<const MDNode *> &) { |
| 62 | SMD.print(ProgName: nullptr, S&: errs()); |
| 63 | } |
| 64 | |
| 65 | MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo &mai, |
| 66 | const MCRegisterInfo &mri, const MCSubtargetInfo &msti, |
| 67 | const SourceMgr *mgr, bool DoAutoReset, |
| 68 | StringRef Swift5ReflSegmentName) |
| 69 | : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple), |
| 70 | SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler), |
| 71 | MAI(mai), MRI(&mri), MSTI(&msti), Symbols(Allocator), |
| 72 | InlineAsmUsedLabelNames(Allocator), |
| 73 | CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), |
| 74 | AutoReset(DoAutoReset) { |
| 75 | const MCTargetOptions &TO = getTargetOptions(); |
| 76 | SaveTempLabels = TO.MCSaveTempLabels; |
| 77 | if (SaveTempLabels) |
| 78 | setUseNamesOnTempLabels(true); |
| 79 | SecureLogFile = TO.AsSecureLogFile; |
| 80 | |
| 81 | if (SrcMgr && SrcMgr->getNumBuffers()) |
| 82 | MainFileName = std::string(SrcMgr->getMemoryBuffer(i: SrcMgr->getMainFileID()) |
| 83 | ->getBufferIdentifier()); |
| 84 | |
| 85 | switch (TheTriple.getObjectFormat()) { |
| 86 | case Triple::MachO: |
| 87 | Env = IsMachO; |
| 88 | break; |
| 89 | case Triple::COFF: |
| 90 | if (!TheTriple.isOSWindows() && !TheTriple.isUEFI()) { |
| 91 | reportFatalUsageError( |
| 92 | reason: "cannot initialize MC for non-Windows COFF object files" ); |
| 93 | } |
| 94 | |
| 95 | Env = IsCOFF; |
| 96 | break; |
| 97 | case Triple::ELF: |
| 98 | Env = IsELF; |
| 99 | break; |
| 100 | case Triple::Wasm: |
| 101 | Env = IsWasm; |
| 102 | break; |
| 103 | case Triple::XCOFF: |
| 104 | Env = IsXCOFF; |
| 105 | break; |
| 106 | case Triple::GOFF: |
| 107 | Env = IsGOFF; |
| 108 | break; |
| 109 | case Triple::DXContainer: |
| 110 | Env = IsDXContainer; |
| 111 | break; |
| 112 | case Triple::SPIRV: |
| 113 | Env = IsSPIRV; |
| 114 | break; |
| 115 | case Triple::UnknownObjectFormat: |
| 116 | report_fatal_error(reason: "Cannot initialize MC for unknown object file format." ); |
| 117 | break; |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | const MCTargetOptions &MCContext::getTargetOptions() const { |
| 122 | return MAI.getTargetOptions(); |
| 123 | } |
| 124 | |
| 125 | MCContext::~MCContext() { |
| 126 | if (AutoReset) |
| 127 | reset(); |
| 128 | |
| 129 | // NOTE: The symbols are all allocated out of a bump pointer allocator, |
| 130 | // we don't need to free them here. |
| 131 | } |
| 132 | |
| 133 | void MCContext::initInlineSourceManager() { |
| 134 | if (!InlineSrcMgr) |
| 135 | InlineSrcMgr.reset(p: new SourceMgr()); |
| 136 | } |
| 137 | |
| 138 | //===----------------------------------------------------------------------===// |
| 139 | // Module Lifetime Management |
| 140 | //===----------------------------------------------------------------------===// |
| 141 | |
| 142 | void MCContext::reset() { |
| 143 | SrcMgr = nullptr; |
| 144 | InlineSrcMgr.reset(); |
| 145 | LocInfos.clear(); |
| 146 | DiagHandler = defaultDiagHandler; |
| 147 | |
| 148 | // Call the destructors so the fragments are freed |
| 149 | COFFAllocator.DestroyAll(); |
| 150 | DXCAllocator.DestroyAll(); |
| 151 | ELFAllocator.DestroyAll(); |
| 152 | GOFFAllocator.DestroyAll(); |
| 153 | MachOAllocator.DestroyAll(); |
| 154 | WasmAllocator.DestroyAll(); |
| 155 | XCOFFAllocator.DestroyAll(); |
| 156 | MCInstAllocator.DestroyAll(); |
| 157 | SPIRVAllocator.DestroyAll(); |
| 158 | WasmSignatureAllocator.DestroyAll(); |
| 159 | |
| 160 | CVContext.reset(); |
| 161 | |
| 162 | MCSubtargetAllocator.DestroyAll(); |
| 163 | InlineAsmUsedLabelNames.clear(); |
| 164 | Symbols.clear(); |
| 165 | Allocator.Reset(); |
| 166 | Instances.clear(); |
| 167 | CompilationDir.clear(); |
| 168 | MainFileName.clear(); |
| 169 | MCDwarfLineTablesCUMap.clear(); |
| 170 | SectionsForRanges.clear(); |
| 171 | MCGenDwarfLabelEntries.clear(); |
| 172 | DwarfDebugFlags = StringRef(); |
| 173 | DwarfCompileUnitID = 0; |
| 174 | CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); |
| 175 | |
| 176 | MachOUniquingMap.clear(); |
| 177 | ELFUniquingMap.clear(); |
| 178 | GOFFUniquingMap.clear(); |
| 179 | COFFUniquingMap.clear(); |
| 180 | WasmUniquingMap.clear(); |
| 181 | XCOFFUniquingMap.clear(); |
| 182 | DXCUniquingMap.clear(); |
| 183 | |
| 184 | RelSecNames.clear(); |
| 185 | MacroMap.clear(); |
| 186 | ELFEntrySizeMap.clear(); |
| 187 | ELFSeenGenericMergeableSections.clear(); |
| 188 | |
| 189 | DwarfLocSeen = false; |
| 190 | GenDwarfForAssembly = false; |
| 191 | GenDwarfFileNumber = 0; |
| 192 | |
| 193 | HadError = false; |
| 194 | } |
| 195 | |
| 196 | //===----------------------------------------------------------------------===// |
| 197 | // MCInst Management |
| 198 | //===----------------------------------------------------------------------===// |
| 199 | |
| 200 | MCInst *MCContext::createMCInst() { |
| 201 | return new (MCInstAllocator.Allocate()) MCInst; |
| 202 | } |
| 203 | |
| 204 | //===----------------------------------------------------------------------===// |
| 205 | // Symbol Manipulation |
| 206 | //===----------------------------------------------------------------------===// |
| 207 | |
| 208 | MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { |
| 209 | SmallString<128> NameSV; |
| 210 | StringRef NameRef = Name.toStringRef(Out&: NameSV); |
| 211 | |
| 212 | assert(!NameRef.empty() && "Normal symbols cannot be unnamed!" ); |
| 213 | |
| 214 | MCSymbolTableEntry &Entry = getSymbolTableEntry(Name: NameRef); |
| 215 | if (!Entry.second.Symbol) { |
| 216 | bool IsRenamable = NameRef.starts_with(Prefix: MAI.getInternalSymbolPrefix()); |
| 217 | bool IsTemporary = IsRenamable && !SaveTempLabels; |
| 218 | if (!Entry.second.Used) { |
| 219 | Entry.second.Used = true; |
| 220 | Entry.second.Symbol = createSymbolImpl(Name: &Entry, IsTemporary); |
| 221 | } else { |
| 222 | assert(IsRenamable && "cannot rename non-private symbol" ); |
| 223 | // Slow path: we need to rename a temp symbol from the user. |
| 224 | Entry.second.Symbol = createRenamableSymbol(Name: NameRef, AlwaysAddSuffix: false, IsTemporary); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | return Entry.second.Symbol; |
| 229 | } |
| 230 | |
| 231 | MCSymbol *MCContext::parseSymbol(const Twine &Name) { |
| 232 | SmallString<128> SV; |
| 233 | StringRef NameRef = Name.toStringRef(Out&: SV); |
| 234 | if (NameRef.contains(C: '\\')) { |
| 235 | SV = NameRef; |
| 236 | size_t S = 0; |
| 237 | // Support escaped \\ and \" as in GNU Assembler. GAS issues a warning for |
| 238 | // other characters following \\, which we do not implement due to code |
| 239 | // structure. |
| 240 | for (size_t I = 0, E = SV.size(); I != E; ++I) { |
| 241 | char C = SV[I]; |
| 242 | if (C == '\\' && I + 1 != E) { |
| 243 | switch (SV[I + 1]) { |
| 244 | case '"': |
| 245 | case '\\': |
| 246 | C = SV[++I]; |
| 247 | break; |
| 248 | } |
| 249 | } |
| 250 | SV[S++] = C; |
| 251 | } |
| 252 | SV.resize(N: S); |
| 253 | NameRef = SV; |
| 254 | } |
| 255 | |
| 256 | return getOrCreateSymbol(Name: NameRef); |
| 257 | } |
| 258 | |
| 259 | MCSymbol *MCContext::getOrCreateFrameAllocSymbol(const Twine &FuncName, |
| 260 | unsigned Idx) { |
| 261 | return getOrCreateSymbol(Name: MAI.getInternalSymbolPrefix() + FuncName + |
| 262 | "$frame_escape_" + Twine(Idx)); |
| 263 | } |
| 264 | |
| 265 | MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(const Twine &FuncName) { |
| 266 | return getOrCreateSymbol(Name: MAI.getInternalSymbolPrefix() + FuncName + |
| 267 | "$parent_frame_offset" ); |
| 268 | } |
| 269 | |
| 270 | MCSymbol *MCContext::getOrCreateLSDASymbol(const Twine &FuncName) { |
| 271 | return getOrCreateSymbol(Name: MAI.getInternalSymbolPrefix() + "__ehtable$" + |
| 272 | FuncName); |
| 273 | } |
| 274 | |
| 275 | MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) { |
| 276 | return *Symbols.try_emplace(Key: Name, Args: MCSymbolTableValue{}).first; |
| 277 | } |
| 278 | |
| 279 | MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name, |
| 280 | bool IsTemporary) { |
| 281 | static_assert(std::is_trivially_destructible<MCSymbolCOFF>(), |
| 282 | "MCSymbol classes must be trivially destructible" ); |
| 283 | static_assert(std::is_trivially_destructible<MCSymbolELF>(), |
| 284 | "MCSymbol classes must be trivially destructible" ); |
| 285 | static_assert(std::is_trivially_destructible<MCSymbolMachO>(), |
| 286 | "MCSymbol classes must be trivially destructible" ); |
| 287 | static_assert(std::is_trivially_destructible<MCSymbolWasm>(), |
| 288 | "MCSymbol classes must be trivially destructible" ); |
| 289 | static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(), |
| 290 | "MCSymbol classes must be trivially destructible" ); |
| 291 | |
| 292 | switch (getObjectFileType()) { |
| 293 | case MCContext::IsCOFF: |
| 294 | return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); |
| 295 | case MCContext::IsELF: |
| 296 | return new (Name, *this) MCSymbolELF(Name, IsTemporary); |
| 297 | case MCContext::IsGOFF: |
| 298 | return new (Name, *this) MCSymbolGOFF(Name, IsTemporary); |
| 299 | case MCContext::IsMachO: |
| 300 | return new (Name, *this) MCSymbolMachO(Name, IsTemporary); |
| 301 | case MCContext::IsWasm: |
| 302 | return new (Name, *this) MCSymbolWasm(Name, IsTemporary); |
| 303 | case MCContext::IsXCOFF: |
| 304 | return createXCOFFSymbolImpl(Name, IsTemporary); |
| 305 | case MCContext::IsDXContainer: |
| 306 | break; |
| 307 | case MCContext::IsSPIRV: |
| 308 | return new (Name, *this) MCSymbol(Name, IsTemporary); |
| 309 | } |
| 310 | return new (Name, *this) MCSymbol(Name, IsTemporary); |
| 311 | } |
| 312 | |
| 313 | MCSymbol *MCContext::cloneSymbol(MCSymbol &Sym) { |
| 314 | MCSymbol *NewSym = nullptr; |
| 315 | auto Name = Sym.getNameEntryPtr(); |
| 316 | switch (getObjectFileType()) { |
| 317 | case MCContext::IsCOFF: |
| 318 | NewSym = |
| 319 | new (Name, *this) MCSymbolCOFF(static_cast<const MCSymbolCOFF &>(Sym)); |
| 320 | break; |
| 321 | case MCContext::IsELF: |
| 322 | NewSym = |
| 323 | new (Name, *this) MCSymbolELF(static_cast<const MCSymbolELF &>(Sym)); |
| 324 | break; |
| 325 | case MCContext::IsMachO: |
| 326 | NewSym = new (Name, *this) |
| 327 | MCSymbolMachO(static_cast<const MCSymbolMachO &>(Sym)); |
| 328 | break; |
| 329 | default: |
| 330 | reportFatalUsageError(reason: ".set redefinition is not supported" ); |
| 331 | break; |
| 332 | } |
| 333 | // Set the name and redirect the `Symbols` entry to `NewSym`. |
| 334 | NewSym->getNameEntryPtr() = Name; |
| 335 | const_cast<MCSymbolTableEntry *>(Name)->second.Symbol = NewSym; |
| 336 | // Ensure the next `registerSymbol` call will add the new symbol to `Symbols`. |
| 337 | NewSym->setIsRegistered(false); |
| 338 | |
| 339 | // Ensure the original symbol is not emitted to the symbol table. |
| 340 | Sym.IsTemporary = true; |
| 341 | return NewSym; |
| 342 | } |
| 343 | |
| 344 | MCSymbol *MCContext::createRenamableSymbol(const Twine &Name, |
| 345 | bool AlwaysAddSuffix, |
| 346 | bool IsTemporary) { |
| 347 | SmallString<128> NewName; |
| 348 | Name.toVector(Out&: NewName); |
| 349 | size_t NameLen = NewName.size(); |
| 350 | |
| 351 | MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name: NewName.str()); |
| 352 | MCSymbolTableEntry *EntryPtr = &NameEntry; |
| 353 | while (AlwaysAddSuffix || EntryPtr->second.Used) { |
| 354 | AlwaysAddSuffix = false; |
| 355 | |
| 356 | NewName.resize(N: NameLen); |
| 357 | raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++; |
| 358 | EntryPtr = &getSymbolTableEntry(Name: NewName.str()); |
| 359 | } |
| 360 | |
| 361 | EntryPtr->second.Used = true; |
| 362 | return createSymbolImpl(Name: EntryPtr, IsTemporary); |
| 363 | } |
| 364 | |
| 365 | MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) { |
| 366 | if (!UseNamesOnTempLabels) |
| 367 | return createSymbolImpl(Name: nullptr, /*IsTemporary=*/true); |
| 368 | return createRenamableSymbol(Name: MAI.getInternalSymbolPrefix() + Name, |
| 369 | AlwaysAddSuffix, /*IsTemporary=*/true); |
| 370 | } |
| 371 | |
| 372 | MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) { |
| 373 | return createRenamableSymbol(Name: MAI.getInternalSymbolPrefix() + Name, AlwaysAddSuffix: true, |
| 374 | /*IsTemporary=*/!SaveTempLabels); |
| 375 | } |
| 376 | |
| 377 | MCSymbol *MCContext::createBlockSymbol(const Twine &Name, bool AlwaysEmit) { |
| 378 | if (AlwaysEmit) |
| 379 | return getOrCreateSymbol(Name: MAI.getInternalSymbolPrefix() + Name); |
| 380 | |
| 381 | bool IsTemporary = !SaveTempLabels; |
| 382 | if (IsTemporary && !UseNamesOnTempLabels) |
| 383 | return createSymbolImpl(Name: nullptr, IsTemporary); |
| 384 | return createRenamableSymbol(Name: MAI.getInternalSymbolPrefix() + Name, |
| 385 | /*AlwaysAddSuffix=*/false, IsTemporary); |
| 386 | } |
| 387 | |
| 388 | MCSymbol *MCContext::createLinkerPrivateTempSymbol() { |
| 389 | return createLinkerPrivateSymbol(Name: "tmp" ); |
| 390 | } |
| 391 | |
| 392 | MCSymbol *MCContext::createLinkerPrivateSymbol(const Twine &Name) { |
| 393 | return createRenamableSymbol(Name: MAI.getLinkerPrivateGlobalPrefix() + Name, |
| 394 | /*AlwaysAddSuffix=*/true, |
| 395 | /*IsTemporary=*/false); |
| 396 | } |
| 397 | |
| 398 | MCSymbol *MCContext::createTempSymbol() { return createTempSymbol(Name: "tmp" ); } |
| 399 | |
| 400 | MCSymbol *MCContext::createNamedTempSymbol() { |
| 401 | return createNamedTempSymbol(Name: "tmp" ); |
| 402 | } |
| 403 | |
| 404 | MCSymbol *MCContext::createLocalSymbol(StringRef Name) { |
| 405 | MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name); |
| 406 | return createSymbolImpl(Name: &NameEntry, /*IsTemporary=*/false); |
| 407 | } |
| 408 | |
| 409 | unsigned MCContext::NextInstance(unsigned LocalLabelVal) { |
| 410 | MCLabel *&Label = Instances[LocalLabelVal]; |
| 411 | if (!Label) |
| 412 | Label = new (*this) MCLabel(0); |
| 413 | return Label->incInstance(); |
| 414 | } |
| 415 | |
| 416 | unsigned MCContext::GetInstance(unsigned LocalLabelVal) { |
| 417 | MCLabel *&Label = Instances[LocalLabelVal]; |
| 418 | if (!Label) |
| 419 | Label = new (*this) MCLabel(0); |
| 420 | return Label->getInstance(); |
| 421 | } |
| 422 | |
| 423 | MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, |
| 424 | unsigned Instance) { |
| 425 | MCSymbol *&Sym = LocalSymbols[std::make_pair(x&: LocalLabelVal, y&: Instance)]; |
| 426 | if (!Sym) |
| 427 | Sym = createNamedTempSymbol(); |
| 428 | return Sym; |
| 429 | } |
| 430 | |
| 431 | MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { |
| 432 | unsigned Instance = NextInstance(LocalLabelVal); |
| 433 | return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); |
| 434 | } |
| 435 | |
| 436 | MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, |
| 437 | bool Before) { |
| 438 | unsigned Instance = GetInstance(LocalLabelVal); |
| 439 | if (!Before) |
| 440 | ++Instance; |
| 441 | return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); |
| 442 | } |
| 443 | |
| 444 | // Create a section symbol, with a distinct one for each section of the same. |
| 445 | // The first symbol is used for assembly code references. |
| 446 | template <typename Symbol> |
| 447 | Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) { |
| 448 | Symbol *R; |
| 449 | auto &SymEntry = getSymbolTableEntry(Name: Section); |
| 450 | MCSymbol *Sym = SymEntry.second.Symbol; |
| 451 | if (Sym && Sym->isDefined() && |
| 452 | (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) { |
| 453 | reportError(L: SMLoc(), Msg: "invalid symbol redefinition" ); |
| 454 | // Don't reuse the conflicting symbol (e.g. an equated symbol from `x=0`) |
| 455 | // as a section symbol, which would cause a crash in changeSection. |
| 456 | Sym = nullptr; |
| 457 | } |
| 458 | // Use the symbol's index to track if it has been used as a section symbol. |
| 459 | // Set to -1 to catch potential bugs if misused as a symbol index. |
| 460 | if (Sym && Sym->getIndex() != -1u) { |
| 461 | R = static_cast<Symbol *>(Sym); |
| 462 | } else { |
| 463 | SymEntry.second.Used = true; |
| 464 | R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false); |
| 465 | if (!Sym) |
| 466 | SymEntry.second.Symbol = R; |
| 467 | } |
| 468 | // Mark as section symbol. |
| 469 | R->setIndex(-1u); |
| 470 | return R; |
| 471 | } |
| 472 | |
| 473 | MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { |
| 474 | SmallString<128> NameSV; |
| 475 | StringRef NameRef = Name.toStringRef(Out&: NameSV); |
| 476 | return Symbols.lookup(Key: NameRef).Symbol; |
| 477 | } |
| 478 | |
| 479 | void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym, |
| 480 | uint64_t Val) { |
| 481 | auto Symbol = getOrCreateSymbol(Name: Sym); |
| 482 | Streamer.emitAssignment(Symbol, Value: MCConstantExpr::create(Value: Val, Ctx&: *this)); |
| 483 | } |
| 484 | |
| 485 | void MCContext::registerInlineAsmLabel(MCSymbol *Sym) { |
| 486 | InlineAsmUsedLabelNames[Sym->getName()] = Sym; |
| 487 | } |
| 488 | |
| 489 | wasm::WasmSignature *MCContext::createWasmSignature() { |
| 490 | return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature; |
| 491 | } |
| 492 | |
| 493 | MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name, |
| 494 | bool IsTemporary) { |
| 495 | if (!Name) |
| 496 | return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary); |
| 497 | |
| 498 | StringRef OriginalName = Name->first(); |
| 499 | if (OriginalName.starts_with(Prefix: "._Renamed.." ) || |
| 500 | OriginalName.starts_with(Prefix: "_Renamed.." )) |
| 501 | reportError(L: SMLoc(), Msg: "invalid symbol name from source" ); |
| 502 | |
| 503 | if (MAI.isValidUnquotedName(Name: OriginalName)) |
| 504 | return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary); |
| 505 | |
| 506 | // Now we have a name that contains invalid character(s) for XCOFF symbol. |
| 507 | // Let's replace with something valid, but save the original name so that |
| 508 | // we could still use the original name in the symbol table. |
| 509 | SmallString<128> InvalidName(OriginalName); |
| 510 | |
| 511 | // If it's an entry point symbol, we will keep the '.' |
| 512 | // in front for the convention purpose. Otherwise, add "_Renamed.." |
| 513 | // as prefix to signal this is an renamed symbol. |
| 514 | const bool IsEntryPoint = InvalidName.starts_with(Prefix: "." ); |
| 515 | SmallString<128> ValidName = |
| 516 | StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed.." ); |
| 517 | |
| 518 | // Append the hex values of '_' and invalid characters with "_Renamed.."; |
| 519 | // at the same time replace invalid characters with '_'. |
| 520 | for (char &C : InvalidName) { |
| 521 | if (!MAI.isAcceptableChar(C) || C == '_') { |
| 522 | raw_svector_ostream(ValidName).write_hex(N: C); |
| 523 | C = '_'; |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | // Skip entry point symbol's '.' as we already have a '.' in front of |
| 528 | // "_Renamed". |
| 529 | if (IsEntryPoint) |
| 530 | ValidName.append(RHS: InvalidName.substr(Start: 1, N: InvalidName.size() - 1)); |
| 531 | else |
| 532 | ValidName.append(RHS: InvalidName); |
| 533 | |
| 534 | MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name: ValidName.str()); |
| 535 | assert(!NameEntry.second.Used && "This name is used somewhere else." ); |
| 536 | NameEntry.second.Used = true; |
| 537 | // Have the MCSymbol object itself refer to the copy of the string |
| 538 | // that is embedded in the symbol table entry. |
| 539 | MCSymbolXCOFF *XSym = |
| 540 | new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary); |
| 541 | XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(Name: OriginalName)); |
| 542 | return XSym; |
| 543 | } |
| 544 | |
| 545 | //===----------------------------------------------------------------------===// |
| 546 | // Section Management |
| 547 | //===----------------------------------------------------------------------===// |
| 548 | |
| 549 | MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, |
| 550 | unsigned TypeAndAttributes, |
| 551 | unsigned Reserved2, SectionKind Kind, |
| 552 | const char *BeginSymName) { |
| 553 | // We unique sections by their segment/section pair. The returned section |
| 554 | // may not have the same flags as the requested section, if so this should be |
| 555 | // diagnosed by the client as an error. |
| 556 | |
| 557 | // Form the name to look up. |
| 558 | assert(Section.size() <= 16 && "section name is too long" ); |
| 559 | assert(!memchr(Section.data(), '\0', Section.size()) && |
| 560 | "section name cannot contain NUL" ); |
| 561 | |
| 562 | // Do the lookup, if we have a hit, return it. |
| 563 | auto R = MachOUniquingMap.try_emplace(Key: (Segment + Twine(',') + Section).str()); |
| 564 | if (!R.second) |
| 565 | return R.first->second; |
| 566 | |
| 567 | MCSymbol *Begin = nullptr; |
| 568 | if (BeginSymName) |
| 569 | Begin = createTempSymbol(Name: BeginSymName, AlwaysAddSuffix: false); |
| 570 | |
| 571 | // Otherwise, return a new section. |
| 572 | StringRef Name = R.first->first(); |
| 573 | auto *Ret = new (MachOAllocator.Allocate()) |
| 574 | MCSectionMachO(Segment, Name.substr(Start: Name.size() - Section.size()), |
| 575 | TypeAndAttributes, Reserved2, Kind, Begin); |
| 576 | R.first->second = Ret; |
| 577 | return Ret; |
| 578 | } |
| 579 | |
| 580 | MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type, |
| 581 | unsigned Flags, |
| 582 | unsigned EntrySize, |
| 583 | const MCSymbolELF *Group, |
| 584 | bool Comdat, unsigned UniqueID, |
| 585 | const MCSymbolELF *LinkedToSym) { |
| 586 | auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section); |
| 587 | return new (ELFAllocator.Allocate()) MCSectionELF( |
| 588 | Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym); |
| 589 | } |
| 590 | |
| 591 | MCSectionELF * |
| 592 | MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, |
| 593 | unsigned EntrySize, const MCSymbolELF *Group, |
| 594 | const MCSectionELF *RelInfoSection) { |
| 595 | StringMap<bool>::iterator I; |
| 596 | bool Inserted; |
| 597 | std::tie(args&: I, args&: Inserted) = RelSecNames.insert(KV: std::make_pair(x: Name.str(), y: true)); |
| 598 | |
| 599 | return createELFSectionImpl( |
| 600 | Section: I->getKey(), Type, Flags, EntrySize, Group, Comdat: true, UniqueID: true, |
| 601 | LinkedToSym: static_cast<const MCSymbolELF *>(RelInfoSection->getBeginSymbol())); |
| 602 | } |
| 603 | |
| 604 | MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix, |
| 605 | const Twine &Suffix, unsigned Type, |
| 606 | unsigned Flags, |
| 607 | unsigned EntrySize) { |
| 608 | return getELFSection(Section: Prefix + "." + Suffix, Type, Flags, EntrySize, Group: Suffix, |
| 609 | /*IsComdat=*/true); |
| 610 | } |
| 611 | |
| 612 | MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, |
| 613 | unsigned Flags, unsigned EntrySize, |
| 614 | const Twine &Group, bool IsComdat, |
| 615 | unsigned UniqueID, |
| 616 | const MCSymbolELF *LinkedToSym) { |
| 617 | MCSymbolELF *GroupSym = nullptr; |
| 618 | if (!Group.isTriviallyEmpty() && !Group.str().empty()) |
| 619 | GroupSym = static_cast<MCSymbolELF *>(getOrCreateSymbol(Name: Group)); |
| 620 | |
| 621 | return getELFSection(Section, Type, Flags, EntrySize, Group: GroupSym, IsComdat, |
| 622 | UniqueID, LinkedToSym); |
| 623 | } |
| 624 | |
| 625 | MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, |
| 626 | unsigned Flags, unsigned EntrySize, |
| 627 | const MCSymbolELF *GroupSym, |
| 628 | bool IsComdat, unsigned UniqueID, |
| 629 | const MCSymbolELF *LinkedToSym) { |
| 630 | assert(!(LinkedToSym && LinkedToSym->getName().empty())); |
| 631 | |
| 632 | // Sections are differentiated by the quadruple (section_name, group_name, |
| 633 | // unique_id, link_to_symbol_name). Sections sharing the same quadruple are |
| 634 | // combined into one section. As an optimization, non-unique sections without |
| 635 | // group or linked-to symbol have a shorter unique-ing key. |
| 636 | std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair; |
| 637 | // Length of the section name, which are the first SectionLen bytes of the key |
| 638 | unsigned SectionLen; |
| 639 | if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) { |
| 640 | SmallString<128> Buffer; |
| 641 | Section.toVector(Out&: Buffer); |
| 642 | SectionLen = Buffer.size(); |
| 643 | Buffer.push_back(Elt: 0); // separator which cannot occur in the name |
| 644 | if (GroupSym) |
| 645 | Buffer.append(RHS: GroupSym->getName()); |
| 646 | Buffer.push_back(Elt: 0); // separator which cannot occur in the name |
| 647 | if (LinkedToSym) |
| 648 | Buffer.append(RHS: LinkedToSym->getName()); |
| 649 | support::endian::write(Out&: Buffer, V: UniqueID, E: endianness::native); |
| 650 | StringRef UniqueMapKey = StringRef(Buffer); |
| 651 | EntryNewPair = ELFUniquingMap.try_emplace(Key: UniqueMapKey); |
| 652 | } else if (!Section.isSingleStringRef()) { |
| 653 | SmallString<128> Buffer; |
| 654 | StringRef UniqueMapKey = Section.toStringRef(Out&: Buffer); |
| 655 | SectionLen = UniqueMapKey.size(); |
| 656 | EntryNewPair = ELFUniquingMap.try_emplace(Key: UniqueMapKey); |
| 657 | } else { |
| 658 | StringRef UniqueMapKey = Section.getSingleStringRef(); |
| 659 | SectionLen = UniqueMapKey.size(); |
| 660 | EntryNewPair = ELFUniquingMap.try_emplace(Key: UniqueMapKey); |
| 661 | } |
| 662 | |
| 663 | if (!EntryNewPair.second) |
| 664 | return EntryNewPair.first->second; |
| 665 | |
| 666 | StringRef CachedName = EntryNewPair.first->getKey().take_front(N: SectionLen); |
| 667 | |
| 668 | MCSectionELF *Result = |
| 669 | createELFSectionImpl(Section: CachedName, Type, Flags, EntrySize, Group: GroupSym, |
| 670 | Comdat: IsComdat, UniqueID, LinkedToSym); |
| 671 | EntryNewPair.first->second = Result; |
| 672 | |
| 673 | recordELFMergeableSectionInfo(SectionName: Result->getName(), Flags: Result->getFlags(), |
| 674 | UniqueID: Result->getUniqueID(), EntrySize: Result->getEntrySize()); |
| 675 | |
| 676 | return Result; |
| 677 | } |
| 678 | |
| 679 | MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group, |
| 680 | bool IsComdat) { |
| 681 | return createELFSectionImpl(Section: ".group" , Type: ELF::SHT_GROUP, Flags: 0, EntrySize: 4, Group, Comdat: IsComdat, |
| 682 | UniqueID: MCSection::NonUniqueID, LinkedToSym: nullptr); |
| 683 | } |
| 684 | |
| 685 | void MCContext::recordELFMergeableSectionInfo(StringRef SectionName, |
| 686 | unsigned Flags, unsigned UniqueID, |
| 687 | unsigned EntrySize) { |
| 688 | bool IsMergeable = Flags & ELF::SHF_MERGE; |
| 689 | if (UniqueID == MCSection::NonUniqueID) { |
| 690 | ELFSeenGenericMergeableSections.insert(V: SectionName); |
| 691 | // Minor performance optimization: avoid hash map lookup in |
| 692 | // isELFGenericMergeableSection, which will return true for SectionName. |
| 693 | IsMergeable = true; |
| 694 | } |
| 695 | |
| 696 | // For mergeable sections or non-mergeable sections with a generic mergeable |
| 697 | // section name we enter their Unique ID into the ELFEntrySizeMap so that |
| 698 | // compatible globals can be assigned to the same section. |
| 699 | |
| 700 | if (IsMergeable || isELFGenericMergeableSection(Name: SectionName)) { |
| 701 | ELFEntrySizeMap.insert(KV: std::make_pair( |
| 702 | x: std::make_tuple(args&: SectionName, args&: Flags, args&: EntrySize), y&: UniqueID)); |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) { |
| 707 | return SectionName.starts_with(Prefix: ".rodata.str" ) || |
| 708 | SectionName.starts_with(Prefix: ".rodata.cst" ); |
| 709 | } |
| 710 | |
| 711 | bool MCContext::isELFGenericMergeableSection(StringRef SectionName) { |
| 712 | return isELFImplicitMergeableSectionNamePrefix(SectionName) || |
| 713 | ELFSeenGenericMergeableSections.count(V: SectionName); |
| 714 | } |
| 715 | |
| 716 | std::optional<unsigned> |
| 717 | MCContext::getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags, |
| 718 | unsigned EntrySize) { |
| 719 | auto I = ELFEntrySizeMap.find(Val: std::make_tuple(args&: SectionName, args&: Flags, args&: EntrySize)); |
| 720 | return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second) |
| 721 | : std::nullopt; |
| 722 | } |
| 723 | |
| 724 | template <typename TAttr> |
| 725 | MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name, |
| 726 | TAttr Attributes, MCSection *Parent, |
| 727 | bool IsVirtual) { |
| 728 | std::string UniqueName(Name); |
| 729 | if (Parent) { |
| 730 | UniqueName.append(s: "/" ).append(svt: Parent->getName()); |
| 731 | if (auto *P = static_cast<MCSectionGOFF *>(Parent)->getParent()) |
| 732 | UniqueName.append(s: "/" ).append(svt: P->getName()); |
| 733 | } |
| 734 | // Do the lookup. If we don't have a hit, return a new section. |
| 735 | auto [Iter, Inserted] = GOFFUniquingMap.try_emplace(k: UniqueName); |
| 736 | if (!Inserted) |
| 737 | return Iter->second; |
| 738 | |
| 739 | StringRef CachedName = StringRef(Iter->first.c_str(), Name.size()); |
| 740 | MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate()) |
| 741 | MCSectionGOFF(CachedName, Kind, IsVirtual, Attributes, |
| 742 | static_cast<MCSectionGOFF *>(Parent)); |
| 743 | Iter->second = GOFFSection; |
| 744 | return GOFFSection; |
| 745 | } |
| 746 | |
| 747 | MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name, |
| 748 | GOFF::SDAttr SDAttributes) { |
| 749 | return getGOFFSection<GOFF::SDAttr>(Kind, Name, Attributes: SDAttributes, Parent: nullptr, |
| 750 | /*IsVirtual=*/true); |
| 751 | } |
| 752 | |
| 753 | MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name, |
| 754 | GOFF::EDAttr EDAttributes, |
| 755 | MCSection *Parent) { |
| 756 | return getGOFFSection<GOFF::EDAttr>( |
| 757 | Kind, Name, Attributes: EDAttributes, Parent, |
| 758 | /*IsVirtual=*/EDAttributes.BindAlgorithm == GOFF::ESD_BA_Merge); |
| 759 | } |
| 760 | |
| 761 | MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name, |
| 762 | GOFF::PRAttr PRAttributes, |
| 763 | MCSection *Parent) { |
| 764 | return getGOFFSection<GOFF::PRAttr>(Kind, Name, Attributes: PRAttributes, Parent, |
| 765 | /*IsVirtual=*/false); |
| 766 | } |
| 767 | |
| 768 | MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, |
| 769 | unsigned Characteristics, |
| 770 | StringRef COMDATSymName, int Selection, |
| 771 | unsigned UniqueID) { |
| 772 | MCSymbol *COMDATSymbol = nullptr; |
| 773 | if (!COMDATSymName.empty()) { |
| 774 | COMDATSymbol = getOrCreateSymbol(Name: COMDATSymName); |
| 775 | assert(COMDATSymbol && "COMDATSymbol is null" ); |
| 776 | COMDATSymName = COMDATSymbol->getName(); |
| 777 | // A non-associative COMDAT is considered to define the COMDAT symbol. Check |
| 778 | // the redefinition error. |
| 779 | if (Selection != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE && |
| 780 | COMDATSymbol->isDefined() && |
| 781 | (!COMDATSymbol->isInSection() || |
| 782 | static_cast<const MCSectionCOFF &>(COMDATSymbol->getSection()) |
| 783 | .getCOMDATSymbol() != COMDATSymbol)) |
| 784 | reportError(L: SMLoc(), Msg: "invalid symbol redefinition" ); |
| 785 | } |
| 786 | |
| 787 | // Do the lookup, if we have a hit, return it. |
| 788 | COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID}; |
| 789 | auto [Iter, Inserted] = COFFUniquingMap.try_emplace(k: T); |
| 790 | if (!Inserted) |
| 791 | return Iter->second; |
| 792 | |
| 793 | StringRef CachedName = Iter->first.SectionName; |
| 794 | MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section); |
| 795 | MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( |
| 796 | CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin); |
| 797 | Iter->second = Result; |
| 798 | Begin->setFragment(&Result->getDummyFragment()); |
| 799 | return Result; |
| 800 | } |
| 801 | |
| 802 | MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, |
| 803 | unsigned Characteristics) { |
| 804 | return getCOFFSection(Section, Characteristics, COMDATSymName: "" , Selection: 0, |
| 805 | UniqueID: MCSection::NonUniqueID); |
| 806 | } |
| 807 | |
| 808 | MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, |
| 809 | const MCSymbol *KeySym, |
| 810 | unsigned UniqueID) { |
| 811 | // Return the normal section if we don't have to be associative or unique. |
| 812 | if (!KeySym && UniqueID == MCSection::NonUniqueID) |
| 813 | return Sec; |
| 814 | |
| 815 | // If we have a key symbol, make an associative section with the same name and |
| 816 | // kind as the normal section. |
| 817 | unsigned Characteristics = Sec->getCharacteristics(); |
| 818 | if (KeySym) { |
| 819 | Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; |
| 820 | return getCOFFSection(Section: Sec->getName(), Characteristics, COMDATSymName: KeySym->getName(), |
| 821 | Selection: COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); |
| 822 | } |
| 823 | |
| 824 | return getCOFFSection(Section: Sec->getName(), Characteristics, COMDATSymName: "" , Selection: 0, UniqueID); |
| 825 | } |
| 826 | |
| 827 | MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K, |
| 828 | unsigned Flags, const Twine &Group, |
| 829 | unsigned UniqueID) { |
| 830 | MCSymbolWasm *GroupSym = nullptr; |
| 831 | if (!Group.isTriviallyEmpty() && !Group.str().empty()) { |
| 832 | GroupSym = static_cast<MCSymbolWasm *>(getOrCreateSymbol(Name: Group)); |
| 833 | GroupSym->setComdat(true); |
| 834 | if (K.isMetadata() && !GroupSym->getType().has_value()) { |
| 835 | // Comdat group symbol associated with a custom section is a section |
| 836 | // symbol (not a data symbol). |
| 837 | GroupSym->setType(wasm::WASM_SYMBOL_TYPE_SECTION); |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | return getWasmSection(Section, K, Flags, Group: GroupSym, UniqueID); |
| 842 | } |
| 843 | |
| 844 | MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind, |
| 845 | unsigned Flags, |
| 846 | const MCSymbolWasm *GroupSym, |
| 847 | unsigned UniqueID) { |
| 848 | StringRef Group = "" ; |
| 849 | if (GroupSym) |
| 850 | Group = GroupSym->getName(); |
| 851 | // Do the lookup, if we have a hit, return it. |
| 852 | auto IterBool = WasmUniquingMap.insert( |
| 853 | x: std::make_pair(x: WasmSectionKey{Section.str(), Group, UniqueID}, y: nullptr)); |
| 854 | auto &Entry = *IterBool.first; |
| 855 | if (!IterBool.second) |
| 856 | return Entry.second; |
| 857 | |
| 858 | StringRef CachedName = Entry.first.SectionName; |
| 859 | |
| 860 | MCSymbol *Begin = createRenamableSymbol(Name: CachedName, AlwaysAddSuffix: true, IsTemporary: false); |
| 861 | // Begin always has a different name than CachedName... see #48596. |
| 862 | getSymbolTableEntry(Name: Begin->getName()).second.Symbol = Begin; |
| 863 | static_cast<MCSymbolWasm *>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION); |
| 864 | |
| 865 | MCSectionWasm *Result = new (WasmAllocator.Allocate()) |
| 866 | MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin); |
| 867 | Entry.second = Result; |
| 868 | |
| 869 | return Result; |
| 870 | } |
| 871 | |
| 872 | bool MCContext::hasXCOFFSection(StringRef Section, |
| 873 | XCOFF::CsectProperties CsectProp) const { |
| 874 | return XCOFFUniquingMap.count( |
| 875 | x: XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0; |
| 876 | } |
| 877 | |
| 878 | MCSectionXCOFF *MCContext::getXCOFFSection( |
| 879 | StringRef Section, SectionKind Kind, |
| 880 | std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed, |
| 881 | std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) { |
| 882 | bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value(); |
| 883 | assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!" ); |
| 884 | |
| 885 | // Do the lookup. If we have a hit, return it. |
| 886 | auto IterBool = XCOFFUniquingMap.insert(x: std::make_pair( |
| 887 | x: IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags) |
| 888 | : XCOFFSectionKey(Section.str(), CsectProp->MappingClass), |
| 889 | y: nullptr)); |
| 890 | auto &Entry = *IterBool.first; |
| 891 | if (!IterBool.second) { |
| 892 | MCSectionXCOFF *ExistedEntry = Entry.second; |
| 893 | if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed) |
| 894 | report_fatal_error(reason: "section's multiply symbols policy does not match" ); |
| 895 | |
| 896 | return ExistedEntry; |
| 897 | } |
| 898 | |
| 899 | // Otherwise, return a new section. |
| 900 | StringRef CachedName = Entry.first.SectionName; |
| 901 | MCSymbolXCOFF *QualName = nullptr; |
| 902 | // Debug section don't have storage class attribute. |
| 903 | if (IsDwarfSec) |
| 904 | QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(Name: CachedName)); |
| 905 | else |
| 906 | QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol( |
| 907 | Name: CachedName + "[" + |
| 908 | XCOFF::getMappingClassString(SMC: CsectProp->MappingClass) + "]" )); |
| 909 | |
| 910 | // QualName->getUnqualifiedName() and CachedName are the same except when |
| 911 | // CachedName contains invalid character(s) such as '$' for an XCOFF symbol. |
| 912 | MCSectionXCOFF *Result = nullptr; |
| 913 | if (IsDwarfSec) |
| 914 | Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF( |
| 915 | QualName->getUnqualifiedName(), Kind, QualName, |
| 916 | *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed); |
| 917 | else |
| 918 | Result = new (XCOFFAllocator.Allocate()) |
| 919 | MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass, |
| 920 | CsectProp->Type, Kind, QualName, nullptr, CachedName, |
| 921 | MultiSymbolsAllowed); |
| 922 | |
| 923 | Entry.second = Result; |
| 924 | return Result; |
| 925 | } |
| 926 | |
| 927 | MCSectionSPIRV *MCContext::getSPIRVSection() { |
| 928 | MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV(); |
| 929 | return Result; |
| 930 | } |
| 931 | |
| 932 | MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section, |
| 933 | SectionKind K) { |
| 934 | // Do the lookup, if we have a hit, return it. |
| 935 | auto ItInsertedPair = DXCUniquingMap.try_emplace(Key: Section); |
| 936 | if (!ItInsertedPair.second) |
| 937 | return ItInsertedPair.first->second; |
| 938 | |
| 939 | auto MapIt = ItInsertedPair.first; |
| 940 | // Grab the name from the StringMap. Since the Section is going to keep a |
| 941 | // copy of this StringRef we need to make sure the underlying string stays |
| 942 | // alive as long as we need it. |
| 943 | StringRef Name = MapIt->first(); |
| 944 | MapIt->second = |
| 945 | new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr); |
| 946 | |
| 947 | // The first fragment will store the header |
| 948 | return MapIt->second; |
| 949 | } |
| 950 | |
| 951 | MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { |
| 952 | return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); |
| 953 | } |
| 954 | |
| 955 | void MCContext::addDebugPrefixMapEntry(const std::string &From, |
| 956 | const std::string &To) { |
| 957 | DebugPrefixMap.emplace_back(Args: From, Args: To); |
| 958 | } |
| 959 | |
| 960 | void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) { |
| 961 | for (const auto &[From, To] : llvm::reverse(C&: DebugPrefixMap)) |
| 962 | if (llvm::sys::path::replace_path_prefix(Path, OldPrefix: From, NewPrefix: To)) |
| 963 | break; |
| 964 | } |
| 965 | |
| 966 | void MCContext::RemapDebugPaths() { |
| 967 | const auto &DebugPrefixMap = this->DebugPrefixMap; |
| 968 | if (DebugPrefixMap.empty()) |
| 969 | return; |
| 970 | |
| 971 | // Remap compilation directory. |
| 972 | remapDebugPath(Path&: CompilationDir); |
| 973 | |
| 974 | // Remap MCDwarfDirs and RootFile.Name in all compilation units. |
| 975 | SmallString<256> P; |
| 976 | for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) { |
| 977 | for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) { |
| 978 | P = Dir; |
| 979 | remapDebugPath(Path&: P); |
| 980 | Dir = std::string(P); |
| 981 | } |
| 982 | |
| 983 | // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's |
| 984 | // DW_AT_decl_file for DWARF v5 generated for assembly source. |
| 985 | P = CUIDTablePair.second.getRootFile().Name; |
| 986 | remapDebugPath(Path&: P); |
| 987 | CUIDTablePair.second.getRootFile().Name = std::string(P); |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | //===----------------------------------------------------------------------===// |
| 992 | // Dwarf Management |
| 993 | //===----------------------------------------------------------------------===// |
| 994 | |
| 995 | EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const { |
| 996 | return getTargetOptions().EmitDwarfUnwind; |
| 997 | } |
| 998 | |
| 999 | bool MCContext::emitCompactUnwindNonCanonical() const { |
| 1000 | return getTargetOptions().EmitCompactUnwindNonCanonical; |
| 1001 | } |
| 1002 | |
| 1003 | void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) { |
| 1004 | // MCDwarf needs the root file as well as the compilation directory. |
| 1005 | // If we find a '.file 0' directive that will supersede these values. |
| 1006 | std::optional<MD5::MD5Result> Cksum; |
| 1007 | if (getDwarfVersion() >= 5) { |
| 1008 | MD5 Hash; |
| 1009 | MD5::MD5Result Sum; |
| 1010 | Hash.update(Str: Buffer); |
| 1011 | Hash.final(Result&: Sum); |
| 1012 | Cksum = Sum; |
| 1013 | } |
| 1014 | // Canonicalize the root filename. It cannot be empty, and should not |
| 1015 | // repeat the compilation dir. |
| 1016 | // The MCContext ctor initializes MainFileName to the name associated with |
| 1017 | // the SrcMgr's main file ID, which might be the same as InputFileName (and |
| 1018 | // possibly include directory components). |
| 1019 | // Or, MainFileName might have been overridden by a -main-file-name option, |
| 1020 | // which is supposed to be just a base filename with no directory component. |
| 1021 | // So, if the InputFileName and MainFileName are not equal, assume |
| 1022 | // MainFileName is a substitute basename and replace the last component. |
| 1023 | SmallString<1024> FileNameBuf = InputFileName; |
| 1024 | if (FileNameBuf.empty() || FileNameBuf == "-" ) |
| 1025 | FileNameBuf = "<stdin>" ; |
| 1026 | if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) { |
| 1027 | llvm::sys::path::remove_filename(path&: FileNameBuf); |
| 1028 | llvm::sys::path::append(path&: FileNameBuf, a: getMainFileName()); |
| 1029 | } |
| 1030 | StringRef FileName = FileNameBuf; |
| 1031 | if (FileName.consume_front(Prefix: getCompilationDir())) |
| 1032 | if (llvm::sys::path::is_separator(value: FileName.front())) |
| 1033 | FileName = FileName.drop_front(); |
| 1034 | assert(!FileName.empty()); |
| 1035 | setMCLineTableRootFile( |
| 1036 | /*CUID=*/0, CompilationDir: getCompilationDir(), Filename: FileName, Checksum: Cksum, Source: std::nullopt); |
| 1037 | } |
| 1038 | |
| 1039 | /// getDwarfFile - takes a file name and number to place in the dwarf file and |
| 1040 | /// directory tables. If the file number has already been allocated it is an |
| 1041 | /// error and zero is returned and the client reports the error, else the |
| 1042 | /// allocated file number is returned. The file numbers may be in any order. |
| 1043 | Expected<unsigned> |
| 1044 | MCContext::getDwarfFile(StringRef Directory, StringRef FileName, |
| 1045 | unsigned FileNumber, |
| 1046 | std::optional<MD5::MD5Result> Checksum, |
| 1047 | std::optional<StringRef> Source, unsigned CUID) { |
| 1048 | MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; |
| 1049 | return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, |
| 1050 | FileNumber); |
| 1051 | } |
| 1052 | |
| 1053 | /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it |
| 1054 | /// currently is assigned and false otherwise. |
| 1055 | bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { |
| 1056 | const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID); |
| 1057 | if (FileNumber == 0) |
| 1058 | return getDwarfVersion() >= 5; |
| 1059 | if (FileNumber >= LineTable.getMCDwarfFiles().size()) |
| 1060 | return false; |
| 1061 | |
| 1062 | return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty(); |
| 1063 | } |
| 1064 | |
| 1065 | /// Remove empty sections from SectionsForRanges, to avoid generating |
| 1066 | /// useless debug info for them. |
| 1067 | void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { |
| 1068 | SectionsForRanges.remove_if( |
| 1069 | P: [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(Sec&: *Sec); }); |
| 1070 | } |
| 1071 | |
| 1072 | CodeViewContext &MCContext::getCVContext() { |
| 1073 | if (!CVContext) |
| 1074 | CVContext.reset(p: new CodeViewContext(this)); |
| 1075 | return *CVContext; |
| 1076 | } |
| 1077 | |
| 1078 | //===----------------------------------------------------------------------===// |
| 1079 | // Error Reporting |
| 1080 | //===----------------------------------------------------------------------===// |
| 1081 | |
| 1082 | void MCContext::diagnose(const SMDiagnostic &SMD) { |
| 1083 | assert(DiagHandler && "MCContext::DiagHandler is not set" ); |
| 1084 | bool UseInlineSrcMgr = false; |
| 1085 | const SourceMgr *SMP = nullptr; |
| 1086 | if (SrcMgr) { |
| 1087 | SMP = SrcMgr; |
| 1088 | } else if (InlineSrcMgr) { |
| 1089 | SMP = InlineSrcMgr.get(); |
| 1090 | UseInlineSrcMgr = true; |
| 1091 | } else |
| 1092 | llvm_unreachable("Either SourceMgr should be available" ); |
| 1093 | DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos); |
| 1094 | } |
| 1095 | |
| 1096 | void MCContext::reportCommon( |
| 1097 | SMLoc Loc, |
| 1098 | std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) { |
| 1099 | // * MCContext::SrcMgr is null when the MC layer emits machine code for input |
| 1100 | // other than assembly file, say, for .c/.cpp/.ll/.bc. |
| 1101 | // * MCContext::InlineSrcMgr is null when the inline asm is not used. |
| 1102 | // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr |
| 1103 | // and MCContext::InlineSrcMgr are null. |
| 1104 | SourceMgr SM; |
| 1105 | const SourceMgr *SMP = &SM; |
| 1106 | bool UseInlineSrcMgr = false; |
| 1107 | |
| 1108 | // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr. |
| 1109 | // For MC-only execution, only SrcMgr is used; |
| 1110 | // For non MC-only execution, InlineSrcMgr is only ctor'd if there is |
| 1111 | // inline asm in the IR. |
| 1112 | if (Loc.isValid()) { |
| 1113 | if (SrcMgr) { |
| 1114 | SMP = SrcMgr; |
| 1115 | } else if (InlineSrcMgr) { |
| 1116 | SMP = InlineSrcMgr.get(); |
| 1117 | UseInlineSrcMgr = true; |
| 1118 | } else |
| 1119 | llvm_unreachable("Either SourceMgr should be available" ); |
| 1120 | } |
| 1121 | |
| 1122 | SMDiagnostic D; |
| 1123 | GetMessage(D, SMP); |
| 1124 | DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos); |
| 1125 | } |
| 1126 | |
| 1127 | void MCContext::reportError(SMLoc Loc, const Twine &Msg) { |
| 1128 | HadError = true; |
| 1129 | reportCommon(Loc, GetMessage: [&](SMDiagnostic &D, const SourceMgr *SMP) { |
| 1130 | D = SMP->GetMessage(Loc, Kind: SourceMgr::DK_Error, Msg); |
| 1131 | }); |
| 1132 | } |
| 1133 | |
| 1134 | void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) { |
| 1135 | if (getTargetOptions().MCNoWarn) |
| 1136 | return; |
| 1137 | if (getTargetOptions().MCFatalWarnings) { |
| 1138 | reportError(Loc, Msg); |
| 1139 | } else { |
| 1140 | reportCommon(Loc, GetMessage: [&](SMDiagnostic &D, const SourceMgr *SMP) { |
| 1141 | D = SMP->GetMessage(Loc, Kind: SourceMgr::DK_Warning, Msg); |
| 1142 | }); |
| 1143 | } |
| 1144 | } |
| 1145 | |