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"
21 #include "llvm/MC/MCFixupKindInfo.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"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.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
MCAsmLayout(MCAssembler & Asm)67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68 : Assembler(Asm), LastValidFragment()
69 {
70 // Compute the section layout order. Virtual sections must go last.
71 for (MCSection &Sec : Asm)
72 if (!Sec.isVirtualSection())
73 SectionOrder.push_back(&Sec);
74 for (MCSection &Sec : Asm)
75 if (Sec.isVirtualSection())
76 SectionOrder.push_back(&Sec);
77 }
78
isFragmentValid(const MCFragment * F) const79 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
invalidateFragmentsFrom(MCFragment * F)88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
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
ensureValid(const MCFragment * F) const98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99 MCSection *Sec = F->getParent();
100 MCSection::iterator I;
101 if (MCFragment *Cur = LastValidFragment[Sec])
102 I = ++MCSection::iterator(Cur);
103 else
104 I = Sec->begin();
105
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(I != Sec->end() && "Layout bookkeeping error");
109 const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
110 ++I;
111 }
112 }
113
getFragmentOffset(const MCFragment * F) const114 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.
getLabelOffset(const MCAsmLayout & Layout,const MCSymbol & S,bool ReportError,uint64_t & Val)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
getSymbolOffsetImpl(const MCAsmLayout & Layout,const MCSymbol & S,bool ReportError,uint64_t & Val)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()->evaluateAsValue(Target, Layout))
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
getSymbolOffset(const MCSymbol & S,uint64_t & Val) const166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167 return getSymbolOffsetImpl(*this, S, false, Val);
168 }
169
getSymbolOffset(const MCSymbol & S) const170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
171 uint64_t Val;
172 getSymbolOffsetImpl(*this, S, true, Val);
173 return Val;
174 }
175
getBaseSymbol(const MCSymbol & Symbol) const176 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
177 if (!Symbol.isVariable())
178 return &Symbol;
179
180 const MCExpr *Expr = Symbol.getVariableValue();
181 MCValue Value;
182 if (!Expr->evaluateAsValue(Value, *this)) {
183 Assembler.getContext().reportError(
184 SMLoc(), "expression could not be evaluated");
185 return nullptr;
186 }
187
188 const MCSymbolRefExpr *RefB = Value.getSymB();
189 if (RefB) {
190 Assembler.getContext().reportError(
191 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
192 "' could not be evaluated in a subtraction expression");
193 return nullptr;
194 }
195
196 const MCSymbolRefExpr *A = Value.getSymA();
197 if (!A)
198 return nullptr;
199
200 const MCSymbol &ASym = A->getSymbol();
201 const MCAssembler &Asm = getAssembler();
202 if (ASym.isCommon()) {
203 // FIXME: we should probably add a SMLoc to MCExpr.
204 Asm.getContext().reportError(SMLoc(),
205 "Common symbol '" + ASym.getName() +
206 "' cannot be used in assignment expr");
207 return nullptr;
208 }
209
210 return &ASym;
211 }
212
getSectionAddressSize(const MCSection * Sec) const213 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
214 // The size is the last fragment's end offset.
215 const MCFragment &F = Sec->getFragmentList().back();
216 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
217 }
218
getSectionFileSize(const MCSection * Sec) const219 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
220 // Virtual sections have no file size.
221 if (Sec->isVirtualSection())
222 return 0;
223
224 // Otherwise, the file size is the same as the address space size.
225 return getSectionAddressSize(Sec);
226 }
227
computeBundlePadding(const MCAssembler & Assembler,const MCFragment * F,uint64_t FOffset,uint64_t FSize)228 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
229 const MCFragment *F,
230 uint64_t FOffset, uint64_t FSize) {
231 uint64_t BundleSize = Assembler.getBundleAlignSize();
232 assert(BundleSize > 0 &&
233 "computeBundlePadding should only be called if bundling is enabled");
234 uint64_t BundleMask = BundleSize - 1;
235 uint64_t OffsetInBundle = FOffset & BundleMask;
236 uint64_t EndOfFragment = OffsetInBundle + FSize;
237
238 // There are two kinds of bundling restrictions:
239 //
240 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
241 // *end* on a bundle boundary.
242 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
243 // would, add padding until the end of the bundle so that the fragment
244 // will start in a new one.
245 if (F->alignToBundleEnd()) {
246 // Three possibilities here:
247 //
248 // A) The fragment just happens to end at a bundle boundary, so we're good.
249 // B) The fragment ends before the current bundle boundary: pad it just
250 // enough to reach the boundary.
251 // C) The fragment ends after the current bundle boundary: pad it until it
252 // reaches the end of the next bundle boundary.
253 //
254 // Note: this code could be made shorter with some modulo trickery, but it's
255 // intentionally kept in its more explicit form for simplicity.
256 if (EndOfFragment == BundleSize)
257 return 0;
258 else if (EndOfFragment < BundleSize)
259 return BundleSize - EndOfFragment;
260 else { // EndOfFragment > BundleSize
261 return 2 * BundleSize - EndOfFragment;
262 }
263 } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
264 return BundleSize - OffsetInBundle;
265 else
266 return 0;
267 }
268
269 /* *** */
270
deleteNode(MCFragment * V)271 void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
272 V->destroy();
273 }
274
MCFragment()275 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
276 AlignToBundleEnd(false), BundlePadding(0) {
277 }
278
~MCFragment()279 MCFragment::~MCFragment() { }
280
MCFragment(FragmentType Kind,bool HasInstructions,uint8_t BundlePadding,MCSection * Parent)281 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
282 uint8_t BundlePadding, MCSection *Parent)
283 : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
284 BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
285 Offset(~UINT64_C(0)) {
286 if (Parent && !isDummy())
287 Parent->getFragmentList().push_back(this);
288 }
289
destroy()290 void MCFragment::destroy() {
291 // First check if we are the sentinal.
292 if (Kind == FragmentType(~0)) {
293 delete this;
294 return;
295 }
296
297 switch (Kind) {
298 case FT_Align:
299 delete cast<MCAlignFragment>(this);
300 return;
301 case FT_Data:
302 delete cast<MCDataFragment>(this);
303 return;
304 case FT_CompactEncodedInst:
305 delete cast<MCCompactEncodedInstFragment>(this);
306 return;
307 case FT_Fill:
308 delete cast<MCFillFragment>(this);
309 return;
310 case FT_Relaxable:
311 delete cast<MCRelaxableFragment>(this);
312 return;
313 case FT_Org:
314 delete cast<MCOrgFragment>(this);
315 return;
316 case FT_Dwarf:
317 delete cast<MCDwarfLineAddrFragment>(this);
318 return;
319 case FT_DwarfFrame:
320 delete cast<MCDwarfCallFrameFragment>(this);
321 return;
322 case FT_LEB:
323 delete cast<MCLEBFragment>(this);
324 return;
325 case FT_SafeSEH:
326 delete cast<MCSafeSEHFragment>(this);
327 return;
328 case FT_Dummy:
329 delete cast<MCDummyFragment>(this);
330 return;
331 }
332 }
333
334 /* *** */
335
MCAssembler(MCContext & Context_,MCAsmBackend & Backend_,MCCodeEmitter & Emitter_,MCObjectWriter & Writer_)336 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
337 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
338 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
339 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
340 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
341 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
342 }
343
~MCAssembler()344 MCAssembler::~MCAssembler() {
345 }
346
reset()347 void MCAssembler::reset() {
348 Sections.clear();
349 Symbols.clear();
350 IndirectSymbols.clear();
351 DataRegions.clear();
352 LinkerOptions.clear();
353 FileNames.clear();
354 ThumbFuncs.clear();
355 BundleAlignSize = 0;
356 RelaxAll = false;
357 SubsectionsViaSymbols = false;
358 IncrementalLinkerCompatible = false;
359 ELFHeaderEFlags = 0;
360 LOHContainer.reset();
361 VersionMinInfo.Major = 0;
362
363 // reset objects owned by us
364 getBackend().reset();
365 getEmitter().reset();
366 getWriter().reset();
367 getLOHContainer().reset();
368 }
369
registerSection(MCSection & Section)370 bool MCAssembler::registerSection(MCSection &Section) {
371 if (Section.isRegistered())
372 return false;
373 Sections.push_back(&Section);
374 Section.setIsRegistered(true);
375 return true;
376 }
377
isThumbFunc(const MCSymbol * Symbol) const378 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
379 if (ThumbFuncs.count(Symbol))
380 return true;
381
382 if (!Symbol->isVariable())
383 return false;
384
385 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
386 // is not clear if that is a bug or a feature.
387 const MCExpr *Expr = Symbol->getVariableValue();
388 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
389 if (!Ref)
390 return false;
391
392 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
393 return false;
394
395 const MCSymbol &Sym = Ref->getSymbol();
396 if (!isThumbFunc(&Sym))
397 return false;
398
399 ThumbFuncs.insert(Symbol); // Cache it.
400 return true;
401 }
402
isSymbolLinkerVisible(const MCSymbol & Symbol) const403 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
404 // Non-temporary labels should always be visible to the linker.
405 if (!Symbol.isTemporary())
406 return true;
407
408 // Absolute temporary labels are never visible.
409 if (!Symbol.isInSection())
410 return false;
411
412 if (Symbol.isUsedInReloc())
413 return true;
414
415 return false;
416 }
417
getAtom(const MCSymbol & S) const418 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
419 // Linker visible symbols define atoms.
420 if (isSymbolLinkerVisible(S))
421 return &S;
422
423 // Absolute and undefined symbols have no defining atom.
424 if (!S.isInSection())
425 return nullptr;
426
427 // Non-linker visible symbols in sections which can't be atomized have no
428 // defining atom.
429 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
430 *S.getFragment()->getParent()))
431 return nullptr;
432
433 // Otherwise, return the atom for the containing fragment.
434 return S.getFragment()->getAtom();
435 }
436
evaluateFixup(const MCAsmLayout & Layout,const MCFixup & Fixup,const MCFragment * DF,MCValue & Target,uint64_t & Value) const437 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
438 const MCFixup &Fixup, const MCFragment *DF,
439 MCValue &Target, uint64_t &Value) const {
440 ++stats::evaluateFixup;
441
442 // FIXME: This code has some duplication with recordRelocation. We should
443 // probably merge the two into a single callback that tries to evaluate a
444 // fixup and records a relocation if one is needed.
445 const MCExpr *Expr = Fixup.getValue();
446 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
447 getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
448 // Claim to have completely evaluated the fixup, to prevent any further
449 // processing from being done.
450 Value = 0;
451 return true;
452 }
453
454 bool IsPCRel = Backend.getFixupKindInfo(
455 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
456
457 bool IsResolved;
458 if (IsPCRel) {
459 if (Target.getSymB()) {
460 IsResolved = false;
461 } else if (!Target.getSymA()) {
462 IsResolved = false;
463 } else {
464 const MCSymbolRefExpr *A = Target.getSymA();
465 const MCSymbol &SA = A->getSymbol();
466 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
467 IsResolved = false;
468 } else {
469 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
470 *this, SA, *DF, false, true);
471 }
472 }
473 } else {
474 IsResolved = Target.isAbsolute();
475 }
476
477 Value = Target.getConstant();
478
479 if (const MCSymbolRefExpr *A = Target.getSymA()) {
480 const MCSymbol &Sym = A->getSymbol();
481 if (Sym.isDefined())
482 Value += Layout.getSymbolOffset(Sym);
483 }
484 if (const MCSymbolRefExpr *B = Target.getSymB()) {
485 const MCSymbol &Sym = B->getSymbol();
486 if (Sym.isDefined())
487 Value -= Layout.getSymbolOffset(Sym);
488 }
489
490
491 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
492 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
493 assert((ShouldAlignPC ? IsPCRel : true) &&
494 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
495
496 if (IsPCRel) {
497 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
498
499 // A number of ARM fixups in Thumb mode require that the effective PC
500 // address be determined as the 32-bit aligned version of the actual offset.
501 if (ShouldAlignPC) Offset &= ~0x3;
502 Value -= Offset;
503 }
504
505 // Let the backend adjust the fixup value if necessary, including whether
506 // we need a relocation.
507 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
508 IsResolved);
509
510 return IsResolved;
511 }
512
computeFragmentSize(const MCAsmLayout & Layout,const MCFragment & F) const513 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
514 const MCFragment &F) const {
515 switch (F.getKind()) {
516 case MCFragment::FT_Data:
517 return cast<MCDataFragment>(F).getContents().size();
518 case MCFragment::FT_Relaxable:
519 return cast<MCRelaxableFragment>(F).getContents().size();
520 case MCFragment::FT_CompactEncodedInst:
521 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
522 case MCFragment::FT_Fill:
523 return cast<MCFillFragment>(F).getSize();
524
525 case MCFragment::FT_LEB:
526 return cast<MCLEBFragment>(F).getContents().size();
527
528 case MCFragment::FT_SafeSEH:
529 return 4;
530
531 case MCFragment::FT_Align: {
532 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
533 unsigned Offset = Layout.getFragmentOffset(&AF);
534 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
535 // If we are padding with nops, force the padding to be larger than the
536 // minimum nop size.
537 if (Size > 0 && AF.hasEmitNops()) {
538 while (Size % getBackend().getMinimumNopSize())
539 Size += AF.getAlignment();
540 }
541 if (Size > AF.getMaxBytesToEmit())
542 return 0;
543 return Size;
544 }
545
546 case MCFragment::FT_Org: {
547 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
548 MCValue Value;
549 if (!OF.getOffset().evaluateAsValue(Value, Layout))
550 report_fatal_error("expected assembly-time absolute expression");
551
552 // FIXME: We need a way to communicate this error.
553 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
554 int64_t TargetLocation = Value.getConstant();
555 if (const MCSymbolRefExpr *A = Value.getSymA()) {
556 uint64_t Val;
557 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
558 report_fatal_error("expected absolute expression");
559 TargetLocation += Val;
560 }
561 int64_t Size = TargetLocation - FragmentOffset;
562 if (Size < 0 || Size >= 0x40000000)
563 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
564 "' (at offset '" + Twine(FragmentOffset) + "')");
565 return Size;
566 }
567
568 case MCFragment::FT_Dwarf:
569 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
570 case MCFragment::FT_DwarfFrame:
571 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
572 case MCFragment::FT_Dummy:
573 llvm_unreachable("Should not have been added");
574 }
575
576 llvm_unreachable("invalid fragment kind");
577 }
578
layoutFragment(MCFragment * F)579 void MCAsmLayout::layoutFragment(MCFragment *F) {
580 MCFragment *Prev = F->getPrevNode();
581
582 // We should never try to recompute something which is valid.
583 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
584 // We should never try to compute the fragment layout if its predecessor
585 // isn't valid.
586 assert((!Prev || isFragmentValid(Prev)) &&
587 "Attempt to compute fragment before its predecessor!");
588
589 ++stats::FragmentLayouts;
590
591 // Compute fragment offset and size.
592 if (Prev)
593 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
594 else
595 F->Offset = 0;
596 LastValidFragment[F->getParent()] = F;
597
598 // If bundling is enabled and this fragment has instructions in it, it has to
599 // obey the bundling restrictions. With padding, we'll have:
600 //
601 //
602 // BundlePadding
603 // |||
604 // -------------------------------------
605 // Prev |##########| F |
606 // -------------------------------------
607 // ^
608 // |
609 // F->Offset
610 //
611 // The fragment's offset will point to after the padding, and its computed
612 // size won't include the padding.
613 //
614 // When the -mc-relax-all flag is used, we optimize bundling by writting the
615 // padding directly into fragments when the instructions are emitted inside
616 // the streamer. When the fragment is larger than the bundle size, we need to
617 // ensure that it's bundle aligned. This means that if we end up with
618 // multiple fragments, we must emit bundle padding between fragments.
619 //
620 // ".align N" is an example of a directive that introduces multiple
621 // fragments. We could add a special case to handle ".align N" by emitting
622 // within-fragment padding (which would produce less padding when N is less
623 // than the bundle size), but for now we don't.
624 //
625 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
626 assert(isa<MCEncodedFragment>(F) &&
627 "Only MCEncodedFragment implementations have instructions");
628 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
629
630 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
631 report_fatal_error("Fragment can't be larger than a bundle size");
632
633 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
634 F->Offset, FSize);
635 if (RequiredBundlePadding > UINT8_MAX)
636 report_fatal_error("Padding cannot exceed 255 bytes");
637 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
638 F->Offset += RequiredBundlePadding;
639 }
640 }
641
registerSymbol(const MCSymbol & Symbol,bool * Created)642 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
643 bool New = !Symbol.isRegistered();
644 if (Created)
645 *Created = New;
646 if (New) {
647 Symbol.setIsRegistered(true);
648 Symbols.push_back(&Symbol);
649 }
650 }
651
writeFragmentPadding(const MCFragment & F,uint64_t FSize,MCObjectWriter * OW) const652 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
653 MCObjectWriter *OW) const {
654 // Should NOP padding be written out before this fragment?
655 unsigned BundlePadding = F.getBundlePadding();
656 if (BundlePadding > 0) {
657 assert(isBundlingEnabled() &&
658 "Writing bundle padding with disabled bundling");
659 assert(F.hasInstructions() &&
660 "Writing bundle padding for a fragment without instructions");
661
662 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
663 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
664 // If the padding itself crosses a bundle boundary, it must be emitted
665 // in 2 pieces, since even nop instructions must not cross boundaries.
666 // v--------------v <- BundleAlignSize
667 // v---------v <- BundlePadding
668 // ----------------------------
669 // | Prev |####|####| F |
670 // ----------------------------
671 // ^-------------------^ <- TotalLength
672 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
673 if (!getBackend().writeNopData(DistanceToBoundary, OW))
674 report_fatal_error("unable to write NOP sequence of " +
675 Twine(DistanceToBoundary) + " bytes");
676 BundlePadding -= DistanceToBoundary;
677 }
678 if (!getBackend().writeNopData(BundlePadding, OW))
679 report_fatal_error("unable to write NOP sequence of " +
680 Twine(BundlePadding) + " bytes");
681 }
682 }
683
684 /// \brief Write the fragment \p F to the output file.
writeFragment(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment & F)685 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
686 const MCFragment &F) {
687 MCObjectWriter *OW = &Asm.getWriter();
688
689 // FIXME: Embed in fragments instead?
690 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
691
692 Asm.writeFragmentPadding(F, FragmentSize, OW);
693
694 // This variable (and its dummy usage) is to participate in the assert at
695 // the end of the function.
696 uint64_t Start = OW->getStream().tell();
697 (void) Start;
698
699 ++stats::EmittedFragments;
700
701 switch (F.getKind()) {
702 case MCFragment::FT_Align: {
703 ++stats::EmittedAlignFragments;
704 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
705 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
706
707 uint64_t Count = FragmentSize / AF.getValueSize();
708
709 // FIXME: This error shouldn't actually occur (the front end should emit
710 // multiple .align directives to enforce the semantics it wants), but is
711 // severe enough that we want to report it. How to handle this?
712 if (Count * AF.getValueSize() != FragmentSize)
713 report_fatal_error("undefined .align directive, value size '" +
714 Twine(AF.getValueSize()) +
715 "' is not a divisor of padding size '" +
716 Twine(FragmentSize) + "'");
717
718 // See if we are aligning with nops, and if so do that first to try to fill
719 // the Count bytes. Then if that did not fill any bytes or there are any
720 // bytes left to fill use the Value and ValueSize to fill the rest.
721 // If we are aligning with nops, ask that target to emit the right data.
722 if (AF.hasEmitNops()) {
723 if (!Asm.getBackend().writeNopData(Count, OW))
724 report_fatal_error("unable to write nop sequence of " +
725 Twine(Count) + " bytes");
726 break;
727 }
728
729 // Otherwise, write out in multiples of the value size.
730 for (uint64_t i = 0; i != Count; ++i) {
731 switch (AF.getValueSize()) {
732 default: llvm_unreachable("Invalid size!");
733 case 1: OW->write8 (uint8_t (AF.getValue())); break;
734 case 2: OW->write16(uint16_t(AF.getValue())); break;
735 case 4: OW->write32(uint32_t(AF.getValue())); break;
736 case 8: OW->write64(uint64_t(AF.getValue())); break;
737 }
738 }
739 break;
740 }
741
742 case MCFragment::FT_Data:
743 ++stats::EmittedDataFragments;
744 OW->writeBytes(cast<MCDataFragment>(F).getContents());
745 break;
746
747 case MCFragment::FT_Relaxable:
748 ++stats::EmittedRelaxableFragments;
749 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
750 break;
751
752 case MCFragment::FT_CompactEncodedInst:
753 ++stats::EmittedCompactEncodedInstFragments;
754 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
755 break;
756
757 case MCFragment::FT_Fill: {
758 ++stats::EmittedFillFragments;
759 const MCFillFragment &FF = cast<MCFillFragment>(F);
760
761 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
762
763 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
764 switch (FF.getValueSize()) {
765 default: llvm_unreachable("Invalid size!");
766 case 1: OW->write8 (uint8_t (FF.getValue())); break;
767 case 2: OW->write16(uint16_t(FF.getValue())); break;
768 case 4: OW->write32(uint32_t(FF.getValue())); break;
769 case 8: OW->write64(uint64_t(FF.getValue())); break;
770 }
771 }
772 break;
773 }
774
775 case MCFragment::FT_LEB: {
776 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
777 OW->writeBytes(LF.getContents());
778 break;
779 }
780
781 case MCFragment::FT_SafeSEH: {
782 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
783 OW->write32(SF.getSymbol()->getIndex());
784 break;
785 }
786
787 case MCFragment::FT_Org: {
788 ++stats::EmittedOrgFragments;
789 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
790
791 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
792 OW->write8(uint8_t(OF.getValue()));
793
794 break;
795 }
796
797 case MCFragment::FT_Dwarf: {
798 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
799 OW->writeBytes(OF.getContents());
800 break;
801 }
802 case MCFragment::FT_DwarfFrame: {
803 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
804 OW->writeBytes(CF.getContents());
805 break;
806 }
807 case MCFragment::FT_Dummy:
808 llvm_unreachable("Should not have been added");
809 }
810
811 assert(OW->getStream().tell() - Start == FragmentSize &&
812 "The stream should advance by fragment size");
813 }
814
writeSectionData(const MCSection * Sec,const MCAsmLayout & Layout) const815 void MCAssembler::writeSectionData(const MCSection *Sec,
816 const MCAsmLayout &Layout) const {
817 // Ignore virtual sections.
818 if (Sec->isVirtualSection()) {
819 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
820
821 // Check that contents are only things legal inside a virtual section.
822 for (const MCFragment &F : *Sec) {
823 switch (F.getKind()) {
824 default: llvm_unreachable("Invalid fragment in virtual section!");
825 case MCFragment::FT_Data: {
826 // Check that we aren't trying to write a non-zero contents (or fixups)
827 // into a virtual section. This is to support clients which use standard
828 // directives to fill the contents of virtual sections.
829 const MCDataFragment &DF = cast<MCDataFragment>(F);
830 assert(DF.fixup_begin() == DF.fixup_end() &&
831 "Cannot have fixups in virtual section!");
832 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
833 if (DF.getContents()[i]) {
834 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
835 report_fatal_error("non-zero initializer found in section '" +
836 ELFSec->getSectionName() + "'");
837 else
838 report_fatal_error("non-zero initializer found in virtual section");
839 }
840 break;
841 }
842 case MCFragment::FT_Align:
843 // Check that we aren't trying to write a non-zero value into a virtual
844 // section.
845 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
846 cast<MCAlignFragment>(F).getValue() == 0) &&
847 "Invalid align in virtual section!");
848 break;
849 case MCFragment::FT_Fill:
850 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
851 cast<MCFillFragment>(F).getValue() == 0) &&
852 "Invalid fill in virtual section!");
853 break;
854 }
855 }
856
857 return;
858 }
859
860 uint64_t Start = getWriter().getStream().tell();
861 (void)Start;
862
863 for (const MCFragment &F : *Sec)
864 writeFragment(*this, Layout, F);
865
866 assert(getWriter().getStream().tell() - Start ==
867 Layout.getSectionAddressSize(Sec));
868 }
869
handleFixup(const MCAsmLayout & Layout,MCFragment & F,const MCFixup & Fixup)870 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
871 MCFragment &F,
872 const MCFixup &Fixup) {
873 // Evaluate the fixup.
874 MCValue Target;
875 uint64_t FixedValue;
876 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
877 MCFixupKindInfo::FKF_IsPCRel;
878 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
879 // The fixup was unresolved, we need a relocation. Inform the object
880 // writer of the relocation, and give it an opportunity to adjust the
881 // fixup value if need be.
882 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
883 FixedValue);
884 }
885 return std::make_pair(FixedValue, IsPCRel);
886 }
887
layout(MCAsmLayout & Layout)888 void MCAssembler::layout(MCAsmLayout &Layout) {
889 DEBUG_WITH_TYPE("mc-dump", {
890 llvm::errs() << "assembler backend - pre-layout\n--\n";
891 dump(); });
892
893 // Create dummy fragments and assign section ordinals.
894 unsigned SectionIndex = 0;
895 for (MCSection &Sec : *this) {
896 // Create dummy fragments to eliminate any empty sections, this simplifies
897 // layout.
898 if (Sec.getFragmentList().empty())
899 new MCDataFragment(&Sec);
900
901 Sec.setOrdinal(SectionIndex++);
902 }
903
904 // Assign layout order indices to sections and fragments.
905 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
906 MCSection *Sec = Layout.getSectionOrder()[i];
907 Sec->setLayoutOrder(i);
908
909 unsigned FragmentIndex = 0;
910 for (MCFragment &Frag : *Sec)
911 Frag.setLayoutOrder(FragmentIndex++);
912 }
913
914 // Layout until everything fits.
915 while (layoutOnce(Layout))
916 continue;
917
918 DEBUG_WITH_TYPE("mc-dump", {
919 llvm::errs() << "assembler backend - post-relaxation\n--\n";
920 dump(); });
921
922 // Finalize the layout, including fragment lowering.
923 finishLayout(Layout);
924
925 DEBUG_WITH_TYPE("mc-dump", {
926 llvm::errs() << "assembler backend - final-layout\n--\n";
927 dump(); });
928
929 // Allow the object writer a chance to perform post-layout binding (for
930 // example, to set the index fields in the symbol data).
931 getWriter().executePostLayoutBinding(*this, Layout);
932
933 // Evaluate and apply the fixups, generating relocation entries as necessary.
934 for (MCSection &Sec : *this) {
935 for (MCFragment &Frag : Sec) {
936 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
937 // Data and relaxable fragments both have fixups. So only process
938 // those here.
939 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
940 // being templated makes this tricky.
941 if (!F || isa<MCCompactEncodedInstFragment>(F))
942 continue;
943 ArrayRef<MCFixup> Fixups;
944 MutableArrayRef<char> Contents;
945 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
946 Fixups = FragWithFixups->getFixups();
947 Contents = FragWithFixups->getContents();
948 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
949 Fixups = FragWithFixups->getFixups();
950 Contents = FragWithFixups->getContents();
951 } else
952 llvm_unreachable("Unknown fragment with fixups!");
953 for (const MCFixup &Fixup : Fixups) {
954 uint64_t FixedValue;
955 bool IsPCRel;
956 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
957 getBackend().applyFixup(Fixup, Contents.data(),
958 Contents.size(), FixedValue, IsPCRel);
959 }
960 }
961 }
962 }
963
Finish()964 void MCAssembler::Finish() {
965 // Create the layout object.
966 MCAsmLayout Layout(*this);
967 layout(Layout);
968
969 raw_ostream &OS = getWriter().getStream();
970 uint64_t StartOffset = OS.tell();
971
972 // Write the object file.
973 getWriter().writeObject(*this, Layout);
974
975 stats::ObjectBytes += OS.tell() - StartOffset;
976 }
977
fixupNeedsRelaxation(const MCFixup & Fixup,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const978 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
979 const MCRelaxableFragment *DF,
980 const MCAsmLayout &Layout) const {
981 MCValue Target;
982 uint64_t Value;
983 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
984 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
985 Layout);
986 }
987
fragmentNeedsRelaxation(const MCRelaxableFragment * F,const MCAsmLayout & Layout) const988 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
989 const MCAsmLayout &Layout) const {
990 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
991 // are intentionally pushing out inst fragments, or because we relaxed a
992 // previous instruction to one that doesn't need relaxation.
993 if (!getBackend().mayNeedRelaxation(F->getInst()))
994 return false;
995
996 for (const MCFixup &Fixup : F->getFixups())
997 if (fixupNeedsRelaxation(Fixup, F, Layout))
998 return true;
999
1000 return false;
1001 }
1002
relaxInstruction(MCAsmLayout & Layout,MCRelaxableFragment & F)1003 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
1004 MCRelaxableFragment &F) {
1005 if (!fragmentNeedsRelaxation(&F, Layout))
1006 return false;
1007
1008 ++stats::RelaxedInstructions;
1009
1010 // FIXME-PERF: We could immediately lower out instructions if we can tell
1011 // they are fully resolved, to avoid retesting on later passes.
1012
1013 // Relax the fragment.
1014
1015 MCInst Relaxed;
1016 getBackend().relaxInstruction(F.getInst(), Relaxed);
1017
1018 // Encode the new instruction.
1019 //
1020 // FIXME-PERF: If it matters, we could let the target do this. It can
1021 // probably do so more efficiently in many cases.
1022 SmallVector<MCFixup, 4> Fixups;
1023 SmallString<256> Code;
1024 raw_svector_ostream VecOS(Code);
1025 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1026
1027 // Update the fragment.
1028 F.setInst(Relaxed);
1029 F.getContents() = Code;
1030 F.getFixups() = Fixups;
1031
1032 return true;
1033 }
1034
relaxLEB(MCAsmLayout & Layout,MCLEBFragment & LF)1035 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1036 uint64_t OldSize = LF.getContents().size();
1037 int64_t Value;
1038 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1039 if (!Abs)
1040 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1041 SmallString<8> &Data = LF.getContents();
1042 Data.clear();
1043 raw_svector_ostream OSE(Data);
1044 if (LF.isSigned())
1045 encodeSLEB128(Value, OSE);
1046 else
1047 encodeULEB128(Value, OSE);
1048 return OldSize != LF.getContents().size();
1049 }
1050
relaxDwarfLineAddr(MCAsmLayout & Layout,MCDwarfLineAddrFragment & DF)1051 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1052 MCDwarfLineAddrFragment &DF) {
1053 MCContext &Context = Layout.getAssembler().getContext();
1054 uint64_t OldSize = DF.getContents().size();
1055 int64_t AddrDelta;
1056 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1057 assert(Abs && "We created a line delta with an invalid expression");
1058 (void) Abs;
1059 int64_t LineDelta;
1060 LineDelta = DF.getLineDelta();
1061 SmallString<8> &Data = DF.getContents();
1062 Data.clear();
1063 raw_svector_ostream OSE(Data);
1064 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1065 AddrDelta, OSE);
1066 return OldSize != Data.size();
1067 }
1068
relaxDwarfCallFrameFragment(MCAsmLayout & Layout,MCDwarfCallFrameFragment & DF)1069 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1070 MCDwarfCallFrameFragment &DF) {
1071 MCContext &Context = Layout.getAssembler().getContext();
1072 uint64_t OldSize = DF.getContents().size();
1073 int64_t AddrDelta;
1074 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1075 assert(Abs && "We created call frame with an invalid expression");
1076 (void) Abs;
1077 SmallString<8> &Data = DF.getContents();
1078 Data.clear();
1079 raw_svector_ostream OSE(Data);
1080 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1081 return OldSize != Data.size();
1082 }
1083
layoutSectionOnce(MCAsmLayout & Layout,MCSection & Sec)1084 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1085 // Holds the first fragment which needed relaxing during this layout. It will
1086 // remain NULL if none were relaxed.
1087 // When a fragment is relaxed, all the fragments following it should get
1088 // invalidated because their offset is going to change.
1089 MCFragment *FirstRelaxedFragment = nullptr;
1090
1091 // Attempt to relax all the fragments in the section.
1092 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1093 // Check if this is a fragment that needs relaxation.
1094 bool RelaxedFrag = false;
1095 switch(I->getKind()) {
1096 default:
1097 break;
1098 case MCFragment::FT_Relaxable:
1099 assert(!getRelaxAll() &&
1100 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1101 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1102 break;
1103 case MCFragment::FT_Dwarf:
1104 RelaxedFrag = relaxDwarfLineAddr(Layout,
1105 *cast<MCDwarfLineAddrFragment>(I));
1106 break;
1107 case MCFragment::FT_DwarfFrame:
1108 RelaxedFrag =
1109 relaxDwarfCallFrameFragment(Layout,
1110 *cast<MCDwarfCallFrameFragment>(I));
1111 break;
1112 case MCFragment::FT_LEB:
1113 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1114 break;
1115 }
1116 if (RelaxedFrag && !FirstRelaxedFragment)
1117 FirstRelaxedFragment = &*I;
1118 }
1119 if (FirstRelaxedFragment) {
1120 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1121 return true;
1122 }
1123 return false;
1124 }
1125
layoutOnce(MCAsmLayout & Layout)1126 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1127 ++stats::RelaxationSteps;
1128
1129 bool WasRelaxed = false;
1130 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1131 MCSection &Sec = *it;
1132 while (layoutSectionOnce(Layout, Sec))
1133 WasRelaxed = true;
1134 }
1135
1136 return WasRelaxed;
1137 }
1138
finishLayout(MCAsmLayout & Layout)1139 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1140 // The layout is done. Mark every fragment as valid.
1141 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1142 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1143 }
1144 }
1145
1146 // Debugging methods
1147
1148 namespace llvm {
1149
operator <<(raw_ostream & OS,const MCFixup & AF)1150 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1151 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1152 << " Value:" << *AF.getValue()
1153 << " Kind:" << AF.getKind() << ">";
1154 return OS;
1155 }
1156
1157 }
1158
1159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump()1160 void MCFragment::dump() {
1161 raw_ostream &OS = llvm::errs();
1162
1163 OS << "<";
1164 switch (getKind()) {
1165 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1166 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1167 case MCFragment::FT_CompactEncodedInst:
1168 OS << "MCCompactEncodedInstFragment"; break;
1169 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1170 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1171 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1172 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1173 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1174 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1175 case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1176 case MCFragment::FT_Dummy:
1177 OS << "MCDummyFragment";
1178 break;
1179 }
1180
1181 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1182 << " Offset:" << Offset
1183 << " HasInstructions:" << hasInstructions()
1184 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1185
1186 switch (getKind()) {
1187 case MCFragment::FT_Align: {
1188 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1189 if (AF->hasEmitNops())
1190 OS << " (emit nops)";
1191 OS << "\n ";
1192 OS << " Alignment:" << AF->getAlignment()
1193 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1194 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1195 break;
1196 }
1197 case MCFragment::FT_Data: {
1198 const MCDataFragment *DF = cast<MCDataFragment>(this);
1199 OS << "\n ";
1200 OS << " Contents:[";
1201 const SmallVectorImpl<char> &Contents = DF->getContents();
1202 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1203 if (i) OS << ",";
1204 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1205 }
1206 OS << "] (" << Contents.size() << " bytes)";
1207
1208 if (DF->fixup_begin() != DF->fixup_end()) {
1209 OS << ",\n ";
1210 OS << " Fixups:[";
1211 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1212 ie = DF->fixup_end(); it != ie; ++it) {
1213 if (it != DF->fixup_begin()) OS << ",\n ";
1214 OS << *it;
1215 }
1216 OS << "]";
1217 }
1218 break;
1219 }
1220 case MCFragment::FT_CompactEncodedInst: {
1221 const MCCompactEncodedInstFragment *CEIF =
1222 cast<MCCompactEncodedInstFragment>(this);
1223 OS << "\n ";
1224 OS << " Contents:[";
1225 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1226 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1227 if (i) OS << ",";
1228 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1229 }
1230 OS << "] (" << Contents.size() << " bytes)";
1231 break;
1232 }
1233 case MCFragment::FT_Fill: {
1234 const MCFillFragment *FF = cast<MCFillFragment>(this);
1235 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1236 << " Size:" << FF->getSize();
1237 break;
1238 }
1239 case MCFragment::FT_Relaxable: {
1240 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1241 OS << "\n ";
1242 OS << " Inst:";
1243 F->getInst().dump_pretty(OS);
1244 break;
1245 }
1246 case MCFragment::FT_Org: {
1247 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1248 OS << "\n ";
1249 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1250 break;
1251 }
1252 case MCFragment::FT_Dwarf: {
1253 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1254 OS << "\n ";
1255 OS << " AddrDelta:" << OF->getAddrDelta()
1256 << " LineDelta:" << OF->getLineDelta();
1257 break;
1258 }
1259 case MCFragment::FT_DwarfFrame: {
1260 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1261 OS << "\n ";
1262 OS << " AddrDelta:" << CF->getAddrDelta();
1263 break;
1264 }
1265 case MCFragment::FT_LEB: {
1266 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1267 OS << "\n ";
1268 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1269 break;
1270 }
1271 case MCFragment::FT_SafeSEH: {
1272 const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1273 OS << "\n ";
1274 OS << " Sym:" << F->getSymbol();
1275 break;
1276 }
1277 case MCFragment::FT_Dummy:
1278 break;
1279 }
1280 OS << ">";
1281 }
1282
dump()1283 void MCAssembler::dump() {
1284 raw_ostream &OS = llvm::errs();
1285
1286 OS << "<MCAssembler\n";
1287 OS << " Sections:[\n ";
1288 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1289 if (it != begin()) OS << ",\n ";
1290 it->dump();
1291 }
1292 OS << "],\n";
1293 OS << " Symbols:[";
1294
1295 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1296 if (it != symbol_begin()) OS << ",\n ";
1297 OS << "(";
1298 it->dump();
1299 OS << ", Index:" << it->getIndex() << ", ";
1300 OS << ")";
1301 }
1302 OS << "]>\n";
1303 }
1304 #endif
1305