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