LLVM  3.7.0
MCAssembler.cpp
Go to the documentation of this file.
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/LEB128.h"
32 #include <tuple>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "assembler"
36 
37 namespace {
38 namespace stats {
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41  "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43  "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45  "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47  "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49  "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51  "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
57 }
58 }
59 
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
64 
65 /* *** */
66 
68  : Assembler(Asm), LastValidFragment()
69  {
70  // Compute the section layout order. Virtual sections must go last.
71  for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72  if (!it->isVirtualSection())
73  SectionOrder.push_back(&*it);
74  for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75  if (it->isVirtualSection())
76  SectionOrder.push_back(&*it);
77 }
78 
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80  const MCSection *Sec = F->getParent();
81  const MCFragment *LastValid = LastValidFragment.lookup(Sec);
82  if (!LastValid)
83  return false;
84  assert(LastValid->getParent() == Sec);
85  return F->getLayoutOrder() <= LastValid->getLayoutOrder();
86 }
87 
89  // If this fragment wasn't already valid, we don't need to do anything.
90  if (!isFragmentValid(F))
91  return;
92 
93  // Otherwise, reset the last valid fragment to the previous fragment
94  // (if this is the first fragment, it will be NULL).
95  LastValidFragment[F->getParent()] = F->getPrevNode();
96 }
97 
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99  MCSection *Sec = F->getParent();
100  MCFragment *Cur = LastValidFragment[Sec];
101  if (!Cur)
102  Cur = Sec->begin();
103  else
104  Cur = Cur->getNextNode();
105 
106  // Advance the layout position until the fragment is valid.
107  while (!isFragmentValid(F)) {
108  assert(Cur && "Layout bookkeeping error");
109  const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
110  Cur = Cur->getNextNode();
111  }
112 }
113 
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
115  ensureValid(F);
116  assert(F->Offset != ~UINT64_C(0) && "Address not set!");
117  return F->Offset;
118 }
119 
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122  bool ReportError, uint64_t &Val) {
123  if (!S.getFragment()) {
124  if (ReportError)
125  report_fatal_error("unable to evaluate offset to undefined symbol '" +
126  S.getName() + "'");
127  return false;
128  }
129  Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
130  return true;
131 }
132 
133 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
134  bool ReportError, uint64_t &Val) {
135  if (!S.isVariable())
136  return getLabelOffset(Layout, S, ReportError, Val);
137 
138  // If SD is a variable, evaluate it.
139  MCValue Target;
140  if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
141  report_fatal_error("unable to evaluate offset for variable '" +
142  S.getName() + "'");
143 
144  uint64_t Offset = Target.getConstant();
145 
146  const MCSymbolRefExpr *A = Target.getSymA();
147  if (A) {
148  uint64_t ValA;
149  if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
150  return false;
151  Offset += ValA;
152  }
153 
154  const MCSymbolRefExpr *B = Target.getSymB();
155  if (B) {
156  uint64_t ValB;
157  if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
158  return false;
159  Offset -= ValB;
160  }
161 
162  Val = Offset;
163  return true;
164 }
165 
166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167  return getSymbolOffsetImpl(*this, S, false, Val);
168 }
169 
170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
171  uint64_t Val;
172  getSymbolOffsetImpl(*this, S, true, Val);
173  return Val;
174 }
175 
177  if (!Symbol.isVariable())
178  return &Symbol;
179 
180  const MCExpr *Expr = Symbol.getVariableValue();
181  MCValue Value;
182  if (!Expr->evaluateAsValue(Value, *this))
183  llvm_unreachable("Invalid Expression");
184 
185  const MCSymbolRefExpr *RefB = Value.getSymB();
186  if (RefB)
187  Assembler.getContext().reportFatalError(
188  SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
189  "' could not be evaluated in a subtraction expression");
190 
191  const MCSymbolRefExpr *A = Value.getSymA();
192  if (!A)
193  return nullptr;
194 
195  const MCSymbol &ASym = A->getSymbol();
196  const MCAssembler &Asm = getAssembler();
197  if (ASym.isCommon()) {
198  // FIXME: we should probably add a SMLoc to MCExpr.
200  "Common symbol " + ASym.getName() +
201  " cannot be used in assignment expr");
202  }
203 
204  return &ASym;
205 }
206 
207 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
208  // The size is the last fragment's end offset.
209  const MCFragment &F = Sec->getFragmentList().back();
210  return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
211 }
212 
213 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
214  // Virtual sections have no file size.
215  if (Sec->isVirtualSection())
216  return 0;
217 
218  // Otherwise, the file size is the same as the address space size.
219  return getSectionAddressSize(Sec);
220 }
221 
222 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
223  const MCFragment *F,
224  uint64_t FOffset, uint64_t FSize) {
225  uint64_t BundleSize = Assembler.getBundleAlignSize();
226  assert(BundleSize > 0 &&
227  "computeBundlePadding should only be called if bundling is enabled");
228  uint64_t BundleMask = BundleSize - 1;
229  uint64_t OffsetInBundle = FOffset & BundleMask;
230  uint64_t EndOfFragment = OffsetInBundle + FSize;
231 
232  // There are two kinds of bundling restrictions:
233  //
234  // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
235  // *end* on a bundle boundary.
236  // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
237  // would, add padding until the end of the bundle so that the fragment
238  // will start in a new one.
239  if (F->alignToBundleEnd()) {
240  // Three possibilities here:
241  //
242  // A) The fragment just happens to end at a bundle boundary, so we're good.
243  // B) The fragment ends before the current bundle boundary: pad it just
244  // enough to reach the boundary.
245  // C) The fragment ends after the current bundle boundary: pad it until it
246  // reaches the end of the next bundle boundary.
247  //
248  // Note: this code could be made shorter with some modulo trickery, but it's
249  // intentionally kept in its more explicit form for simplicity.
250  if (EndOfFragment == BundleSize)
251  return 0;
252  else if (EndOfFragment < BundleSize)
253  return BundleSize - EndOfFragment;
254  else { // EndOfFragment > BundleSize
255  return 2 * BundleSize - EndOfFragment;
256  }
257  } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
258  return BundleSize - OffsetInBundle;
259  else
260  return 0;
261 }
262 
263 /* *** */
264 
266  V->destroy();
267 }
268 
269 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
270  AlignToBundleEnd(false), BundlePadding(0) {
271 }
272 
273 MCFragment::~MCFragment() { }
274 
275 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
276  uint8_t BundlePadding, MCSection *Parent)
277  : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
278  BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
279  Offset(~UINT64_C(0)) {
280  if (Parent)
281  Parent->getFragmentList().push_back(this);
282 }
283 
285  // First check if we are the sentinal.
286  if (Kind == FragmentType(~0)) {
287  delete this;
288  return;
289  }
290 
291  switch (Kind) {
292  case FT_Align:
293  delete cast<MCAlignFragment>(this);
294  return;
295  case FT_Data:
296  delete cast<MCDataFragment>(this);
297  return;
299  delete cast<MCCompactEncodedInstFragment>(this);
300  return;
301  case FT_Fill:
302  delete cast<MCFillFragment>(this);
303  return;
304  case FT_Relaxable:
305  delete cast<MCRelaxableFragment>(this);
306  return;
307  case FT_Org:
308  delete cast<MCOrgFragment>(this);
309  return;
310  case FT_Dwarf:
311  delete cast<MCDwarfLineAddrFragment>(this);
312  return;
313  case FT_DwarfFrame:
314  delete cast<MCDwarfCallFrameFragment>(this);
315  return;
316  case FT_LEB:
317  delete cast<MCLEBFragment>(this);
318  return;
319  case FT_SafeSEH:
320  delete cast<MCSafeSEHFragment>(this);
321  return;
322  }
323 }
324 
325 /* *** */
326 
327 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
328  MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
329  raw_ostream &OS_)
330  : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
331  OS(OS_), BundleAlignSize(0), RelaxAll(false),
332  SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
333  VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
334 }
335 
337 }
338 
340  Sections.clear();
341  Symbols.clear();
342  IndirectSymbols.clear();
343  DataRegions.clear();
344  LinkerOptions.clear();
345  FileNames.clear();
346  ThumbFuncs.clear();
347  BundleAlignSize = 0;
348  RelaxAll = false;
349  SubsectionsViaSymbols = false;
350  ELFHeaderEFlags = 0;
351  LOHContainer.reset();
352  VersionMinInfo.Major = 0;
353 
354  // reset objects owned by us
355  getBackend().reset();
356  getEmitter().reset();
357  getWriter().reset();
359 }
360 
362  if (ThumbFuncs.count(Symbol))
363  return true;
364 
365  if (!Symbol->isVariable())
366  return false;
367 
368  // FIXME: It looks like gas supports some cases of the form "foo + 2". It
369  // is not clear if that is a bug or a feature.
370  const MCExpr *Expr = Symbol->getVariableValue();
371  const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
372  if (!Ref)
373  return false;
374 
375  if (Ref->getKind() != MCSymbolRefExpr::VK_None)
376  return false;
377 
378  const MCSymbol &Sym = Ref->getSymbol();
379  if (!isThumbFunc(&Sym))
380  return false;
381 
382  ThumbFuncs.insert(Symbol); // Cache it.
383  return true;
384 }
385 
387  // Non-temporary labels should always be visible to the linker.
388  if (!Symbol.isTemporary())
389  return true;
390 
391  // Absolute temporary labels are never visible.
392  if (!Symbol.isInSection())
393  return false;
394 
395  if (Symbol.isUsedInReloc())
396  return true;
397 
398  return false;
399 }
400 
401 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
402  // Linker visible symbols define atoms.
403  if (isSymbolLinkerVisible(S))
404  return &S;
405 
406  // Absolute and undefined symbols have no defining atom.
407  if (!S.getFragment())
408  return nullptr;
409 
410  // Non-linker visible symbols in sections which can't be atomized have no
411  // defining atom.
413  *S.getFragment()->getParent()))
414  return nullptr;
415 
416  // Otherwise, return the atom for the containing fragment.
417  return S.getFragment()->getAtom();
418 }
419 
420 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
421  const MCFixup &Fixup, const MCFragment *DF,
422  MCValue &Target, uint64_t &Value) const {
423  ++stats::evaluateFixup;
424 
425  // FIXME: This code has some duplication with recordRelocation. We should
426  // probably merge the two into a single callback that tries to evaluate a
427  // fixup and records a relocation if one is needed.
428  const MCExpr *Expr = Fixup.getValue();
429  if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
430  getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
431 
432  bool IsPCRel = Backend.getFixupKindInfo(
434 
435  bool IsResolved;
436  if (IsPCRel) {
437  if (Target.getSymB()) {
438  IsResolved = false;
439  } else if (!Target.getSymA()) {
440  IsResolved = false;
441  } else {
442  const MCSymbolRefExpr *A = Target.getSymA();
443  const MCSymbol &SA = A->getSymbol();
444  if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
445  IsResolved = false;
446  } else {
448  *this, SA, *DF, false, true);
449  }
450  }
451  } else {
452  IsResolved = Target.isAbsolute();
453  }
454 
455  Value = Target.getConstant();
456 
457  if (const MCSymbolRefExpr *A = Target.getSymA()) {
458  const MCSymbol &Sym = A->getSymbol();
459  if (Sym.isDefined())
460  Value += Layout.getSymbolOffset(Sym);
461  }
462  if (const MCSymbolRefExpr *B = Target.getSymB()) {
463  const MCSymbol &Sym = B->getSymbol();
464  if (Sym.isDefined())
465  Value -= Layout.getSymbolOffset(Sym);
466  }
467 
468 
469  bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
471  assert((ShouldAlignPC ? IsPCRel : true) &&
472  "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
473 
474  if (IsPCRel) {
475  uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
476 
477  // A number of ARM fixups in Thumb mode require that the effective PC
478  // address be determined as the 32-bit aligned version of the actual offset.
479  if (ShouldAlignPC) Offset &= ~0x3;
480  Value -= Offset;
481  }
482 
483  // Let the backend adjust the fixup value if necessary, including whether
484  // we need a relocation.
485  Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
486  IsResolved);
487 
488  return IsResolved;
489 }
490 
492  const MCFragment &F) const {
493  switch (F.getKind()) {
494  case MCFragment::FT_Data:
495  return cast<MCDataFragment>(F).getContents().size();
497  return cast<MCRelaxableFragment>(F).getContents().size();
499  return cast<MCCompactEncodedInstFragment>(F).getContents().size();
500  case MCFragment::FT_Fill:
501  return cast<MCFillFragment>(F).getSize();
502 
503  case MCFragment::FT_LEB:
504  return cast<MCLEBFragment>(F).getContents().size();
505 
507  return 4;
508 
509  case MCFragment::FT_Align: {
510  const MCAlignFragment &AF = cast<MCAlignFragment>(F);
511  unsigned Offset = Layout.getFragmentOffset(&AF);
512  unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
513  // If we are padding with nops, force the padding to be larger than the
514  // minimum nop size.
515  if (Size > 0 && AF.hasEmitNops()) {
516  while (Size % getBackend().getMinimumNopSize())
517  Size += AF.getAlignment();
518  }
519  if (Size > AF.getMaxBytesToEmit())
520  return 0;
521  return Size;
522  }
523 
524  case MCFragment::FT_Org: {
525  const MCOrgFragment &OF = cast<MCOrgFragment>(F);
526  int64_t TargetLocation;
527  if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
528  report_fatal_error("expected assembly-time absolute expression");
529 
530  // FIXME: We need a way to communicate this error.
531  uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
532  int64_t Size = TargetLocation - FragmentOffset;
533  if (Size < 0 || Size >= 0x40000000)
534  report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
535  "' (at offset '" + Twine(FragmentOffset) + "')");
536  return Size;
537  }
538 
540  return cast<MCDwarfLineAddrFragment>(F).getContents().size();
542  return cast<MCDwarfCallFrameFragment>(F).getContents().size();
543  }
544 
545  llvm_unreachable("invalid fragment kind");
546 }
547 
549  MCFragment *Prev = F->getPrevNode();
550 
551  // We should never try to recompute something which is valid.
552  assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
553  // We should never try to compute the fragment layout if its predecessor
554  // isn't valid.
555  assert((!Prev || isFragmentValid(Prev)) &&
556  "Attempt to compute fragment before its predecessor!");
557 
558  ++stats::FragmentLayouts;
559 
560  // Compute fragment offset and size.
561  if (Prev)
562  F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
563  else
564  F->Offset = 0;
565  LastValidFragment[F->getParent()] = F;
566 
567  // If bundling is enabled and this fragment has instructions in it, it has to
568  // obey the bundling restrictions. With padding, we'll have:
569  //
570  //
571  // BundlePadding
572  // |||
573  // -------------------------------------
574  // Prev |##########| F |
575  // -------------------------------------
576  // ^
577  // |
578  // F->Offset
579  //
580  // The fragment's offset will point to after the padding, and its computed
581  // size won't include the padding.
582  //
583  // When the -mc-relax-all flag is used, we optimize bundling by writting the
584  // padding directly into fragments when the instructions are emitted inside
585  // the streamer. When the fragment is larger than the bundle size, we need to
586  // ensure that it's bundle aligned. This means that if we end up with
587  // multiple fragments, we must emit bundle padding between fragments.
588  //
589  // ".align N" is an example of a directive that introduces multiple
590  // fragments. We could add a special case to handle ".align N" by emitting
591  // within-fragment padding (which would produce less padding when N is less
592  // than the bundle size), but for now we don't.
593  //
594  if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
595  assert(isa<MCEncodedFragment>(F) &&
596  "Only MCEncodedFragment implementations have instructions");
597  uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
598 
599  if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
600  report_fatal_error("Fragment can't be larger than a bundle size");
601 
602  uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
603  F->Offset, FSize);
604  if (RequiredBundlePadding > UINT8_MAX)
605  report_fatal_error("Padding cannot exceed 255 bytes");
606  F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
607  F->Offset += RequiredBundlePadding;
608  }
609 }
610 
611 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
612  bool New = !Symbol.isRegistered();
613  if (Created)
614  *Created = New;
615  if (New) {
616  Symbol.setIsRegistered(true);
617  Symbols.push_back(&Symbol);
618  }
619 }
620 
621 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
622  MCObjectWriter *OW) const {
623  // Should NOP padding be written out before this fragment?
624  unsigned BundlePadding = F.getBundlePadding();
625  if (BundlePadding > 0) {
626  assert(isBundlingEnabled() &&
627  "Writing bundle padding with disabled bundling");
628  assert(F.hasInstructions() &&
629  "Writing bundle padding for a fragment without instructions");
630 
631  unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
632  if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
633  // If the padding itself crosses a bundle boundary, it must be emitted
634  // in 2 pieces, since even nop instructions must not cross boundaries.
635  // v--------------v <- BundleAlignSize
636  // v---------v <- BundlePadding
637  // ----------------------------
638  // | Prev |####|####| F |
639  // ----------------------------
640  // ^-------------------^ <- TotalLength
641  unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
642  if (!getBackend().writeNopData(DistanceToBoundary, OW))
643  report_fatal_error("unable to write NOP sequence of " +
644  Twine(DistanceToBoundary) + " bytes");
645  BundlePadding -= DistanceToBoundary;
646  }
647  if (!getBackend().writeNopData(BundlePadding, OW))
648  report_fatal_error("unable to write NOP sequence of " +
649  Twine(BundlePadding) + " bytes");
650  }
651 }
652 
653 /// \brief Write the fragment \p F to the output file.
654 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
655  const MCFragment &F) {
656  MCObjectWriter *OW = &Asm.getWriter();
657 
658  // FIXME: Embed in fragments instead?
659  uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
660 
661  Asm.writeFragmentPadding(F, FragmentSize, OW);
662 
663  // This variable (and its dummy usage) is to participate in the assert at
664  // the end of the function.
665  uint64_t Start = OW->getStream().tell();
666  (void) Start;
667 
668  ++stats::EmittedFragments;
669 
670  switch (F.getKind()) {
671  case MCFragment::FT_Align: {
672  ++stats::EmittedAlignFragments;
673  const MCAlignFragment &AF = cast<MCAlignFragment>(F);
674  assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
675 
676  uint64_t Count = FragmentSize / AF.getValueSize();
677 
678  // FIXME: This error shouldn't actually occur (the front end should emit
679  // multiple .align directives to enforce the semantics it wants), but is
680  // severe enough that we want to report it. How to handle this?
681  if (Count * AF.getValueSize() != FragmentSize)
682  report_fatal_error("undefined .align directive, value size '" +
683  Twine(AF.getValueSize()) +
684  "' is not a divisor of padding size '" +
685  Twine(FragmentSize) + "'");
686 
687  // See if we are aligning with nops, and if so do that first to try to fill
688  // the Count bytes. Then if that did not fill any bytes or there are any
689  // bytes left to fill use the Value and ValueSize to fill the rest.
690  // If we are aligning with nops, ask that target to emit the right data.
691  if (AF.hasEmitNops()) {
692  if (!Asm.getBackend().writeNopData(Count, OW))
693  report_fatal_error("unable to write nop sequence of " +
694  Twine(Count) + " bytes");
695  break;
696  }
697 
698  // Otherwise, write out in multiples of the value size.
699  for (uint64_t i = 0; i != Count; ++i) {
700  switch (AF.getValueSize()) {
701  default: llvm_unreachable("Invalid size!");
702  case 1: OW->write8 (uint8_t (AF.getValue())); break;
703  case 2: OW->write16(uint16_t(AF.getValue())); break;
704  case 4: OW->write32(uint32_t(AF.getValue())); break;
705  case 8: OW->write64(uint64_t(AF.getValue())); break;
706  }
707  }
708  break;
709  }
710 
711  case MCFragment::FT_Data:
712  ++stats::EmittedDataFragments;
713  OW->writeBytes(cast<MCDataFragment>(F).getContents());
714  break;
715 
717  ++stats::EmittedRelaxableFragments;
718  OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
719  break;
720 
722  ++stats::EmittedCompactEncodedInstFragments;
723  OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
724  break;
725 
726  case MCFragment::FT_Fill: {
727  ++stats::EmittedFillFragments;
728  const MCFillFragment &FF = cast<MCFillFragment>(F);
729 
730  assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
731 
732  for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
733  switch (FF.getValueSize()) {
734  default: llvm_unreachable("Invalid size!");
735  case 1: OW->write8 (uint8_t (FF.getValue())); break;
736  case 2: OW->write16(uint16_t(FF.getValue())); break;
737  case 4: OW->write32(uint32_t(FF.getValue())); break;
738  case 8: OW->write64(uint64_t(FF.getValue())); break;
739  }
740  }
741  break;
742  }
743 
744  case MCFragment::FT_LEB: {
745  const MCLEBFragment &LF = cast<MCLEBFragment>(F);
746  OW->writeBytes(LF.getContents());
747  break;
748  }
749 
750  case MCFragment::FT_SafeSEH: {
751  const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
752  OW->write32(SF.getSymbol()->getIndex());
753  break;
754  }
755 
756  case MCFragment::FT_Org: {
757  ++stats::EmittedOrgFragments;
758  const MCOrgFragment &OF = cast<MCOrgFragment>(F);
759 
760  for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
761  OW->write8(uint8_t(OF.getValue()));
762 
763  break;
764  }
765 
766  case MCFragment::FT_Dwarf: {
767  const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
768  OW->writeBytes(OF.getContents());
769  break;
770  }
772  const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
773  OW->writeBytes(CF.getContents());
774  break;
775  }
776  }
777 
778  assert(OW->getStream().tell() - Start == FragmentSize &&
779  "The stream should advance by fragment size");
780 }
781 
783  const MCAsmLayout &Layout) const {
784  // Ignore virtual sections.
785  if (Sec->isVirtualSection()) {
786  assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
787 
788  // Check that contents are only things legal inside a virtual section.
789  for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
790  ++it) {
791  switch (it->getKind()) {
792  default: llvm_unreachable("Invalid fragment in virtual section!");
793  case MCFragment::FT_Data: {
794  // Check that we aren't trying to write a non-zero contents (or fixups)
795  // into a virtual section. This is to support clients which use standard
796  // directives to fill the contents of virtual sections.
797  const MCDataFragment &DF = cast<MCDataFragment>(*it);
798  assert(DF.fixup_begin() == DF.fixup_end() &&
799  "Cannot have fixups in virtual section!");
800  for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
801  if (DF.getContents()[i]) {
802  if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
803  report_fatal_error("non-zero initializer found in section '" +
804  ELFSec->getSectionName() + "'");
805  else
806  report_fatal_error("non-zero initializer found in virtual section");
807  }
808  break;
809  }
811  // Check that we aren't trying to write a non-zero value into a virtual
812  // section.
813  assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
814  cast<MCAlignFragment>(it)->getValue() == 0) &&
815  "Invalid align in virtual section!");
816  break;
817  case MCFragment::FT_Fill:
818  assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
819  cast<MCFillFragment>(it)->getValue() == 0) &&
820  "Invalid fill in virtual section!");
821  break;
822  }
823  }
824 
825  return;
826  }
827 
828  uint64_t Start = getWriter().getStream().tell();
829  (void)Start;
830 
831  for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
832  ++it)
833  writeFragment(*this, Layout, *it);
834 
835  assert(getWriter().getStream().tell() - Start ==
836  Layout.getSectionAddressSize(Sec));
837 }
838 
839 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
840  MCFragment &F,
841  const MCFixup &Fixup) {
842  // Evaluate the fixup.
843  MCValue Target;
844  uint64_t FixedValue;
845  bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
847  if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
848  // The fixup was unresolved, we need a relocation. Inform the object
849  // writer of the relocation, and give it an opportunity to adjust the
850  // fixup value if need be.
851  getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
852  FixedValue);
853  }
854  return std::make_pair(FixedValue, IsPCRel);
855 }
856 
858  DEBUG_WITH_TYPE("mc-dump", {
859  llvm::errs() << "assembler backend - pre-layout\n--\n";
860  dump(); });
861 
862  // Create the layout object.
863  MCAsmLayout Layout(*this);
864 
865  // Create dummy fragments and assign section ordinals.
866  unsigned SectionIndex = 0;
867  for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
868  // Create dummy fragments to eliminate any empty sections, this simplifies
869  // layout.
870  if (it->getFragmentList().empty())
871  new MCDataFragment(&*it);
872 
873  it->setOrdinal(SectionIndex++);
874  }
875 
876  // Assign layout order indices to sections and fragments.
877  for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
878  MCSection *Sec = Layout.getSectionOrder()[i];
879  Sec->setLayoutOrder(i);
880 
881  unsigned FragmentIndex = 0;
882  for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
883  iFrag != iFragEnd; ++iFrag)
884  iFrag->setLayoutOrder(FragmentIndex++);
885  }
886 
887  // Layout until everything fits.
888  while (layoutOnce(Layout))
889  continue;
890 
891  DEBUG_WITH_TYPE("mc-dump", {
892  llvm::errs() << "assembler backend - post-relaxation\n--\n";
893  dump(); });
894 
895  // Finalize the layout, including fragment lowering.
896  finishLayout(Layout);
897 
898  DEBUG_WITH_TYPE("mc-dump", {
899  llvm::errs() << "assembler backend - final-layout\n--\n";
900  dump(); });
901 
902  uint64_t StartOffset = OS.tell();
903 
904  // Allow the object writer a chance to perform post-layout binding (for
905  // example, to set the index fields in the symbol data).
906  getWriter().executePostLayoutBinding(*this, Layout);
907 
908  // Evaluate and apply the fixups, generating relocation entries as necessary.
909  for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
910  for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
911  ++it2) {
913  // Data and relaxable fragments both have fixups. So only process
914  // those here.
915  // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
916  // being templated makes this tricky.
917  if (!F || isa<MCCompactEncodedInstFragment>(F))
918  continue;
920  MutableArrayRef<char> Contents;
921  if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
922  Fixups = FragWithFixups->getFixups();
923  Contents = FragWithFixups->getContents();
924  } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
925  Fixups = FragWithFixups->getFixups();
926  Contents = FragWithFixups->getContents();
927  } else
928  llvm_unreachable("Unknown fragment with fixups!");
929  for (const MCFixup &Fixup : Fixups) {
930  uint64_t FixedValue;
931  bool IsPCRel;
932  std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
933  getBackend().applyFixup(Fixup, Contents.data(),
934  Contents.size(), FixedValue, IsPCRel);
935  }
936  }
937  }
938 
939  // Write the object file.
940  getWriter().writeObject(*this, Layout);
941 
942  stats::ObjectBytes += OS.tell() - StartOffset;
943 }
944 
945 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
946  const MCRelaxableFragment *DF,
947  const MCAsmLayout &Layout) const {
948  MCValue Target;
949  uint64_t Value;
950  bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
951  return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
952  Layout);
953 }
954 
955 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
956  const MCAsmLayout &Layout) const {
957  // If this inst doesn't ever need relaxation, ignore it. This occurs when we
958  // are intentionally pushing out inst fragments, or because we relaxed a
959  // previous instruction to one that doesn't need relaxation.
960  if (!getBackend().mayNeedRelaxation(F->getInst()))
961  return false;
962 
964  ie = F->fixup_end(); it != ie; ++it)
965  if (fixupNeedsRelaxation(*it, F, Layout))
966  return true;
967 
968  return false;
969 }
970 
971 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
972  MCRelaxableFragment &F) {
973  if (!fragmentNeedsRelaxation(&F, Layout))
974  return false;
975 
976  ++stats::RelaxedInstructions;
977 
978  // FIXME-PERF: We could immediately lower out instructions if we can tell
979  // they are fully resolved, to avoid retesting on later passes.
980 
981  // Relax the fragment.
982 
983  MCInst Relaxed;
984  getBackend().relaxInstruction(F.getInst(), Relaxed);
985 
986  // Encode the new instruction.
987  //
988  // FIXME-PERF: If it matters, we could let the target do this. It can
989  // probably do so more efficiently in many cases.
992  raw_svector_ostream VecOS(Code);
993  getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
994  VecOS.flush();
995 
996  // Update the fragment.
997  F.setInst(Relaxed);
998  F.getContents() = Code;
999  F.getFixups() = Fixups;
1000 
1001  return true;
1002 }
1003 
1004 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1005  uint64_t OldSize = LF.getContents().size();
1006  int64_t Value;
1007  bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1008  if (!Abs)
1009  report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1011  Data.clear();
1012  raw_svector_ostream OSE(Data);
1013  if (LF.isSigned())
1014  encodeSLEB128(Value, OSE);
1015  else
1016  encodeULEB128(Value, OSE);
1017  OSE.flush();
1018  return OldSize != LF.getContents().size();
1019 }
1020 
1021 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1023  MCContext &Context = Layout.getAssembler().getContext();
1024  uint64_t OldSize = DF.getContents().size();
1025  int64_t AddrDelta;
1026  bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1027  assert(Abs && "We created a line delta with an invalid expression");
1028  (void) Abs;
1029  int64_t LineDelta;
1030  LineDelta = DF.getLineDelta();
1031  SmallString<8> &Data = DF.getContents();
1032  Data.clear();
1033  raw_svector_ostream OSE(Data);
1034  MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
1035  OSE.flush();
1036  return OldSize != Data.size();
1037 }
1038 
1039 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1041  MCContext &Context = Layout.getAssembler().getContext();
1042  uint64_t OldSize = DF.getContents().size();
1043  int64_t AddrDelta;
1044  bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1045  assert(Abs && "We created call frame with an invalid expression");
1046  (void) Abs;
1047  SmallString<8> &Data = DF.getContents();
1048  Data.clear();
1049  raw_svector_ostream OSE(Data);
1050  MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1051  OSE.flush();
1052  return OldSize != Data.size();
1053 }
1054 
1055 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1056  // Holds the first fragment which needed relaxing during this layout. It will
1057  // remain NULL if none were relaxed.
1058  // When a fragment is relaxed, all the fragments following it should get
1059  // invalidated because their offset is going to change.
1060  MCFragment *FirstRelaxedFragment = nullptr;
1061 
1062  // Attempt to relax all the fragments in the section.
1063  for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1064  // Check if this is a fragment that needs relaxation.
1065  bool RelaxedFrag = false;
1066  switch(I->getKind()) {
1067  default:
1068  break;
1070  assert(!getRelaxAll() &&
1071  "Did not expect a MCRelaxableFragment in RelaxAll mode");
1072  RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1073  break;
1074  case MCFragment::FT_Dwarf:
1075  RelaxedFrag = relaxDwarfLineAddr(Layout,
1076  *cast<MCDwarfLineAddrFragment>(I));
1077  break;
1079  RelaxedFrag =
1080  relaxDwarfCallFrameFragment(Layout,
1081  *cast<MCDwarfCallFrameFragment>(I));
1082  break;
1083  case MCFragment::FT_LEB:
1084  RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1085  break;
1086  }
1087  if (RelaxedFrag && !FirstRelaxedFragment)
1088  FirstRelaxedFragment = I;
1089  }
1090  if (FirstRelaxedFragment) {
1091  Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1092  return true;
1093  }
1094  return false;
1095 }
1096 
1097 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1098  ++stats::RelaxationSteps;
1099 
1100  bool WasRelaxed = false;
1101  for (iterator it = begin(), ie = end(); it != ie; ++it) {
1102  MCSection &Sec = *it;
1103  while (layoutSectionOnce(Layout, Sec))
1104  WasRelaxed = true;
1105  }
1106 
1107  return WasRelaxed;
1108 }
1109 
1110 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1111  // The layout is done. Mark every fragment as valid.
1112  for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1113  Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1114  }
1115 }
1116 
1117 // Debugging methods
1118 
1119 namespace llvm {
1120 
1122  OS << "<MCFixup" << " Offset:" << AF.getOffset()
1123  << " Value:" << *AF.getValue()
1124  << " Kind:" << AF.getKind() << ">";
1125  return OS;
1126 }
1127 
1128 }
1129 
1130 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1132  raw_ostream &OS = llvm::errs();
1133 
1134  OS << "<";
1135  switch (getKind()) {
1136  case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1137  case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1139  OS << "MCCompactEncodedInstFragment"; break;
1140  case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1141  case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1142  case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1143  case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1144  case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1145  case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1146  case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1147  }
1148 
1149  OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1150  << " Offset:" << Offset
1151  << " HasInstructions:" << hasInstructions()
1152  << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1153 
1154  switch (getKind()) {
1155  case MCFragment::FT_Align: {
1156  const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1157  if (AF->hasEmitNops())
1158  OS << " (emit nops)";
1159  OS << "\n ";
1160  OS << " Alignment:" << AF->getAlignment()
1161  << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1162  << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1163  break;
1164  }
1165  case MCFragment::FT_Data: {
1166  const MCDataFragment *DF = cast<MCDataFragment>(this);
1167  OS << "\n ";
1168  OS << " Contents:[";
1169  const SmallVectorImpl<char> &Contents = DF->getContents();
1170  for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1171  if (i) OS << ",";
1172  OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1173  }
1174  OS << "] (" << Contents.size() << " bytes)";
1175 
1176  if (DF->fixup_begin() != DF->fixup_end()) {
1177  OS << ",\n ";
1178  OS << " Fixups:[";
1180  ie = DF->fixup_end(); it != ie; ++it) {
1181  if (it != DF->fixup_begin()) OS << ",\n ";
1182  OS << *it;
1183  }
1184  OS << "]";
1185  }
1186  break;
1187  }
1189  const MCCompactEncodedInstFragment *CEIF =
1190  cast<MCCompactEncodedInstFragment>(this);
1191  OS << "\n ";
1192  OS << " Contents:[";
1193  const SmallVectorImpl<char> &Contents = CEIF->getContents();
1194  for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1195  if (i) OS << ",";
1196  OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1197  }
1198  OS << "] (" << Contents.size() << " bytes)";
1199  break;
1200  }
1201  case MCFragment::FT_Fill: {
1202  const MCFillFragment *FF = cast<MCFillFragment>(this);
1203  OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1204  << " Size:" << FF->getSize();
1205  break;
1206  }
1207  case MCFragment::FT_Relaxable: {
1208  const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1209  OS << "\n ";
1210  OS << " Inst:";
1211  F->getInst().dump_pretty(OS);
1212  break;
1213  }
1214  case MCFragment::FT_Org: {
1215  const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1216  OS << "\n ";
1217  OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1218  break;
1219  }
1220  case MCFragment::FT_Dwarf: {
1221  const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1222  OS << "\n ";
1223  OS << " AddrDelta:" << OF->getAddrDelta()
1224  << " LineDelta:" << OF->getLineDelta();
1225  break;
1226  }
1228  const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1229  OS << "\n ";
1230  OS << " AddrDelta:" << CF->getAddrDelta();
1231  break;
1232  }
1233  case MCFragment::FT_LEB: {
1234  const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1235  OS << "\n ";
1236  OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1237  break;
1238  }
1239  case MCFragment::FT_SafeSEH: {
1240  const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1241  OS << "\n ";
1242  OS << " Sym:" << F->getSymbol();
1243  break;
1244  }
1245  }
1246  OS << ">";
1247 }
1248 
1250  raw_ostream &OS = llvm::errs();
1251 
1252  OS << "<MCAssembler\n";
1253  OS << " Sections:[\n ";
1254  for (iterator it = begin(), ie = end(); it != ie; ++it) {
1255  if (it != begin()) OS << ",\n ";
1256  it->dump();
1257  }
1258  OS << "],\n";
1259  OS << " Symbols:[";
1260 
1261  for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1262  if (it != symbol_begin()) OS << ",\n ";
1263  OS << "(";
1264  it->dump();
1265  OS << ", Index:" << it->getIndex() << ", ";
1266  OS << ")";
1267  }
1268  OS << "]>\n";
1269 }
1270 #endif
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:428
uint8_t getBundlePadding() const
Get the padding size that must be inserted before this fragment.
Definition: MCAssembler.h:140
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:48
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:225
unsigned getValueSize() const
Definition: MCAssembler.h:319
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
raw_ostream & getStream()
const MCSymbol & getSymbol() const
Definition: MCExpr.h:328
SMLoc getLoc() const
Definition: MCFixup.h:108
STATISTIC(NumFunctions,"Total number of functions")
void write64(uint64_t Value)
This represents an "assembler immediate".
Definition: MCValue.h:44
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
unsigned getAlignment() const
Definition: MCAssembler.h:315
iterator begin()
Definition: MCAssembler.h:764
const MCExpr & getAddrDelta() const
Definition: MCAssembler.h:483
bool isRegistered() const
Definition: MCSymbol.h:212
void setLayoutOrder(unsigned Value)
Definition: MCSection.h:131
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:753
T * data() const
Definition: ArrayRef.h:256
virtual bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout) const
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
bool alignToBundleEnd() const
Should this fragment be placed at the end of an aligned bundle?
Definition: MCAssembler.h:132
void writeFragmentPadding(const MCFragment &F, uint64_t FSize, MCObjectWriter *OW) const
Write the necessary bundle padding to the given object writer.
virtual void executePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L, const Twine &Msg) const
Definition: MCContext.cpp:474
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:735
virtual void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Write the object file.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:488
void registerSymbol(const MCSymbol &Symbol, bool *Created=nullptr)
virtual bool isSectionAtomizableBySymbols(const MCSection &Section) const
True if the section is atomized using the symbols in it.
Definition: MCAsmInfo.cpp:116
This is a compact (memory-size-wise) fragment for holding an encoded instruction (non-relaxable) that...
Definition: MCAssembler.h:245
F(f)
const MCSubtargetInfo & getSubtargetInfo()
Definition: MCAssembler.h:278
bool isSigned() const
Definition: MCAssembler.h:417
MCContext & getContext() const
Definition: MCAssembler.h:731
Defines the object file and target independent interfaces used by the assembler backend to write nati...
void write8(uint8_t Value)
uint64_t getSize() const
Definition: MCAssembler.h:361
const MCExpr & getOffset() const
Definition: MCAssembler.h:385
void dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer=nullptr, StringRef Separator=" ") const
Dump the MCInst as prettily as possible using the additional MC structures, if given.
Definition: MCInst.cpp:51
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
symbol_iterator symbol_begin()
Definition: MCAssembler.h:775
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:62
const MCInst & getInst() const
Definition: MCAssembler.h:275
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:62
static void Encode(MCContext &Context, int64_t LineDelta, uint64_t AddrDelta, raw_ostream &OS)
Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
Definition: MCDwarf.cpp:429
virtual unsigned getMinimumNopSize() const
Returns the minimum size of a nop in bytes on this target.
Definition: MCAsmBackend.h:123
void push_back(NodeTy *val)
Definition: ilist.h:554
Interface implemented by fragments that contain encoded instructions and/or data. ...
Definition: MCAssembler.h:152
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
NodeTy * getNextNode()
Get the next node, or 0 for the list tail.
Definition: ilist_node.h:80
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:29
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
const MCExpr * getVariableValue() const
getVariableValue() - Get the value for variable symbols.
Definition: MCSymbol.h:299
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
EncodeInstruction - Encode the given Inst to bytes on the output stream OS.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:33
NodeTy * getPrevNode()
Get the previous node, or 0 for the list head.
Definition: ilist_node.h:58
unsigned getMaxBytesToEmit() const
Definition: MCAssembler.h:321
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:159
#define false
Definition: ConvertUTF.c:65
int64_t getLineDelta() const
Definition: MCAssembler.h:452
void destroy()
Destroys the current fragment.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:92
Context object for machine code objects.
Definition: MCContext.h:48
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
Definition: MCSymbol.h:255
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:737
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:56
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
MCSection::iterator end()
Definition: MCSection.cpp:105
virtual void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize, uint64_t Value, bool IsPCRel) const =0
Apply the Value for given Fixup into the provided data fragment, at the offset specified by the fixup...
const MCSymbol * getSymbol()
Definition: MCAssembler.h:505
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
const MCSymbol * getAtom(const MCSymbol &S) const
Find the symbol which defines the atom containing the given symbol, or null if there is no such symbo...
void layoutFragment(MCFragment *Fragment)
Perform layout for a single fragment, assuming that the previous fragment has already been laid out c...
iterator end()
Definition: MCAssembler.h:767
SmallVectorImpl< char > & getContents()
Definition: MCAssembler.h:186
uint32_t getOffset() const
Definition: MCFixup.h:91
const MCExpr & getAddrDelta() const
Definition: MCAssembler.h:454
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:150
virtual bool writeNopData(uint64_t Count, MCObjectWriter *OW) const =0
Write an (optimal) nop sequence of Count bytes to the given output.
static void deleteNode(NodeTy *V)
Definition: ilist.h:113
static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S, bool ReportError, uint64_t &Val)
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCAssembler.h:259
void write32(uint32_t Value)
bool hasInstructions() const
Does this fragment have instructions emitted into it? By default this is false, but specific fragment...
Definition: MCAssembler.h:129
MCAsmLayout(MCAssembler &Assembler)
Definition: MCAssembler.cpp:67
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
If this symbol is equivalent to A + Constant, return A.
const MCExpr * getValue() const
Definition: MCFixup.h:94
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:221
virtual void reset()
Lifetime management.
Definition: MCCodeEmitter.h:35
void writeSectionData(const MCSection *Section, const MCAsmLayout &Layout) const
Emit the section contents using the given object writer.
bool hasEmitNops() const
Definition: MCAssembler.h:323
uint64_t computeFragmentSize(const MCAsmLayout &Layout, const MCFragment &F) const
Compute the effective fragment size assuming it is laid out at the given SectionAddress and FragmentO...
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:310
virtual void relaxInstruction(const MCInst &Inst, MCInst &Res) const =0
Relax the instruction in the given fragment to the next wider instruction.
virtual bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB, bool InSet, bool IsPCRel) const
FragmentType getKind() const
Definition: MCAssembler.h:116
void invalidateFragmentsFrom(MCFragment *F)
Invalidate the fragments starting with F because it has been resized.
Definition: MCAssembler.cpp:88
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:23
virtual void reset()
lifetime management
bool evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const
Try to evaluate the expression to the form (a - b + constant) where neither a nor b are variables...
Definition: MCExpr.cpp:603
bool getRelaxAll() const
Definition: MCAssembler.h:748
virtual void processFixupValue(const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, uint64_t &Value, bool &IsResolved)
Target hook to adjust the literal value of a fixup if necessary.
Definition: MCAsmBackend.h:76
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCAssembler.h:211
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
Should this fixup kind force a 4-byte aligned effective PC value?
MCFragment * getFragment() const
Definition: MCSymbol.h:382
llvm::SmallVectorImpl< MCSection * > & getSectionOrder()
Definition: MCAsmLayout.h:66
MCFixupKind getKind() const
Definition: MCFixup.h:89
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:52
MCSection::iterator begin()
Definition: MCSection.cpp:103
void write16(uint16_t Value)
bool isSymbolLinkerVisible(const MCSymbol &SD) const
Check whether a particular symbol is visible to the linker and is required in the symbol table...
PowerPC TLS Dynamic Call Fixup
uint64_t computeBundlePadding(const MCAssembler &Assembler, const MCFragment *F, uint64_t FOffset, uint64_t FSize)
Compute the amount of padding required before the fragment F to obey bundling restrictions, where FOffset is the fragment's offset in its section and FSize is the fragment's size.
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:251
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:51
bool isUsedInReloc() const
Definition: MCSymbol.h:216
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
bool isBundlingEnabled() const
Definition: MCAssembler.h:751
An iterator type that allows iterating over the pointees via some other iterator. ...
Definition: iterator.h:231
static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment &F)
Write the fragment F to the output file.
static void EncodeAdvanceLoc(MCContext &Context, uint64_t AddrDelta, raw_ostream &OS)
Definition: MCDwarf.cpp:1579
MCLOHContainer & getLOHContainer()
Definition: MCAssembler.h:851
MCSection * getParent() const
Definition: MCAssembler.h:118
void encodeSLEB128(int64_t Value, raw_ostream &OS)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:595
Target - Wrapper for Target specific information.
void setIsRegistered(bool Value) const
Definition: MCSymbol.h:213
SmallVectorImpl< MCFixup >::const_iterator const_fixup_iterator
Definition: MCAssembler.h:208
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
Definition: MCSymbol.h:222
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
SmallString< 8 > & getContents()
Definition: MCAssembler.h:485
virtual void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue)=0
Record a relocation entry.
int64_t getValue() const
Definition: MCAssembler.h:317
static char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16)...
Definition: StringExtras.h:26
void setBundlePadding(uint8_t N)
Set the padding size for this fragment.
Definition: MCAssembler.h:144
const MCSymbol * getAtom() const
Definition: MCAssembler.h:121
block placement stats
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
uint64_t getOffset() const
Definition: MCSymbol.h:319
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:733
#define I(x, y, z)
Definition: MD5.cpp:54
bool isCommon() const
Is this a 'common' symbol.
Definition: MCSymbol.h:378
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S, bool ReportError, uint64_t &Val)
SmallString< 8 > & getContents()
Definition: MCAssembler.h:419
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:1738
unsigned getValueSize() const
Definition: MCAssembler.h:359
reference back()
Definition: ilist.h:398
void writeBytes(const SmallVectorImpl< char > &ByteVec, unsigned ZeroFillSize=0)
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:294
void reset()
Reuse an assembler instance.
Fragment for data and encoded instructions.
Definition: MCAssembler.h:228
VariantKind getKind() const
Definition: MCExpr.h:330
int64_t getConstant() const
Definition: MCValue.h:50
const ARM::ArchExtKind Kind
cl::opt< bool > RelaxAll("mc-relax-all", cl::desc("When used with filetype=obj, ""relax all fixups in the emitted object file"))
LLVM Value Representation.
Definition: Value.h:69
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:34
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:51
uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: MathExtras.h:616
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
const MCExpr & getValue() const
Definition: MCAssembler.h:415
void encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned Padding=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:38
uint64_t getSectionFileSize(const MCSection *Sec) const
Get the data size of the given section, as emitted to the object file.
unsigned getLayoutOrder() const
Definition: MCAssembler.h:124
bool isUndefined() const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:258
uint8_t getValue() const
Definition: MCAssembler.h:387
int64_t getValue() const
Definition: MCAssembler.h:357
SmallString< 8 > & getContents()
Definition: MCAssembler.h:456
Represents a location in source code.
Definition: SMLoc.h:23
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
pointee_iterator< SectionListType::iterator > iterator
Definition: MCAssembler.h:539
virtual void reset()
lifetime management
Definition: MCAsmBackend.h:47
void Finish()
Finish - Do final processing and write the object to the output stream.
MCSection::FragmentListType & getFragmentList()
Definition: MCSection.h:150
void setInst(const MCInst &Value)
Definition: MCAssembler.h:276
symbol_iterator symbol_end()
Definition: MCAssembler.h:778