Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/MC/MCContext.cpp
Line
Count
Source (jump to first uncovered line)
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/Optional.h"
11
#include "llvm/ADT/SmallString.h"
12
#include "llvm/ADT/SmallVector.h"
13
#include "llvm/ADT/StringMap.h"
14
#include "llvm/ADT/StringRef.h"
15
#include "llvm/ADT/Twine.h"
16
#include "llvm/BinaryFormat/COFF.h"
17
#include "llvm/BinaryFormat/ELF.h"
18
#include "llvm/MC/MCAsmInfo.h"
19
#include "llvm/MC/MCCodeView.h"
20
#include "llvm/MC/MCDwarf.h"
21
#include "llvm/MC/MCExpr.h"
22
#include "llvm/MC/MCFragment.h"
23
#include "llvm/MC/MCLabel.h"
24
#include "llvm/MC/MCObjectFileInfo.h"
25
#include "llvm/MC/MCSectionCOFF.h"
26
#include "llvm/MC/MCSectionELF.h"
27
#include "llvm/MC/MCSectionMachO.h"
28
#include "llvm/MC/MCSectionWasm.h"
29
#include "llvm/MC/MCSectionXCOFF.h"
30
#include "llvm/MC/MCStreamer.h"
31
#include "llvm/MC/MCSymbol.h"
32
#include "llvm/MC/MCSymbolCOFF.h"
33
#include "llvm/MC/MCSymbolELF.h"
34
#include "llvm/MC/MCSymbolMachO.h"
35
#include "llvm/MC/MCSymbolWasm.h"
36
#include "llvm/MC/MCSymbolXCOFF.h"
37
#include "llvm/MC/SectionKind.h"
38
#include "llvm/Support/Casting.h"
39
#include "llvm/Support/CommandLine.h"
40
#include "llvm/Support/ErrorHandling.h"
41
#include "llvm/Support/MemoryBuffer.h"
42
#include "llvm/Support/Path.h"
43
#include "llvm/Support/Signals.h"
44
#include "llvm/Support/SourceMgr.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <cassert>
47
#include <cstdlib>
48
#include <tuple>
49
#include <utility>
50
51
using namespace llvm;
52
53
static cl::opt<char*>
54
AsSecureLogFileName("as-secure-log-file-name",
55
        cl::desc("As secure log file name (initialized from "
56
                 "AS_SECURE_LOG_FILE env variable)"),
57
        cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
58
59
MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
60
                     const MCObjectFileInfo *mofi, const SourceMgr *mgr,
61
                     bool DoAutoReset)
62
    : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
63
      Symbols(Allocator), UsedNames(Allocator),
64
      CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
65
54.0k
      AutoReset(DoAutoReset) {
66
54.0k
  SecureLogFile = AsSecureLogFileName;
67
54.0k
68
54.0k
  if (SrcMgr && 
SrcMgr->getNumBuffers()12.0k
)
69
11.8k
    MainFileName =
70
11.8k
        SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
71
54.0k
}
72
73
53.7k
MCContext::~MCContext() {
74
53.7k
  if (AutoReset)
75
15.4k
    reset();
76
53.7k
77
53.7k
  // NOTE: The symbols are all allocated out of a bump pointer allocator,
78
53.7k
  // we don't need to free them here.
79
53.7k
}
80
81
//===----------------------------------------------------------------------===//
82
// Module Lifetime Management
83
//===----------------------------------------------------------------------===//
84
85
53.4k
void MCContext::reset() {
86
53.4k
  // Call the destructors so the fragments are freed
87
53.4k
  COFFAllocator.DestroyAll();
88
53.4k
  ELFAllocator.DestroyAll();
89
53.4k
  MachOAllocator.DestroyAll();
90
53.4k
  XCOFFAllocator.DestroyAll();
91
53.4k
92
53.4k
  MCSubtargetAllocator.DestroyAll();
93
53.4k
  UsedNames.clear();
94
53.4k
  Symbols.clear();
95
53.4k
  Allocator.Reset();
96
53.4k
  Instances.clear();
97
53.4k
  CompilationDir.clear();
98
53.4k
  MainFileName.clear();
99
53.4k
  MCDwarfLineTablesCUMap.clear();
100
53.4k
  SectionsForRanges.clear();
101
53.4k
  MCGenDwarfLabelEntries.clear();
102
53.4k
  DwarfDebugFlags = StringRef();
103
53.4k
  DwarfCompileUnitID = 0;
104
53.4k
  CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
105
53.4k
106
53.4k
  CVContext.reset();
107
53.4k
108
53.4k
  MachOUniquingMap.clear();
109
53.4k
  ELFUniquingMap.clear();
110
53.4k
  COFFUniquingMap.clear();
111
53.4k
  WasmUniquingMap.clear();
112
53.4k
  XCOFFUniquingMap.clear();
113
53.4k
114
53.4k
  NextID.clear();
115
53.4k
  AllowTemporaryLabels = true;
116
53.4k
  DwarfLocSeen = false;
117
53.4k
  GenDwarfForAssembly = false;
118
53.4k
  GenDwarfFileNumber = 0;
119
53.4k
120
53.4k
  HadError = false;
121
53.4k
}
122
123
//===----------------------------------------------------------------------===//
124
// Symbol Manipulation
125
//===----------------------------------------------------------------------===//
126
127
6.04M
MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
128
6.04M
  SmallString<128> NameSV;
129
6.04M
  StringRef NameRef = Name.toStringRef(NameSV);
130
6.04M
131
6.04M
  assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
132
6.04M
133
6.04M
  MCSymbol *&Sym = Symbols[NameRef];
134
6.04M
  if (!Sym)
135
2.50M
    Sym = createSymbol(NameRef, false, false);
136
6.04M
137
6.04M
  return Sym;
138
6.04M
}
139
140
MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
141
43
                                                 unsigned Idx) {
142
43
  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
143
43
                           "$frame_escape_" + Twine(Idx));
144
43
}
145
146
32
MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
147
32
  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
148
32
                           "$parent_frame_offset");
149
32
}
150
151
68
MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
152
68
  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
153
68
                           FuncName);
154
68
}
155
156
MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
157
7.31M
                                      bool IsTemporary) {
158
7.31M
  if (MOFI) {
159
7.31M
    switch (MOFI->getObjectFileType()) {
160
7.31M
    case MCObjectFileInfo::IsCOFF:
161
53.7k
      return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
162
7.31M
    case MCObjectFileInfo::IsELF:
163
650k
      return new (Name, *this) MCSymbolELF(Name, IsTemporary);
164
7.31M
    case MCObjectFileInfo::IsMachO:
165
6.58M
      return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
166
7.31M
    case MCObjectFileInfo::IsWasm:
167
25.0k
      return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
168
7.31M
    case MCObjectFileInfo::IsXCOFF:
169
30
      return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
170
43
    }
171
43
  }
172
43
  return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
173
43
                                    IsTemporary);
174
43
}
175
176
MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
177
7.31M
                                  bool CanBeUnnamed) {
178
7.31M
  if (CanBeUnnamed && 
!UseNamesOnTempLabels4.76M
)
179
4.39M
    return createSymbolImpl(nullptr, true);
180
2.91M
181
2.91M
  // Determine whether this is a user written assembler temporary or normal
182
2.91M
  // label, if used.
183
2.91M
  bool IsTemporary = CanBeUnnamed;
184
2.91M
  if (AllowTemporaryLabels && 
!IsTemporary2.91M
)
185
2.55M
    IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
186
2.91M
187
2.91M
  SmallString<128> NewName = Name;
188
2.91M
  bool AddSuffix = AlwaysAddSuffix;
189
2.91M
  unsigned &NextUniqueID = NextID[Name];
190
2.93M
  while (
true2.93M
) {
191
2.93M
    if (AddSuffix) {
192
315k
      NewName.resize(Name.size());
193
315k
      raw_svector_ostream(NewName) << NextUniqueID++;
194
315k
    }
195
2.93M
    auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
196
2.93M
    if (NameEntry.second || 
!NameEntry.first->second13.9k
) {
197
2.91M
      // Ok, we found a name.
198
2.91M
      // Mark it as used for a non-section symbol.
199
2.91M
      NameEntry.first->second = true;
200
2.91M
      // Have the MCSymbol object itself refer to the copy of the string that is
201
2.91M
      // embedded in the UsedNames entry.
202
2.91M
      return createSymbolImpl(&*NameEntry.first, IsTemporary);
203
2.91M
    }
204
13.9k
    assert(IsTemporary && "Cannot rename non-temporary symbols");
205
13.9k
    AddSuffix = true;
206
13.9k
  }
207
18.4E
  llvm_unreachable("Infinite loop");
208
2.91M
}
209
210
MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
211
4.76M
                                      bool CanBeUnnamed) {
212
4.76M
  SmallString<128> NameSV;
213
4.76M
  raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
214
4.76M
  return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
215
4.76M
}
216
217
32.9k
MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
218
32.9k
  SmallString<128> NameSV;
219
32.9k
  raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
220
32.9k
  return createSymbol(NameSV, true, false);
221
32.9k
}
222
223
1.88M
MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
224
1.88M
  return createTempSymbol("tmp", true, CanBeUnnamed);
225
1.88M
}
226
227
368
unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
228
368
  MCLabel *&Label = Instances[LocalLabelVal];
229
368
  if (!Label)
230
89
    Label = new (*this) MCLabel(0);
231
368
  return Label->incInstance();
232
368
}
233
234
425
unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
235
425
  MCLabel *&Label = Instances[LocalLabelVal];
236
425
  if (!Label)
237
169
    Label = new (*this) MCLabel(0);
238
425
  return Label->getInstance();
239
425
}
240
241
MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
242
793
                                                       unsigned Instance) {
243
793
  MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
244
793
  if (!Sym)
245
380
    Sym = createTempSymbol(false);
246
793
  return Sym;
247
793
}
248
249
368
MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
250
368
  unsigned Instance = NextInstance(LocalLabelVal);
251
368
  return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
252
368
}
253
254
MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
255
425
                                               bool Before) {
256
425
  unsigned Instance = GetInstance(LocalLabelVal);
257
425
  if (!Before)
258
288
    ++Instance;
259
425
  return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
260
425
}
261
262
2.43k
MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
263
2.43k
  SmallString<128> NameSV;
264
2.43k
  StringRef NameRef = Name.toStringRef(NameSV);
265
2.43k
  return Symbols.lookup(NameRef);
266
2.43k
}
267
268
void MCContext::setSymbolValue(MCStreamer &Streamer,
269
                              StringRef Sym,
270
8
                              uint64_t Val) {
271
8
  auto Symbol = getOrCreateSymbol(Sym);
272
8
  Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this));
273
8
}
274
275
//===----------------------------------------------------------------------===//
276
// Section Management
277
//===----------------------------------------------------------------------===//
278
279
MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
280
                                           unsigned TypeAndAttributes,
281
                                           unsigned Reserved2, SectionKind Kind,
282
899k
                                           const char *BeginSymName) {
283
899k
  // We unique sections by their segment/section pair.  The returned section
284
899k
  // may not have the same flags as the requested section, if so this should be
285
899k
  // diagnosed by the client as an error.
286
899k
287
899k
  // Form the name to look up.
288
899k
  SmallString<64> Name;
289
899k
  Name += Segment;
290
899k
  Name.push_back(',');
291
899k
  Name += Section;
292
899k
293
899k
  // Do the lookup, if we have a hit, return it.
294
899k
  MCSectionMachO *&Entry = MachOUniquingMap[Name];
295
899k
  if (Entry)
296
8.70k
    return Entry;
297
890k
298
890k
  MCSymbol *Begin = nullptr;
299
890k
  if (BeginSymName)
300
287k
    Begin = createTempSymbol(BeginSymName, false);
301
890k
302
890k
  // Otherwise, return a new section.
303
890k
  return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
304
890k
             Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
305
890k
}
306
307
7
void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
308
7
  StringRef GroupName;
309
7
  if (const MCSymbol *Group = Section->getGroup())
310
0
    GroupName = Group->getName();
311
7
312
7
  unsigned UniqueID = Section->getUniqueID();
313
7
  ELFUniquingMap.erase(
314
7
      ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
315
7
  auto I = ELFUniquingMap.insert(std::make_pair(
316
7
                                     ELFSectionKey{Name, GroupName, UniqueID},
317
7
                                     Section))
318
7
               .first;
319
7
  StringRef CachedName = I->first.SectionName;
320
7
  const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
321
7
}
322
323
MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
324
                                              unsigned Flags, SectionKind K,
325
                                              unsigned EntrySize,
326
                                              const MCSymbolELF *Group,
327
                                              unsigned UniqueID,
328
2.16M
                                              const MCSymbolELF *Associated) {
329
2.16M
  MCSymbolELF *R;
330
2.16M
  MCSymbol *&Sym = Symbols[Section];
331
2.16M
  // A section symbol can not redefine regular symbols. There may be multiple
332
2.16M
  // sections with the same name, in which case the first such section wins.
333
2.16M
  if (Sym && 
Sym->isDefined()319
&&
334
2.16M
      
(306
!Sym->isInSection()306
||
Sym->getSection().getBeginSymbol() != Sym306
))
335
1
    reportError(SMLoc(), "invalid symbol redefinition");
336
2.16M
  if (Sym && 
Sym->isUndefined()319
) {
337
13
    R = cast<MCSymbolELF>(Sym);
338
2.16M
  } else {
339
2.16M
    auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
340
2.16M
    R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
341
2.16M
    if (!Sym)
342
2.16M
      Sym = R;
343
2.16M
  }
344
2.16M
  R->setBinding(ELF::STB_LOCAL);
345
2.16M
  R->setType(ELF::STT_SECTION);
346
2.16M
347
2.16M
  auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
348
2.16M
      Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated);
349
2.16M
350
2.16M
  auto *F = new MCDataFragment();
351
2.16M
  Ret->getFragmentList().insert(Ret->begin(), F);
352
2.16M
  F->setParent(Ret);
353
2.16M
  R->setFragment(F);
354
2.16M
355
2.16M
  return Ret;
356
2.16M
}
357
358
MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
359
                                             unsigned Flags, unsigned EntrySize,
360
                                             const MCSymbolELF *Group,
361
4.44k
                                             const MCSectionELF *RelInfoSection) {
362
4.44k
  StringMap<bool>::iterator I;
363
4.44k
  bool Inserted;
364
4.44k
  std::tie(I, Inserted) =
365
4.44k
      RelSecNames.insert(std::make_pair(Name.str(), true));
366
4.44k
367
4.44k
  return createELFSectionImpl(
368
4.44k
      I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
369
4.44k
      true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
370
4.44k
}
371
372
MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
373
                                            const Twine &Suffix, unsigned Type,
374
                                            unsigned Flags,
375
52
                                            unsigned EntrySize) {
376
52
  return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
377
52
}
378
379
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
380
                                       unsigned Flags, unsigned EntrySize,
381
                                       const Twine &Group, unsigned UniqueID,
382
2.42M
                                       const MCSymbolELF *Associated) {
383
2.42M
  MCSymbolELF *GroupSym = nullptr;
384
2.42M
  if (!Group.isTriviallyEmpty() && 
!Group.str().empty()671k
)
385
365
    GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
386
2.42M
387
2.42M
  return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
388
2.42M
                       Associated);
389
2.42M
}
390
391
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
392
                                       unsigned Flags, unsigned EntrySize,
393
                                       const MCSymbolELF *GroupSym,
394
                                       unsigned UniqueID,
395
2.42M
                                       const MCSymbolELF *Associated) {
396
2.42M
  StringRef Group = "";
397
2.42M
  if (GroupSym)
398
371
    Group = GroupSym->getName();
399
2.42M
  // Do the lookup, if we have a hit, return it.
400
2.42M
  auto IterBool = ELFUniquingMap.insert(
401
2.42M
      std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr));
402
2.42M
  auto &Entry = *IterBool.first;
403
2.42M
  if (!IterBool.second)
404
265k
    return Entry.second;
405
2.15M
406
2.15M
  StringRef CachedName = Entry.first.SectionName;
407
2.15M
408
2.15M
  SectionKind Kind;
409
2.15M
  if (Flags & ELF::SHF_ARM_PURECODE)
410
454
    Kind = SectionKind::getExecuteOnly();
411
2.15M
  else if (Flags & ELF::SHF_EXECINSTR)
412
35.9k
    Kind = SectionKind::getText();
413
2.11M
  else
414
2.11M
    Kind = SectionKind::getReadOnly();
415
2.15M
416
2.15M
  MCSectionELF *Result = createELFSectionImpl(
417
2.15M
      CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated);
418
2.15M
  Entry.second = Result;
419
2.15M
  return Result;
420
2.15M
}
421
422
173
MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
423
173
  return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
424
173
                              SectionKind::getReadOnly(), 4, Group, ~0,
425
173
                              nullptr);
426
173
}
427
428
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
429
                                         unsigned Characteristics,
430
                                         SectionKind Kind,
431
                                         StringRef COMDATSymName, int Selection,
432
                                         unsigned UniqueID,
433
63.1k
                                         const char *BeginSymName) {
434
63.1k
  MCSymbol *COMDATSymbol = nullptr;
435
63.1k
  if (!COMDATSymName.empty()) {
436
1.27k
    COMDATSymbol = getOrCreateSymbol(COMDATSymName);
437
1.27k
    COMDATSymName = COMDATSymbol->getName();
438
1.27k
  }
439
63.1k
440
63.1k
441
63.1k
  // Do the lookup, if we have a hit, return it.
442
63.1k
  COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
443
63.1k
  auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
444
63.1k
  auto Iter = IterBool.first;
445
63.1k
  if (!IterBool.second)
446
899
    return Iter->second;
447
62.2k
448
62.2k
  MCSymbol *Begin = nullptr;
449
62.2k
  if (BeginSymName)
450
27.3k
    Begin = createTempSymbol(BeginSymName, false);
451
62.2k
452
62.2k
  StringRef CachedName = Iter->first.SectionName;
453
62.2k
  MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
454
62.2k
      CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
455
62.2k
456
62.2k
  Iter->second = Result;
457
62.2k
  return Result;
458
62.2k
}
459
460
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
461
                                         unsigned Characteristics,
462
                                         SectionKind Kind,
463
61.0k
                                         const char *BeginSymName) {
464
61.0k
  return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
465
61.0k
                        BeginSymName);
466
61.0k
}
467
468
MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
469
                                                    const MCSymbol *KeySym,
470
1.16k
                                                    unsigned UniqueID) {
471
1.16k
  // Return the normal section if we don't have to be associative or unique.
472
1.16k
  if (!KeySym && 
UniqueID == GenericSectionID904
)
473
873
    return Sec;
474
288
475
288
  // If we have a key symbol, make an associative section with the same name and
476
288
  // kind as the normal section.
477
288
  unsigned Characteristics = Sec->getCharacteristics();
478
288
  if (KeySym) {
479
257
    Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
480
257
    return getCOFFSection(Sec->getSectionName(), Characteristics,
481
257
                          Sec->getKind(), KeySym->getName(),
482
257
                          COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
483
257
  }
484
31
485
31
  return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
486
31
                        "", 0, UniqueID);
487
31
}
488
489
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
490
                                         const Twine &Group, unsigned UniqueID,
491
13.3k
                                         const char *BeginSymName) {
492
13.3k
  MCSymbolWasm *GroupSym = nullptr;
493
13.3k
  if (!Group.isTriviallyEmpty() && 
!Group.str().empty()4.71k
) {
494
13
    GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
495
13
    GroupSym->setComdat(true);
496
13
  }
497
13.3k
498
13.3k
  return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
499
13.3k
}
500
501
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
502
                                         const MCSymbolWasm *GroupSym,
503
                                         unsigned UniqueID,
504
13.3k
                                         const char *BeginSymName) {
505
13.3k
  StringRef Group = "";
506
13.3k
  if (GroupSym)
507
13
    Group = GroupSym->getName();
508
13.3k
  // Do the lookup, if we have a hit, return it.
509
13.3k
  auto IterBool = WasmUniquingMap.insert(
510
13.3k
      std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
511
13.3k
  auto &Entry = *IterBool.first;
512
13.3k
  if (!IterBool.second)
513
34
    return Entry.second;
514
13.3k
515
13.3k
  StringRef CachedName = Entry.first.SectionName;
516
13.3k
517
13.3k
  MCSymbol *Begin = createSymbol(CachedName, false, false);
518
13.3k
  cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
519
13.3k
520
13.3k
  MCSectionWasm *Result = new (WasmAllocator.Allocate())
521
13.3k
      MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
522
13.3k
  Entry.second = Result;
523
13.3k
524
13.3k
  auto *F = new MCDataFragment();
525
13.3k
  Result->getFragmentList().insert(Result->begin(), F);
526
13.3k
  F->setParent(Result);
527
13.3k
  Begin->setFragment(F);
528
13.3k
529
13.3k
  return Result;
530
13.3k
}
531
532
MCSectionXCOFF *MCContext::getXCOFFSection(StringRef Section,
533
                                           XCOFF::StorageMappingClass SMC,
534
                                           XCOFF::SymbolType Type,
535
                                           SectionKind Kind,
536
17
                                           const char *BeginSymName) {
537
17
  // Do the lookup. If we have a hit, return it.
538
17
  auto IterBool = XCOFFUniquingMap.insert(
539
17
      std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr));
540
17
  auto &Entry = *IterBool.first;
541
17
  if (!IterBool.second)
542
0
    return Entry.second;
543
17
544
17
  // Otherwise, return a new section.
545
17
  StringRef CachedName = Entry.first.SectionName;
546
17
547
17
  MCSymbol *Begin = nullptr;
548
17
  if (BeginSymName)
549
0
    Begin = createTempSymbol(BeginSymName, false);
550
17
551
17
  MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate())
552
17
      MCSectionXCOFF(CachedName, SMC, Type, Kind, Begin);
553
17
  Entry.second = Result;
554
17
555
17
  auto *F = new MCDataFragment();
556
17
  Result->getFragmentList().insert(Result->begin(), F);
557
17
  F->setParent(Result);
558
17
559
17
  if (Begin)
560
0
    Begin->setFragment(F);
561
17
562
17
  return Result;
563
17
}
564
565
2.70k
MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
566
2.70k
  return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
567
2.70k
}
568
569
void MCContext::addDebugPrefixMapEntry(const std::string &From,
570
2
                                       const std::string &To) {
571
2
  DebugPrefixMap.insert(std::make_pair(From, To));
572
2
}
573
574
20.4k
void MCContext::RemapDebugPaths() {
575
20.4k
  const auto &DebugPrefixMap = this->DebugPrefixMap;
576
22.4k
  const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
577
22.4k
    for (const auto &Entry : DebugPrefixMap)
578
2
      if (StringRef(Path).startswith(Entry.first)) {
579
2
        std::string RemappedPath =
580
2
            (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
581
2
        Path.swap(RemappedPath);
582
2
      }
583
22.4k
  };
584
20.4k
585
20.4k
  // Remap compilation directory.
586
20.4k
  std::string CompDir = CompilationDir.str();
587
20.4k
  RemapDebugPath(CompDir);
588
20.4k
  CompilationDir = CompDir;
589
20.4k
590
20.4k
  // Remap MCDwarfDirs in all compilation units.
591
20.4k
  for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
592
2.38k
    for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
593
1.97k
      RemapDebugPath(Dir);
594
20.4k
}
595
596
//===----------------------------------------------------------------------===//
597
// Dwarf Management
598
//===----------------------------------------------------------------------===//
599
600
75
void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
601
75
  // MCDwarf needs the root file as well as the compilation directory.
602
75
  // If we find a '.file 0' directive that will supersede these values.
603
75
  Optional<MD5::MD5Result> Cksum;
604
75
  if (getDwarfVersion() >= 5) {
605
4
    MD5 Hash;
606
4
    MD5::MD5Result Sum;
607
4
    Hash.update(Buffer);
608
4
    Hash.final(Sum);
609
4
    Cksum = Sum;
610
4
  }
611
75
  // Canonicalize the root filename. It cannot be empty, and should not
612
75
  // repeat the compilation dir.
613
75
  // The MCContext ctor initializes MainFileName to the name associated with
614
75
  // the SrcMgr's main file ID, which might be the same as InputFileName (and
615
75
  // possibly include directory components).
616
75
  // Or, MainFileName might have been overridden by a -main-file-name option,
617
75
  // which is supposed to be just a base filename with no directory component.
618
75
  // So, if the InputFileName and MainFileName are not equal, assume
619
75
  // MainFileName is a substitute basename and replace the last component.
620
75
  SmallString<1024> FileNameBuf = InputFileName;
621
75
  if (FileNameBuf.empty() || FileNameBuf == "-")
622
10
    FileNameBuf = "<stdin>";
623
75
  if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
624
20
    llvm::sys::path::remove_filename(FileNameBuf);
625
20
    llvm::sys::path::append(FileNameBuf, getMainFileName());
626
20
  }
627
75
  StringRef FileName = FileNameBuf;
628
75
  if (FileName.consume_front(getCompilationDir()))
629
3
    if (llvm::sys::path::is_separator(FileName.front()))
630
3
      FileName = FileName.drop_front();
631
75
  assert(!FileName.empty());
632
75
  setMCLineTableRootFile(
633
75
      /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
634
75
}
635
636
/// getDwarfFile - takes a file name and number to place in the dwarf file and
637
/// directory tables.  If the file number has already been allocated it is an
638
/// error and zero is returned and the client reports the error, else the
639
/// allocated file number is returned.  The file numbers may be in any order.
640
Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
641
                                           StringRef FileName,
642
                                           unsigned FileNumber,
643
                                           Optional<MD5::MD5Result> Checksum,
644
                                           Optional<StringRef> Source,
645
1.24M
                                           unsigned CUID) {
646
1.24M
  MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
647
1.24M
  return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
648
1.24M
                          FileNumber);
649
1.24M
}
650
651
/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
652
/// currently is assigned and false otherwise.
653
556
bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
654
556
  const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
655
556
  if (FileNumber == 0)
656
14
    return getDwarfVersion() >= 5;
657
542
  if (FileNumber >= LineTable.getMCDwarfFiles().size())
658
0
    return false;
659
542
660
542
  return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
661
542
}
662
663
/// Remove empty sections from SectionsForRanges, to avoid generating
664
/// useless debug info for them.
665
73
void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
666
73
  SectionsForRanges.remove_if(
667
80
      [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
668
73
}
669
670
6.15k
CodeViewContext &MCContext::getCVContext() {
671
6.15k
  if (!CVContext.get())
672
249
    CVContext.reset(new CodeViewContext);
673
6.15k
  return *CVContext.get();
674
6.15k
}
675
676
//===----------------------------------------------------------------------===//
677
// Error Reporting
678
//===----------------------------------------------------------------------===//
679
680
398
void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
681
398
  HadError = true;
682
398
683
398
  // If we have a source manager use it. Otherwise, try using the inline source
684
398
  // manager.
685
398
  // If that fails, use the generic report_fatal_error().
686
398
  if (SrcMgr)
687
388
    SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
688
10
  else if (InlineSrcMgr)
689
5
    InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
690
5
  else
691
5
    report_fatal_error(Msg, false);
692
398
}
693
694
4
void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
695
4
  reportError(Loc, Msg);
696
4
697
4
  // If we reached here, we are failing ungracefully. Run the interrupt handlers
698
4
  // to make sure any special cleanups get done, in particular that we remove
699
4
  // files registered with RemoveFileOnSignal.
700
4
  sys::RunInterruptHandlers();
701
4
  exit(1);
702
4
}