Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/MC/MCAssembler.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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/MCAssembler.h"
10
#include "llvm/ADT/ArrayRef.h"
11
#include "llvm/ADT/SmallString.h"
12
#include "llvm/ADT/SmallVector.h"
13
#include "llvm/ADT/Statistic.h"
14
#include "llvm/ADT/StringRef.h"
15
#include "llvm/ADT/Twine.h"
16
#include "llvm/MC/MCAsmBackend.h"
17
#include "llvm/MC/MCAsmInfo.h"
18
#include "llvm/MC/MCAsmLayout.h"
19
#include "llvm/MC/MCCodeEmitter.h"
20
#include "llvm/MC/MCCodeView.h"
21
#include "llvm/MC/MCContext.h"
22
#include "llvm/MC/MCDwarf.h"
23
#include "llvm/MC/MCExpr.h"
24
#include "llvm/MC/MCFixup.h"
25
#include "llvm/MC/MCFixupKindInfo.h"
26
#include "llvm/MC/MCFragment.h"
27
#include "llvm/MC/MCInst.h"
28
#include "llvm/MC/MCObjectWriter.h"
29
#include "llvm/MC/MCSection.h"
30
#include "llvm/MC/MCSectionELF.h"
31
#include "llvm/MC/MCSymbol.h"
32
#include "llvm/MC/MCValue.h"
33
#include "llvm/Support/Casting.h"
34
#include "llvm/Support/Debug.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/LEB128.h"
37
#include "llvm/Support/MathExtras.h"
38
#include "llvm/Support/raw_ostream.h"
39
#include <cassert>
40
#include <cstdint>
41
#include <cstring>
42
#include <tuple>
43
#include <utility>
44
45
using namespace llvm;
46
47
#define DEBUG_TYPE "assembler"
48
49
namespace {
50
namespace stats {
51
52
STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
53
STATISTIC(EmittedRelaxableFragments,
54
          "Number of emitted assembler fragments - relaxable");
55
STATISTIC(EmittedDataFragments,
56
          "Number of emitted assembler fragments - data");
57
STATISTIC(EmittedCompactEncodedInstFragments,
58
          "Number of emitted assembler fragments - compact encoded inst");
59
STATISTIC(EmittedAlignFragments,
60
          "Number of emitted assembler fragments - align");
61
STATISTIC(EmittedFillFragments,
62
          "Number of emitted assembler fragments - fill");
63
STATISTIC(EmittedOrgFragments,
64
          "Number of emitted assembler fragments - org");
65
STATISTIC(evaluateFixup, "Number of evaluated fixups");
66
STATISTIC(FragmentLayouts, "Number of fragment layouts");
67
STATISTIC(ObjectBytes, "Number of emitted object file bytes");
68
STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
69
STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
70
STATISTIC(PaddingFragmentsRelaxations,
71
          "Number of Padding Fragments relaxations");
72
STATISTIC(PaddingFragmentsBytes,
73
          "Total size of all padding from adding Fragments");
74
75
} // end namespace stats
76
} // end anonymous namespace
77
78
// FIXME FIXME FIXME: There are number of places in this file where we convert
79
// what is a 64-bit assembler value used for computation into a value in the
80
// object file, which may truncate it. We should detect that truncation where
81
// invalid and report errors back.
82
83
/* *** */
84
85
MCAssembler::MCAssembler(MCContext &Context,
86
                         std::unique_ptr<MCAsmBackend> Backend,
87
                         std::unique_ptr<MCCodeEmitter> Emitter,
88
                         std::unique_ptr<MCObjectWriter> Writer)
89
    : Context(Context), Backend(std::move(Backend)),
90
      Emitter(std::move(Emitter)), Writer(std::move(Writer)),
91
      BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
92
47.3k
      IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
93
47.3k
  VersionInfo.Major = 0; // Major version == 0 for "none specified"
94
47.3k
}
95
96
47.1k
MCAssembler::~MCAssembler() = default;
97
98
14.4k
void MCAssembler::reset() {
99
14.4k
  Sections.clear();
100
14.4k
  Symbols.clear();
101
14.4k
  IndirectSymbols.clear();
102
14.4k
  DataRegions.clear();
103
14.4k
  LinkerOptions.clear();
104
14.4k
  FileNames.clear();
105
14.4k
  ThumbFuncs.clear();
106
14.4k
  BundleAlignSize = 0;
107
14.4k
  RelaxAll = false;
108
14.4k
  SubsectionsViaSymbols = false;
109
14.4k
  IncrementalLinkerCompatible = false;
110
14.4k
  ELFHeaderEFlags = 0;
111
14.4k
  LOHContainer.reset();
112
14.4k
  VersionInfo.Major = 0;
113
14.4k
  VersionInfo.SDKVersion = VersionTuple();
114
14.4k
115
14.4k
  // reset objects owned by us
116
14.4k
  if (getBackendPtr())
117
14.4k
    getBackendPtr()->reset();
118
14.4k
  if (getEmitterPtr())
119
14.4k
    getEmitterPtr()->reset();
120
14.4k
  if (getWriterPtr())
121
14.4k
    getWriterPtr()->reset();
122
14.4k
  getLOHContainer().reset();
123
14.4k
}
124
125
641k
bool MCAssembler::registerSection(MCSection &Section) {
126
641k
  if (Section.isRegistered())
127
83.1k
    return false;
128
558k
  Sections.push_back(&Section);
129
558k
  Section.setIsRegistered(true);
130
558k
  return true;
131
558k
}
132
133
4.26M
bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
134
4.26M
  if (ThumbFuncs.count(Symbol))
135
7.54k
    return true;
136
4.25M
137
4.25M
  if (!Symbol->isVariable())
138
4.25M
    return false;
139
490
140
490
  const MCExpr *Expr = Symbol->getVariableValue();
141
490
142
490
  MCValue V;
143
490
  if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
144
1
    return false;
145
489
146
489
  if (V.getSymB() || 
V.getRefKind() != MCSymbolRefExpr::VK_None481
)
147
12
    return false;
148
477
149
477
  const MCSymbolRefExpr *Ref = V.getSymA();
150
477
  if (!Ref)
151
232
    return false;
152
245
153
245
  if (Ref->getKind() != MCSymbolRefExpr::VK_None)
154
0
    return false;
155
245
156
245
  const MCSymbol &Sym = Ref->getSymbol();
157
245
  if (!isThumbFunc(&Sym))
158
245
    return false;
159
0
160
0
  ThumbFuncs.insert(Symbol); // Cache it.
161
0
  return true;
162
0
}
163
164
33.8M
bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
165
33.8M
  // Non-temporary labels should always be visible to the linker.
166
33.8M
  if (!Symbol.isTemporary())
167
6.83M
    return true;
168
26.9M
169
26.9M
  // Absolute temporary labels are never visible.
170
26.9M
  if (!Symbol.isInSection())
171
7.00M
    return false;
172
19.9M
173
19.9M
  if (Symbol.isUsedInReloc())
174
197
    return true;
175
19.9M
176
19.9M
  return false;
177
19.9M
}
178
179
3.29M
const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
180
3.29M
  // Linker visible symbols define atoms.
181
3.29M
  if (isSymbolLinkerVisible(S))
182
2.71M
    return &S;
183
584k
184
584k
  // Absolute and undefined symbols have no defining atom.
185
584k
  if (!S.isInSection())
186
19.5k
    return nullptr;
187
564k
188
564k
  // Non-linker visible symbols in sections which can't be atomized have no
189
564k
  // defining atom.
190
564k
  if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
191
564k
          *S.getFragment()->getParent()))
192
32.9k
    return nullptr;
193
531k
194
531k
  // Otherwise, return the atom for the containing fragment.
195
531k
  return S.getFragment()->getAtom();
196
531k
}
197
198
bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
199
                                const MCFixup &Fixup, const MCFragment *DF,
200
                                MCValue &Target, uint64_t &Value,
201
6.41M
                                bool &WasForced) const {
202
6.41M
  ++stats::evaluateFixup;
203
6.41M
204
6.41M
  // FIXME: This code has some duplication with recordRelocation. We should
205
6.41M
  // probably merge the two into a single callback that tries to evaluate a
206
6.41M
  // fixup and records a relocation if one is needed.
207
6.41M
208
6.41M
  // On error claim to have completely evaluated the fixup, to prevent any
209
6.41M
  // further processing from being done.
210
6.41M
  const MCExpr *Expr = Fixup.getValue();
211
6.41M
  MCContext &Ctx = getContext();
212
6.41M
  Value = 0;
213
6.41M
  WasForced = false;
214
6.41M
  if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
215
25
    Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
216
25
    return true;
217
25
  }
218
6.41M
  if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
219
69.4k
    if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
220
6
      Ctx.reportError(Fixup.getLoc(),
221
6
                      "unsupported subtraction of qualified symbol");
222
6
      return true;
223
6
    }
224
6.41M
  }
225
6.41M
226
6.41M
  assert(getBackendPtr() && "Expected assembler backend");
227
6.41M
  bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
228
6.41M
                 MCFixupKindInfo::FKF_IsPCRel;
229
6.41M
230
6.41M
  bool IsResolved = false;
231
6.41M
  if (IsPCRel) {
232
4.30M
    if (Target.getSymB()) {
233
7
      IsResolved = false;
234
4.30M
    } else if (!Target.getSymA()) {
235
17
      IsResolved = false;
236
4.30M
    } else {
237
4.30M
      const MCSymbolRefExpr *A = Target.getSymA();
238
4.30M
      const MCSymbol &SA = A->getSymbol();
239
4.30M
      if (A->getKind() != MCSymbolRefExpr::VK_None || 
SA.isUndefined()3.65M
) {
240
1.22M
        IsResolved = false;
241
3.07M
      } else if (auto *Writer = getWriterPtr()) {
242
3.07M
        IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
243
3.07M
            *this, SA, *DF, false, true);
244
3.07M
      }
245
4.30M
    }
246
4.30M
  } else {
247
2.10M
    IsResolved = Target.isAbsolute();
248
2.10M
  }
249
6.41M
250
6.41M
  Value = Target.getConstant();
251
6.41M
252
6.41M
  if (const MCSymbolRefExpr *A = Target.getSymA()) {
253
5.84M
    const MCSymbol &Sym = A->getSymbol();
254
5.84M
    if (Sym.isDefined())
255
5.13M
      Value += Layout.getSymbolOffset(Sym);
256
5.84M
  }
257
6.41M
  if (const MCSymbolRefExpr *B = Target.getSymB()) {
258
69.4k
    const MCSymbol &Sym = B->getSymbol();
259
69.4k
    if (Sym.isDefined())
260
69.4k
      Value -= Layout.getSymbolOffset(Sym);
261
69.4k
  }
262
6.41M
263
6.41M
  bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
264
6.41M
                       MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
265
6.41M
  assert((ShouldAlignPC ? IsPCRel : true) &&
266
6.41M
    "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
267
6.41M
268
6.41M
  if (IsPCRel) {
269
4.30M
    uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
270
4.30M
271
4.30M
    // A number of ARM fixups in Thumb mode require that the effective PC
272
4.30M
    // address be determined as the 32-bit aligned version of the actual offset.
273
4.30M
    if (ShouldAlignPC) 
Offset &= ~0x33.21M
;
274
4.30M
    Value -= Offset;
275
4.30M
  }
276
6.41M
277
6.41M
  // Let the backend force a relocation if needed.
278
6.41M
  if (IsResolved && 
getBackend().shouldForceRelocation(*this, Fixup, Target)2.83M
) {
279
670
    IsResolved = false;
280
670
    WasForced = true;
281
670
  }
282
6.41M
283
6.41M
  return IsResolved;
284
6.41M
}
285
286
uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
287
12.2M
                                          const MCFragment &F) const {
288
12.2M
  assert(getBackendPtr() && "Requires assembler backend");
289
12.2M
  switch (F.getKind()) {
290
12.2M
  case MCFragment::FT_Data:
291
6.91M
    return cast<MCDataFragment>(F).getContents().size();
292
12.2M
  case MCFragment::FT_Relaxable:
293
793k
    return cast<MCRelaxableFragment>(F).getContents().size();
294
12.2M
  case MCFragment::FT_CompactEncodedInst:
295
408
    return cast<MCCompactEncodedInstFragment>(F).getContents().size();
296
12.2M
  case MCFragment::FT_Fill: {
297
1.26M
    auto &FF = cast<MCFillFragment>(F);
298
1.26M
    int64_t NumValues = 0;
299
1.26M
    if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
300
2
      getContext().reportError(FF.getLoc(),
301
2
                               "expected assembly-time absolute expression");
302
2
      return 0;
303
2
    }
304
1.26M
    int64_t Size = NumValues * FF.getValueSize();
305
1.26M
    if (Size < 0) {
306
4
      getContext().reportError(FF.getLoc(), "invalid number of bytes");
307
4
      return 0;
308
4
    }
309
1.26M
    return Size;
310
1.26M
  }
311
1.26M
312
1.26M
  case MCFragment::FT_LEB:
313
11.6k
    return cast<MCLEBFragment>(F).getContents().size();
314
1.26M
315
1.26M
  case MCFragment::FT_Padding:
316
0
    return cast<MCPaddingFragment>(F).getSize();
317
1.26M
318
1.26M
  case MCFragment::FT_SymbolId:
319
43
    return 4;
320
1.26M
321
1.26M
  case MCFragment::FT_Align: {
322
1.02M
    const MCAlignFragment &AF = cast<MCAlignFragment>(F);
323
1.02M
    unsigned Offset = Layout.getFragmentOffset(&AF);
324
1.02M
    unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
325
1.02M
326
1.02M
    // Insert extra Nops for code alignment if the target define
327
1.02M
    // shouldInsertExtraNopBytesForCodeAlign target hook.
328
1.02M
    if (AF.getParent()->UseCodeAlign() && 
AF.hasEmitNops()646k
&&
329
1.02M
        
getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size)645k
)
330
43
      return Size;
331
1.02M
332
1.02M
    // If we are padding with nops, force the padding to be larger than the
333
1.02M
    // minimum nop size.
334
1.02M
    if (Size > 0 && 
AF.hasEmitNops()301k
) {
335
110k
      while (Size % getBackend().getMinimumNopSize())
336
0
        Size += AF.getAlignment();
337
110k
    }
338
1.02M
    if (Size > AF.getMaxBytesToEmit())
339
9
      return 0;
340
1.02M
    return Size;
341
1.02M
  }
342
1.02M
343
1.02M
  case MCFragment::FT_Org: {
344
40
    const MCOrgFragment &OF = cast<MCOrgFragment>(F);
345
40
    MCValue Value;
346
40
    if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
347
2
      getContext().reportError(OF.getLoc(),
348
2
                               "expected assembly-time absolute expression");
349
2
        return 0;
350
2
    }
351
38
352
38
    uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
353
38
    int64_t TargetLocation = Value.getConstant();
354
38
    if (const MCSymbolRefExpr *A = Value.getSymA()) {
355
15
      uint64_t Val;
356
15
      if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
357
4
        getContext().reportError(OF.getLoc(), "expected absolute expression");
358
4
        return 0;
359
4
      }
360
11
      TargetLocation += Val;
361
11
    }
362
38
    int64_t Size = TargetLocation - FragmentOffset;
363
34
    if (Size < 0 || 
Size >= 0x4000000030
) {
364
4
      getContext().reportError(
365
4
          OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
366
4
                           "' (at offset '" + Twine(FragmentOffset) + "')");
367
4
      return 0;
368
4
    }
369
30
    return Size;
370
30
  }
371
30
372
1.93M
  case MCFragment::FT_Dwarf:
373
1.93M
    return cast<MCDwarfLineAddrFragment>(F).getContents().size();
374
262k
  case MCFragment::FT_DwarfFrame:
375
262k
    return cast<MCDwarfCallFrameFragment>(F).getContents().size();
376
66
  case MCFragment::FT_CVInlineLines:
377
66
    return cast<MCCVInlineLineTableFragment>(F).getContents().size();
378
716
  case MCFragment::FT_CVDefRange:
379
716
    return cast<MCCVDefRangeFragment>(F).getContents().size();
380
30
  case MCFragment::FT_Dummy:
381
0
    llvm_unreachable("Should not have been added");
382
0
  }
383
0
384
0
  llvm_unreachable("invalid fragment kind");
385
0
}
386
387
6.20M
void MCAsmLayout::layoutFragment(MCFragment *F) {
388
6.20M
  MCFragment *Prev = F->getPrevNode();
389
6.20M
390
6.20M
  // We should never try to recompute something which is valid.
391
6.20M
  assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
392
6.20M
  // We should never try to compute the fragment layout if its predecessor
393
6.20M
  // isn't valid.
394
6.20M
  assert((!Prev || isFragmentValid(Prev)) &&
395
6.20M
         "Attempt to compute fragment before its predecessor!");
396
6.20M
397
6.20M
  ++stats::FragmentLayouts;
398
6.20M
399
6.20M
  // Compute fragment offset and size.
400
6.20M
  if (Prev)
401
5.64M
    F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
402
558k
  else
403
558k
    F->Offset = 0;
404
6.20M
  LastValidFragment[F->getParent()] = F;
405
6.20M
406
6.20M
  // If bundling is enabled and this fragment has instructions in it, it has to
407
6.20M
  // obey the bundling restrictions. With padding, we'll have:
408
6.20M
  //
409
6.20M
  //
410
6.20M
  //        BundlePadding
411
6.20M
  //             |||
412
6.20M
  // -------------------------------------
413
6.20M
  //   Prev  |##########|       F        |
414
6.20M
  // -------------------------------------
415
6.20M
  //                    ^
416
6.20M
  //                    |
417
6.20M
  //                    F->Offset
418
6.20M
  //
419
6.20M
  // The fragment's offset will point to after the padding, and its computed
420
6.20M
  // size won't include the padding.
421
6.20M
  //
422
6.20M
  // When the -mc-relax-all flag is used, we optimize bundling by writting the
423
6.20M
  // padding directly into fragments when the instructions are emitted inside
424
6.20M
  // the streamer. When the fragment is larger than the bundle size, we need to
425
6.20M
  // ensure that it's bundle aligned. This means that if we end up with
426
6.20M
  // multiple fragments, we must emit bundle padding between fragments.
427
6.20M
  //
428
6.20M
  // ".align N" is an example of a directive that introduces multiple
429
6.20M
  // fragments. We could add a special case to handle ".align N" by emitting
430
6.20M
  // within-fragment padding (which would produce less padding when N is less
431
6.20M
  // than the bundle size), but for now we don't.
432
6.20M
  //
433
6.20M
  if (Assembler.isBundlingEnabled() && 
F->hasInstructions()1.86k
) {
434
758
    assert(isa<MCEncodedFragment>(F) &&
435
758
           "Only MCEncodedFragment implementations have instructions");
436
758
    MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
437
758
    uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
438
758
439
758
    if (!Assembler.getRelaxAll() && 
FSize > Assembler.getBundleAlignSize()738
)
440
1
      report_fatal_error("Fragment can't be larger than a bundle size");
441
757
442
757
    uint64_t RequiredBundlePadding =
443
757
        computeBundlePadding(Assembler, EF, EF->Offset, FSize);
444
757
    if (RequiredBundlePadding > UINT8_MAX)
445
757
      
report_fatal_error("Padding cannot exceed 255 bytes")0
;
446
757
    EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
447
757
    EF->Offset += RequiredBundlePadding;
448
757
  }
449
6.20M
}
450
451
14.4M
void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
452
14.4M
  bool New = !Symbol.isRegistered();
453
14.4M
  if (Created)
454
53
    *Created = New;
455
14.4M
  if (New) {
456
6.86M
    Symbol.setIsRegistered(true);
457
6.86M
    Symbols.push_back(&Symbol);
458
6.86M
  }
459
14.4M
}
460
461
void MCAssembler::writeFragmentPadding(raw_ostream &OS,
462
                                       const MCEncodedFragment &EF,
463
4.39M
                                       uint64_t FSize) const {
464
4.39M
  assert(getBackendPtr() && "Expected assembler backend");
465
4.39M
  // Should NOP padding be written out before this fragment?
466
4.39M
  unsigned BundlePadding = EF.getBundlePadding();
467
4.39M
  if (BundlePadding > 0) {
468
431
    assert(isBundlingEnabled() &&
469
431
           "Writing bundle padding with disabled bundling");
470
431
    assert(EF.hasInstructions() &&
471
431
           "Writing bundle padding for a fragment without instructions");
472
431
473
431
    unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
474
431
    if (EF.alignToBundleEnd() && 
TotalLength > getBundleAlignSize()270
) {
475
128
      // If the padding itself crosses a bundle boundary, it must be emitted
476
128
      // in 2 pieces, since even nop instructions must not cross boundaries.
477
128
      //             v--------------v   <- BundleAlignSize
478
128
      //        v---------v             <- BundlePadding
479
128
      // ----------------------------
480
128
      // | Prev |####|####|    F    |
481
128
      // ----------------------------
482
128
      //        ^-------------------^   <- TotalLength
483
128
      unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
484
128
      if (!getBackend().writeNopData(OS, DistanceToBoundary))
485
0
        report_fatal_error("unable to write NOP sequence of " +
486
0
                           Twine(DistanceToBoundary) + " bytes");
487
128
      BundlePadding -= DistanceToBoundary;
488
128
    }
489
431
    if (!getBackend().writeNopData(OS, BundlePadding))
490
0
      report_fatal_error("unable to write NOP sequence of " +
491
0
                         Twine(BundlePadding) + " bytes");
492
431
  }
493
4.39M
}
494
495
/// Write the fragment \p F to the output file.
496
static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
497
5.48M
                          const MCAsmLayout &Layout, const MCFragment &F) {
498
5.48M
  // FIXME: Embed in fragments instead?
499
5.48M
  uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
500
5.48M
501
5.48M
  support::endianness Endian = Asm.getBackend().Endian;
502
5.48M
503
5.48M
  if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
504
4.39M
    Asm.writeFragmentPadding(OS, *EF, FragmentSize);
505
5.48M
506
5.48M
  // This variable (and its dummy usage) is to participate in the assert at
507
5.48M
  // the end of the function.
508
5.48M
  uint64_t Start = OS.tell();
509
5.48M
  (void) Start;
510
5.48M
511
5.48M
  ++stats::EmittedFragments;
512
5.48M
513
5.48M
  switch (F.getKind()) {
514
5.48M
  case MCFragment::FT_Align: {
515
480k
    ++stats::EmittedAlignFragments;
516
480k
    const MCAlignFragment &AF = cast<MCAlignFragment>(F);
517
480k
    assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
518
480k
519
480k
    uint64_t Count = FragmentSize / AF.getValueSize();
520
480k
521
480k
    // FIXME: This error shouldn't actually occur (the front end should emit
522
480k
    // multiple .align directives to enforce the semantics it wants), but is
523
480k
    // severe enough that we want to report it. How to handle this?
524
480k
    if (Count * AF.getValueSize() != FragmentSize)
525
0
      report_fatal_error("undefined .align directive, value size '" +
526
0
                        Twine(AF.getValueSize()) +
527
0
                        "' is not a divisor of padding size '" +
528
0
                        Twine(FragmentSize) + "'");
529
480k
530
480k
    // See if we are aligning with nops, and if so do that first to try to fill
531
480k
    // the Count bytes.  Then if that did not fill any bytes or there are any
532
480k
    // bytes left to fill use the Value and ValueSize to fill the rest.
533
480k
    // If we are aligning with nops, ask that target to emit the right data.
534
480k
    if (AF.hasEmitNops()) {
535
299k
      if (!Asm.getBackend().writeNopData(OS, Count))
536
0
        report_fatal_error("unable to write nop sequence of " +
537
0
                          Twine(Count) + " bytes");
538
299k
      break;
539
299k
    }
540
180k
541
180k
    // Otherwise, write out in multiples of the value size.
542
1.73M
    
for (uint64_t i = 0; 180k
i != Count;
++i1.55M
) {
543
1.55M
      switch (AF.getValueSize()) {
544
1.55M
      
default: 0
llvm_unreachable0
("Invalid size!");
545
1.55M
      
case 1: OS << char(AF.getValue()); break1.55M
;
546
1.55M
      case 2:
547
3
        support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
548
3
        break;
549
1.55M
      case 4:
550
22
        support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
551
22
        break;
552
1.55M
      case 8:
553
0
        support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
554
0
        break;
555
1.55M
      }
556
1.55M
    }
557
180k
    break;
558
180k
  }
559
180k
560
3.06M
  case MCFragment::FT_Data:
561
3.06M
    ++stats::EmittedDataFragments;
562
3.06M
    OS << cast<MCDataFragment>(F).getContents();
563
3.06M
    break;
564
180k
565
237k
  case MCFragment::FT_Relaxable:
566
237k
    ++stats::EmittedRelaxableFragments;
567
237k
    OS << cast<MCRelaxableFragment>(F).getContents();
568
237k
    break;
569
180k
570
180k
  case MCFragment::FT_CompactEncodedInst:
571
135
    ++stats::EmittedCompactEncodedInstFragments;
572
135
    OS << cast<MCCompactEncodedInstFragment>(F).getContents();
573
135
    break;
574
180k
575
602k
  case MCFragment::FT_Fill: {
576
602k
    ++stats::EmittedFillFragments;
577
602k
    const MCFillFragment &FF = cast<MCFillFragment>(F);
578
602k
    uint64_t V = FF.getValue();
579
602k
    unsigned VSize = FF.getValueSize();
580
602k
    const unsigned MaxChunkSize = 16;
581
602k
    char Data[MaxChunkSize];
582
602k
    // Duplicate V into Data as byte vector to reduce number of
583
602k
    // writes done. As such, do endian conversion here.
584
1.20M
    for (unsigned I = 0; I != VSize; 
++I602k
) {
585
602k
      unsigned index = Endian == support::little ? 
I602k
:
(VSize - I - 1)53
;
586
602k
      Data[I] = uint8_t(V >> (index * 8));
587
602k
    }
588
9.63M
    for (unsigned I = VSize; I < MaxChunkSize; 
++I9.03M
)
589
9.03M
      Data[I] = Data[I - VSize];
590
602k
591
602k
    // Set to largest multiple of VSize in Data.
592
602k
    const unsigned NumPerChunk = MaxChunkSize / VSize;
593
602k
    // Set ChunkSize to largest multiple of VSize in Data
594
602k
    const unsigned ChunkSize = VSize * NumPerChunk;
595
602k
596
602k
    // Do copies by chunk.
597
602k
    StringRef Ref(Data, ChunkSize);
598
134M
    for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; 
++I133M
)
599
133M
      OS << Ref;
600
602k
601
602k
    // do remainder if needed.
602
602k
    unsigned TrailingCount = FragmentSize % ChunkSize;
603
602k
    if (TrailingCount)
604
41.8k
      OS.write(Data, TrailingCount);
605
602k
    break;
606
180k
  }
607
180k
608
180k
  case MCFragment::FT_LEB: {
609
4.82k
    const MCLEBFragment &LF = cast<MCLEBFragment>(F);
610
4.82k
    OS << LF.getContents();
611
4.82k
    break;
612
180k
  }
613
180k
614
180k
  case MCFragment::FT_Padding: {
615
0
    if (!Asm.getBackend().writeNopData(OS, FragmentSize))
616
0
      report_fatal_error("unable to write nop sequence of " +
617
0
                         Twine(FragmentSize) + " bytes");
618
0
    break;
619
0
  }
620
0
621
16
  case MCFragment::FT_SymbolId: {
622
16
    const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
623
16
    support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
624
16
    break;
625
0
  }
626
0
627
19
  case MCFragment::FT_Org: {
628
19
    ++stats::EmittedOrgFragments;
629
19
    const MCOrgFragment &OF = cast<MCOrgFragment>(F);
630
19
631
2.48k
    for (uint64_t i = 0, e = FragmentSize; i != e; 
++i2.46k
)
632
2.46k
      OS << char(OF.getValue());
633
19
634
19
    break;
635
0
  }
636
0
637
965k
  case MCFragment::FT_Dwarf: {
638
965k
    const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
639
965k
    OS << OF.getContents();
640
965k
    break;
641
0
  }
642
131k
  case MCFragment::FT_DwarfFrame: {
643
131k
    const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
644
131k
    OS << CF.getContents();
645
131k
    break;
646
0
  }
647
33
  case MCFragment::FT_CVInlineLines: {
648
33
    const auto &OF = cast<MCCVInlineLineTableFragment>(F);
649
33
    OS << OF.getContents();
650
33
    break;
651
0
  }
652
358
  case MCFragment::FT_CVDefRange: {
653
358
    const auto &DRF = cast<MCCVDefRangeFragment>(F);
654
358
    OS << DRF.getContents();
655
358
    break;
656
0
  }
657
0
  case MCFragment::FT_Dummy:
658
0
    llvm_unreachable("Should not have been added");
659
5.48M
  }
660
5.48M
661
5.48M
  assert(OS.tell() - Start == FragmentSize &&
662
5.48M
         "The stream should advance by fragment size");
663
5.48M
}
664
665
void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
666
557k
                                   const MCAsmLayout &Layout) const {
667
557k
  assert(getBackendPtr() && "Expected assembler backend");
668
557k
669
557k
  // Ignore virtual sections.
670
557k
  if (Sec->isVirtualSection()) {
671
4.39k
    assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
672
4.39k
673
4.39k
    // Check that contents are only things legal inside a virtual section.
674
23.4k
    for (const MCFragment &F : *Sec) {
675
23.4k
      switch (F.getKind()) {
676
23.4k
      
default: 0
llvm_unreachable0
("Invalid fragment in virtual section!");
677
23.4k
      case MCFragment::FT_Data: {
678
9.90k
        // Check that we aren't trying to write a non-zero contents (or fixups)
679
9.90k
        // into a virtual section. This is to support clients which use standard
680
9.90k
        // directives to fill the contents of virtual sections.
681
9.90k
        const MCDataFragment &DF = cast<MCDataFragment>(F);
682
9.90k
        if (DF.fixup_begin() != DF.fixup_end())
683
1
          report_fatal_error("cannot have fixups in virtual section!");
684
10.9k
        
for (unsigned i = 0, e = DF.getContents().size(); 9.90k
i != e;
++i993
)
685
994
          if (DF.getContents()[i]) {
686
1
            if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
687
1
              report_fatal_error("non-zero initializer found in section '" +
688
1
                  ELFSec->getSectionName() + "'");
689
0
            else
690
0
              report_fatal_error("non-zero initializer found in virtual section");
691
1
          }
692
9.90k
        
break9.90k
;
693
9.90k
      }
694
9.90k
      case MCFragment::FT_Align:
695
6.78k
        // Check that we aren't trying to write a non-zero value into a virtual
696
6.78k
        // section.
697
6.78k
        assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
698
6.78k
                cast<MCAlignFragment>(F).getValue() == 0) &&
699
6.78k
               "Invalid align in virtual section!");
700
6.78k
        break;
701
9.90k
      case MCFragment::FT_Fill:
702
6.71k
        assert((cast<MCFillFragment>(F).getValue() == 0) &&
703
6.71k
               "Invalid fill in virtual section!");
704
6.71k
        break;
705
23.4k
      }
706
23.4k
    }
707
4.39k
708
4.39k
    
return4.39k
;
709
552k
  }
710
552k
711
552k
  uint64_t Start = OS.tell();
712
552k
  (void)Start;
713
552k
714
552k
  for (const MCFragment &F : *Sec)
715
5.48M
    writeFragment(OS, *this, Layout, F);
716
552k
717
552k
  assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec));
718
552k
}
719
720
std::tuple<MCValue, uint64_t, bool>
721
MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
722
5.79M
                         const MCFixup &Fixup) {
723
5.79M
  // Evaluate the fixup.
724
5.79M
  MCValue Target;
725
5.79M
  uint64_t FixedValue;
726
5.79M
  bool WasForced;
727
5.79M
  bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
728
5.79M
                                  WasForced);
729
5.79M
  if (!IsResolved) {
730
3.57M
    // The fixup was unresolved, we need a relocation. Inform the object
731
3.57M
    // writer of the relocation, and give it an opportunity to adjust the
732
3.57M
    // fixup value if need be.
733
3.57M
    if (Target.getSymA() && 
Target.getSymB()3.57M
&&
734
3.57M
        
getBackend().requiresDiffExpressionRelocations()69.4k
) {
735
105
      // The fixup represents the difference between two symbols, which the
736
105
      // backend has indicated must be resolved at link time. Split up the fixup
737
105
      // into two relocations, one for the add, and one for the sub, and emit
738
105
      // both of these. The constant will be associated with the add half of the
739
105
      // expression.
740
105
      MCFixup FixupAdd = MCFixup::createAddFor(Fixup);
741
105
      MCValue TargetAdd =
742
105
          MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
743
105
      getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd,
744
105
                                   FixedValue);
745
105
      MCFixup FixupSub = MCFixup::createSubFor(Fixup);
746
105
      MCValue TargetSub = MCValue::get(Target.getSymB());
747
105
      getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub,
748
105
                                   FixedValue);
749
3.57M
    } else {
750
3.57M
      getWriter().recordRelocation(*this, Layout, &F, Fixup, Target,
751
3.57M
                                   FixedValue);
752
3.57M
    }
753
3.57M
  }
754
5.79M
  return std::make_tuple(Target, FixedValue, IsResolved);
755
5.79M
}
756
757
20.5k
void MCAssembler::layout(MCAsmLayout &Layout) {
758
20.5k
  assert(getBackendPtr() && "Expected assembler backend");
759
20.5k
  DEBUG_WITH_TYPE("mc-dump", {
760
20.5k
      errs() << "assembler backend - pre-layout\n--\n";
761
20.5k
      dump(); });
762
20.5k
763
20.5k
  // Create dummy fragments and assign section ordinals.
764
20.5k
  unsigned SectionIndex = 0;
765
557k
  for (MCSection &Sec : *this) {
766
557k
    // Create dummy fragments to eliminate any empty sections, this simplifies
767
557k
    // layout.
768
557k
    if (Sec.getFragmentList().empty())
769
1.20k
      new MCDataFragment(&Sec);
770
557k
771
557k
    Sec.setOrdinal(SectionIndex++);
772
557k
  }
773
20.5k
774
20.5k
  // Assign layout order indices to sections and fragments.
775
578k
  for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; 
++i557k
) {
776
557k
    MCSection *Sec = Layout.getSectionOrder()[i];
777
557k
    Sec->setLayoutOrder(i);
778
557k
779
557k
    unsigned FragmentIndex = 0;
780
557k
    for (MCFragment &Frag : *Sec)
781
5.51M
      Frag.setLayoutOrder(FragmentIndex++);
782
557k
  }
783
20.5k
784
20.5k
  // Layout until everything fits.
785
23.7k
  while (layoutOnce(Layout))
786
3.21k
    if (getContext().hadError())
787
0
      return;
788
20.5k
789
20.5k
  DEBUG_WITH_TYPE("mc-dump", {
790
20.5k
      errs() << "assembler backend - post-relaxation\n--\n";
791
20.5k
      dump(); });
792
20.5k
793
20.5k
  // Finalize the layout, including fragment lowering.
794
20.5k
  finishLayout(Layout);
795
20.5k
796
20.5k
  DEBUG_WITH_TYPE("mc-dump", {
797
20.5k
      errs() << "assembler backend - final-layout\n--\n";
798
20.5k
      dump(); });
799
20.5k
800
20.5k
  // Allow the object writer a chance to perform post-layout binding (for
801
20.5k
  // example, to set the index fields in the symbol data).
802
20.5k
  getWriter().executePostLayoutBinding(*this, Layout);
803
20.5k
804
20.5k
  // Evaluate and apply the fixups, generating relocation entries as necessary.
805
557k
  for (MCSection &Sec : *this) {
806
5.51M
    for (MCFragment &Frag : Sec) {
807
5.51M
      // Data and relaxable fragments both have fixups.  So only process
808
5.51M
      // those here.
809
5.51M
      // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
810
5.51M
      // being templated makes this tricky.
811
5.51M
      if (isa<MCEncodedFragment>(&Frag) &&
812
5.51M
          
isa<MCCompactEncodedInstFragment>(&Frag)4.40M
)
813
135
        continue;
814
5.51M
      if (!isa<MCEncodedFragment>(&Frag) && 
!isa<MCCVDefRangeFragment>(&Frag)1.10M
&&
815
5.51M
          
!isa<MCAlignFragment>(&Frag)1.10M
)
816
614k
        continue;
817
4.89M
      ArrayRef<MCFixup> Fixups;
818
4.89M
      MutableArrayRef<char> Contents;
819
4.89M
      const MCSubtargetInfo *STI = nullptr;
820
4.89M
      if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
821
3.07M
        Fixups = FragWithFixups->getFixups();
822
3.07M
        Contents = FragWithFixups->getContents();
823
3.07M
        STI = FragWithFixups->getSubtargetInfo();
824
3.07M
        assert(!FragWithFixups->hasInstructions() || STI != nullptr);
825
3.07M
      } else 
if (auto *1.82M
FragWithFixups1.82M
= dyn_cast<MCRelaxableFragment>(&Frag)) {
826
237k
        Fixups = FragWithFixups->getFixups();
827
237k
        Contents = FragWithFixups->getContents();
828
237k
        STI = FragWithFixups->getSubtargetInfo();
829
237k
        assert(!FragWithFixups->hasInstructions() || STI != nullptr);
830
1.58M
      } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
831
358
        Fixups = FragWithFixups->getFixups();
832
358
        Contents = FragWithFixups->getContents();
833
1.58M
      } else if (auto *FragWithFixups = dyn_cast<MCDwarfLineAddrFragment>(&Frag)) {
834
965k
        Fixups = FragWithFixups->getFixups();
835
965k
        Contents = FragWithFixups->getContents();
836
965k
      } else 
if (auto *619k
AF619k
= dyn_cast<MCAlignFragment>(&Frag)) {
837
487k
        // Insert fixup type for code alignment if the target define
838
487k
        // shouldInsertFixupForCodeAlign target hook.
839
487k
        if (Sec.UseCodeAlign() && 
AF->hasEmitNops()298k
) {
840
298k
          getBackend().shouldInsertFixupForCodeAlign(*this, Layout, *AF);
841
298k
        }
842
487k
        continue;
843
487k
      } else 
if (auto *131k
FragWithFixups131k
=
844
131k
                     dyn_cast<MCDwarfCallFrameFragment>(&Frag)) {
845
131k
        Fixups = FragWithFixups->getFixups();
846
131k
        Contents = FragWithFixups->getContents();
847
131k
      } else
848
131k
        
llvm_unreachable1
("Unknown fragment with fixups!");
849
5.79M
      
for (const MCFixup &Fixup : Fixups)4.40M
{
850
5.79M
        uint64_t FixedValue;
851
5.79M
        bool IsResolved;
852
5.79M
        MCValue Target;
853
5.79M
        std::tie(Target, FixedValue, IsResolved) =
854
5.79M
            handleFixup(Layout, Frag, Fixup);
855
5.79M
        getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
856
5.79M
                                IsResolved, STI);
857
5.79M
      }
858
4.40M
    }
859
557k
  }
860
20.5k
}
861
862
20.4k
void MCAssembler::Finish() {
863
20.4k
  // Create the layout object.
864
20.4k
  MCAsmLayout Layout(*this);
865
20.4k
  layout(Layout);
866
20.4k
867
20.4k
  // Write the object file.
868
20.4k
  stats::ObjectBytes += getWriter().writeObject(*this, Layout);
869
20.4k
}
870
871
bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
872
                                       const MCRelaxableFragment *DF,
873
619k
                                       const MCAsmLayout &Layout) const {
874
619k
  assert(getBackendPtr() && "Expected assembler backend");
875
619k
  MCValue Target;
876
619k
  uint64_t Value;
877
619k
  bool WasForced;
878
619k
  bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
879
619k
  if (Target.getSymA() &&
880
619k
      
Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8619k
&&
881
619k
      
Fixup.getKind() == FK_Data_12
)
882
2
    return false;
883
619k
  return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
884
619k
                                                   Layout, WasForced);
885
619k
}
886
887
bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
888
825k
                                          const MCAsmLayout &Layout) const {
889
825k
  assert(getBackendPtr() && "Expected assembler backend");
890
825k
  // If this inst doesn't ever need relaxation, ignore it. This occurs when we
891
825k
  // are intentionally pushing out inst fragments, or because we relaxed a
892
825k
  // previous instruction to one that doesn't need relaxation.
893
825k
  if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
894
204k
    return false;
895
621k
896
621k
  for (const MCFixup &Fixup : F->getFixups())
897
619k
    if (fixupNeedsRelaxation(Fixup, F, Layout))
898
67.6k
      return true;
899
621k
900
621k
  
return false553k
;
901
621k
}
902
903
bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
904
825k
                                   MCRelaxableFragment &F) {
905
825k
  assert(getEmitterPtr() &&
906
825k
         "Expected CodeEmitter defined for relaxInstruction");
907
825k
  if (!fragmentNeedsRelaxation(&F, Layout))
908
757k
    return false;
909
67.6k
910
67.6k
  ++stats::RelaxedInstructions;
911
67.6k
912
67.6k
  // FIXME-PERF: We could immediately lower out instructions if we can tell
913
67.6k
  // they are fully resolved, to avoid retesting on later passes.
914
67.6k
915
67.6k
  // Relax the fragment.
916
67.6k
917
67.6k
  MCInst Relaxed;
918
67.6k
  getBackend().relaxInstruction(F.getInst(), *F.getSubtargetInfo(), Relaxed);
919
67.6k
920
67.6k
  // Encode the new instruction.
921
67.6k
  //
922
67.6k
  // FIXME-PERF: If it matters, we could let the target do this. It can
923
67.6k
  // probably do so more efficiently in many cases.
924
67.6k
  SmallVector<MCFixup, 4> Fixups;
925
67.6k
  SmallString<256> Code;
926
67.6k
  raw_svector_ostream VecOS(Code);
927
67.6k
  getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
928
67.6k
929
67.6k
  // Update the fragment.
930
67.6k
  F.setInst(Relaxed);
931
67.6k
  F.getContents() = Code;
932
67.6k
  F.getFixups() = Fixups;
933
67.6k
934
67.6k
  return true;
935
67.6k
}
936
937
bool MCAssembler::relaxPaddingFragment(MCAsmLayout &Layout,
938
0
                                       MCPaddingFragment &PF) {
939
0
  assert(getBackendPtr() && "Expected assembler backend");
940
0
  uint64_t OldSize = PF.getSize();
941
0
  if (!getBackend().relaxFragment(&PF, Layout))
942
0
    return false;
943
0
  uint64_t NewSize = PF.getSize();
944
0
945
0
  ++stats::PaddingFragmentsRelaxations;
946
0
  stats::PaddingFragmentsBytes += NewSize;
947
0
  stats::PaddingFragmentsBytes -= OldSize;
948
0
  return true;
949
0
}
950
951
10.5k
bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
952
10.5k
  uint64_t OldSize = LF.getContents().size();
953
10.5k
  int64_t Value;
954
10.5k
  bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
955
10.5k
  if (!Abs)
956
1
    report_fatal_error("sleb128 and uleb128 expressions must be absolute");
957
10.5k
  SmallString<8> &Data = LF.getContents();
958
10.5k
  Data.clear();
959
10.5k
  raw_svector_ostream OSE(Data);
960
10.5k
  // The compiler can generate EH table assembly that is impossible to assemble
961
10.5k
  // without either adding padding to an LEB fragment or adding extra padding
962
10.5k
  // to a later alignment fragment. To accommodate such tables, relaxation can
963
10.5k
  // only increase an LEB fragment size here, not decrease it. See PR35809.
964
10.5k
  if (LF.isSigned())
965
3
    encodeSLEB128(Value, OSE, OldSize);
966
10.5k
  else
967
10.5k
    encodeULEB128(Value, OSE, OldSize);
968
10.5k
  return OldSize != LF.getContents().size();
969
10.5k
}
970
971
bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
972
2.89M
                                     MCDwarfLineAddrFragment &DF) {
973
2.89M
  MCContext &Context = Layout.getAssembler().getContext();
974
2.89M
  uint64_t OldSize = DF.getContents().size();
975
2.89M
  int64_t AddrDelta;
976
2.89M
  bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
977
2.89M
  assert(Abs && "We created a line delta with an invalid expression");
978
2.89M
  (void)Abs;
979
2.89M
  int64_t LineDelta;
980
2.89M
  LineDelta = DF.getLineDelta();
981
2.89M
  SmallVectorImpl<char> &Data = DF.getContents();
982
2.89M
  Data.clear();
983
2.89M
  raw_svector_ostream OSE(Data);
984
2.89M
  DF.getFixups().clear();
985
2.89M
986
2.89M
  if (!getBackend().requiresDiffExpressionRelocations()) {
987
2.89M
    MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
988
2.89M
                            AddrDelta, OSE);
989
2.89M
  } else {
990
36
    uint32_t Offset;
991
36
    uint32_t Size;
992
36
    bool SetDelta = MCDwarfLineAddr::FixedEncode(Context,
993
36
                                                 getDWARFLinetableParams(),
994
36
                                                 LineDelta, AddrDelta,
995
36
                                                 OSE, &Offset, &Size);
996
36
    // Add Fixups for address delta or new address.
997
36
    const MCExpr *FixupExpr;
998
36
    if (SetDelta) {
999
36
      FixupExpr = &DF.getAddrDelta();
1000
36
    } else {
1001
0
      const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta());
1002
0
      FixupExpr = ABE->getLHS();
1003
0
    }
1004
36
    DF.getFixups().push_back(
1005
36
        MCFixup::create(Offset, FixupExpr,
1006
36
                        MCFixup::getKindForSize(Size, false /*isPCRel*/)));
1007
36
  }
1008
2.89M
1009
2.89M
  return OldSize != Data.size();
1010
2.89M
}
1011
1012
bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1013
393k
                                              MCDwarfCallFrameFragment &DF) {
1014
393k
  MCContext &Context = Layout.getAssembler().getContext();
1015
393k
  uint64_t OldSize = DF.getContents().size();
1016
393k
  int64_t AddrDelta;
1017
393k
  bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1018
393k
  assert(Abs && "We created call frame with an invalid expression");
1019
393k
  (void) Abs;
1020
393k
  SmallVectorImpl<char> &Data = DF.getContents();
1021
393k
  Data.clear();
1022
393k
  raw_svector_ostream OSE(Data);
1023
393k
  DF.getFixups().clear();
1024
393k
1025
393k
  if (getBackend().requiresDiffExpressionRelocations()) {
1026
93
    uint32_t Offset;
1027
93
    uint32_t Size;
1028
93
    MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE, &Offset,
1029
93
                                          &Size);
1030
93
    if (Size) {
1031
87
      DF.getFixups().push_back(MCFixup::create(
1032
87
          Offset, &DF.getAddrDelta(),
1033
87
          MCFixup::getKindForSizeInBits(Size /*In bits.*/, false /*isPCRel*/)));
1034
87
    }
1035
393k
  } else {
1036
393k
    MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1037
393k
  }
1038
393k
1039
393k
  return OldSize != Data.size();
1040
393k
}
1041
1042
bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1043
99
                                         MCCVInlineLineTableFragment &F) {
1044
99
  unsigned OldSize = F.getContents().size();
1045
99
  getContext().getCVContext().encodeInlineLineTable(Layout, F);
1046
99
  return OldSize != F.getContents().size();
1047
99
}
1048
1049
bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1050
1.07k
                                  MCCVDefRangeFragment &F) {
1051
1.07k
  unsigned OldSize = F.getContents().size();
1052
1.07k
  getContext().getCVContext().encodeDefRange(Layout, F);
1053
1.07k
  return OldSize != F.getContents().size();
1054
1.07k
}
1055
1056
599k
bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1057
599k
  // Holds the first fragment which needed relaxing during this layout. It will
1058
599k
  // remain NULL if none were relaxed.
1059
599k
  // When a fragment is relaxed, all the fragments following it should get
1060
599k
  // invalidated because their offset is going to change.
1061
599k
  MCFragment *FirstRelaxedFragment = nullptr;
1062
599k
1063
599k
  // Attempt to relax all the fragments in the section.
1064
12.3M
  for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; 
++I11.7M
) {
1065
11.7M
    // Check if this is a fragment that needs relaxation.
1066
11.7M
    bool RelaxedFrag = false;
1067
11.7M
    switch(I->getKind()) {
1068
11.7M
    default:
1069
7.59M
      break;
1070
11.7M
    case MCFragment::FT_Relaxable:
1071
825k
      assert(!getRelaxAll() &&
1072
825k
             "Did not expect a MCRelaxableFragment in RelaxAll mode");
1073
825k
      RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1074
825k
      break;
1075
11.7M
    case MCFragment::FT_Dwarf:
1076
2.89M
      RelaxedFrag = relaxDwarfLineAddr(Layout,
1077
2.89M
                                       *cast<MCDwarfLineAddrFragment>(I));
1078
2.89M
      break;
1079
11.7M
    case MCFragment::FT_DwarfFrame:
1080
393k
      RelaxedFrag =
1081
393k
        relaxDwarfCallFrameFragment(Layout,
1082
393k
                                    *cast<MCDwarfCallFrameFragment>(I));
1083
393k
      break;
1084
11.7M
    case MCFragment::FT_LEB:
1085
10.5k
      RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1086
10.5k
      break;
1087
11.7M
    case MCFragment::FT_Padding:
1088
0
      RelaxedFrag = relaxPaddingFragment(Layout, *cast<MCPaddingFragment>(I));
1089
0
      break;
1090
11.7M
    case MCFragment::FT_CVInlineLines:
1091
99
      RelaxedFrag =
1092
99
          relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
1093
99
      break;
1094
11.7M
    case MCFragment::FT_CVDefRange:
1095
1.07k
      RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
1096
1.07k
      break;
1097
11.7M
    }
1098
11.7M
    if (RelaxedFrag && 
!FirstRelaxedFragment1.09M
)
1099
5.76k
      FirstRelaxedFragment = &*I;
1100
11.7M
  }
1101
599k
  if (FirstRelaxedFragment) {
1102
5.76k
    Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1103
5.76k
    return true;
1104
5.76k
  }
1105
593k
  return false;
1106
593k
}
1107
1108
23.7k
bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1109
23.7k
  ++stats::RelaxationSteps;
1110
23.7k
1111
23.7k
  bool WasRelaxed = false;
1112
617k
  for (iterator it = begin(), ie = end(); it != ie; 
++it593k
) {
1113
593k
    MCSection &Sec = *it;
1114
599k
    while (layoutSectionOnce(Layout, Sec))
1115
5.76k
      WasRelaxed = true;
1116
593k
  }
1117
23.7k
1118
23.7k
  return WasRelaxed;
1119
23.7k
}
1120
1121
20.5k
void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1122
20.5k
  assert(getBackendPtr() && "Expected assembler backend");
1123
20.5k
  // The layout is done. Mark every fragment as valid.
1124
578k
  for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; 
++i557k
) {
1125
557k
    MCSection &Section = *Layout.getSectionOrder()[i];
1126
557k
    Layout.getFragmentOffset(&*Section.rbegin());
1127
557k
    computeFragmentSize(Layout, *Section.rbegin());
1128
557k
  }
1129
20.5k
  getBackend().finishLayout(*this, Layout);
1130
20.5k
}
1131
1132
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1133
LLVM_DUMP_METHOD void MCAssembler::dump() const{
1134
  raw_ostream &OS = errs();
1135
1136
  OS << "<MCAssembler\n";
1137
  OS << "  Sections:[\n    ";
1138
  for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1139
    if (it != begin()) OS << ",\n    ";
1140
    it->dump();
1141
  }
1142
  OS << "],\n";
1143
  OS << "  Symbols:[";
1144
1145
  for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1146
    if (it != symbol_begin()) OS << ",\n           ";
1147
    OS << "(";
1148
    it->dump();
1149
    OS << ", Index:" << it->getIndex() << ", ";
1150
    OS << ")";
1151
  }
1152
  OS << "]>\n";
1153
}
1154
#endif