MC: Direct all {fragment,section,symbol} address access through the MCAsmLayout object.
[oota-llvm.git] / lib / MC / MCAssembler.cpp
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 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSymbol.h"
17 #include "llvm/MC/MCValue.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27
28 #include <vector>
29 using namespace llvm;
30
31 namespace {
32 namespace stats {
33 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
34 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36 STATISTIC(EvaluateFixup, "Number of evaluated fixups");
37 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
38 }
39 }
40
41 // FIXME FIXME FIXME: There are number of places in this file where we convert
42 // what is a 64-bit assembler value used for computation into a value in the
43 // object file, which may truncate it. We should detect that truncation where
44 // invalid and report errors back.
45
46 /* *** */
47
48 uint64_t MCAsmLayout::getFragmentAddress(const MCFragment *F) const {
49   return F->getAddress();
50 }
51
52 uint64_t MCAsmLayout::getSymbolAddress(const MCSymbolData *SD) const {
53   return SD->getAddress();
54 }
55
56 uint64_t MCAsmLayout::getSectionAddress(const MCSectionData *SD) const {
57   return SD->getAddress();
58 }
59
60 void MCAsmLayout::setSectionAddress(MCSectionData *SD, uint64_t Value) {
61   SD->setAddress(Value);
62 }
63
64 /* *** */
65
66 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
67 }
68
69 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
70   : Kind(_Kind),
71     Parent(_Parent),
72     FileSize(~UINT64_C(0))
73 {
74   if (Parent)
75     Parent->getFragmentList().push_back(this);
76 }
77
78 MCFragment::~MCFragment() {
79 }
80
81 uint64_t MCFragment::getAddress() const {
82   assert(getParent() && "Missing Section!");
83   return getParent()->getAddress() + Offset;
84 }
85
86 /* *** */
87
88 MCSectionData::MCSectionData() : Section(0) {}
89
90 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
91   : Section(&_Section),
92     Alignment(1),
93     Address(~UINT64_C(0)),
94     Size(~UINT64_C(0)),
95     FileSize(~UINT64_C(0)),
96     HasInstructions(false)
97 {
98   if (A)
99     A->getSectionList().push_back(this);
100 }
101
102 /* *** */
103
104 MCSymbolData::MCSymbolData() : Symbol(0) {}
105
106 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
107                            uint64_t _Offset, MCAssembler *A)
108   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
109     IsExternal(false), IsPrivateExtern(false),
110     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
111 {
112   if (A)
113     A->getSymbolList().push_back(this);
114 }
115
116 /* *** */
117
118 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
119                          MCCodeEmitter &_Emitter, raw_ostream &_OS)
120   : Context(_Context), Backend(_Backend), Emitter(_Emitter),
121     OS(_OS), SubsectionsViaSymbols(false)
122 {
123 }
124
125 MCAssembler::~MCAssembler() {
126 }
127
128 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
129                                                 const MCAsmFixup &Fixup,
130                                                 const MCValue Target,
131                                                 const MCSection *BaseSection) {
132   // The effective fixup address is
133   //     addr(atom(A)) + offset(A)
134   //   - addr(atom(B)) - offset(B)
135   //   - addr(<base symbol>) + <fixup offset from base symbol>
136   // and the offsets are not relocatable, so the fixup is fully resolved when
137   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
138   //
139   // The simple (Darwin, except on x86_64) way of dealing with this was to
140   // assume that any reference to a temporary symbol *must* be a temporary
141   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
142   // relocation to a temporary symbol (in the same section) is fully
143   // resolved. This also works in conjunction with absolutized .set, which
144   // requires the compiler to use .set to absolutize the differences between
145   // symbols which the compiler knows to be assembly time constants, so we don't
146   // need to worry about consider symbol differences fully resolved.
147
148   // Non-relative fixups are only resolved if constant.
149   if (!BaseSection)
150     return Target.isAbsolute();
151
152   // Otherwise, relative fixups are only resolved if not a difference and the
153   // target is a temporary in the same section.
154   if (Target.isAbsolute() || Target.getSymB())
155     return false;
156
157   const MCSymbol *A = &Target.getSymA()->getSymbol();
158   if (!A->isTemporary() || !A->isInSection() ||
159       &A->getSection() != BaseSection)
160     return false;
161
162   return true;
163 }
164
165 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
166                                           const MCAsmLayout &Layout,
167                                           const MCAsmFixup &Fixup,
168                                           const MCValue Target,
169                                           const MCSymbolData *BaseSymbol) {
170   // The effective fixup address is
171   //     addr(atom(A)) + offset(A)
172   //   - addr(atom(B)) - offset(B)
173   //   - addr(BaseSymbol) + <fixup offset from base symbol>
174   // and the offsets are not relocatable, so the fixup is fully resolved when
175   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
176   //
177   // Note that "false" is almost always conservatively correct (it means we emit
178   // a relocation which is unnecessary), except when it would force us to emit a
179   // relocation which the target cannot encode.
180
181   const MCSymbolData *A_Base = 0, *B_Base = 0;
182   if (const MCSymbolRefExpr *A = Target.getSymA()) {
183     // Modified symbol references cannot be resolved.
184     if (A->getKind() != MCSymbolRefExpr::VK_None)
185       return false;
186
187     A_Base = Asm.getAtom(Layout, &Asm.getSymbolData(A->getSymbol()));
188     if (!A_Base)
189       return false;
190   }
191
192   if (const MCSymbolRefExpr *B = Target.getSymB()) {
193     // Modified symbol references cannot be resolved.
194     if (B->getKind() != MCSymbolRefExpr::VK_None)
195       return false;
196
197     B_Base = Asm.getAtom(Layout, &Asm.getSymbolData(B->getSymbol()));
198     if (!B_Base)
199       return false;
200   }
201
202   // If there is no base, A and B have to be the same atom for this fixup to be
203   // fully resolved.
204   if (!BaseSymbol)
205     return A_Base == B_Base;
206
207   // Otherwise, B must be missing and A must be the base.
208   return !B_Base && BaseSymbol == A_Base;
209 }
210
211 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
212   // Non-temporary labels should always be visible to the linker.
213   if (!SD->getSymbol().isTemporary())
214     return true;
215
216   // Absolute temporary labels are never visible.
217   if (!SD->getFragment())
218     return false;
219
220   // Otherwise, check if the section requires symbols even for temporary labels.
221   return getBackend().doesSectionRequireSymbols(
222     SD->getFragment()->getParent()->getSection());
223 }
224
225 // FIXME-PERF: This routine is really slow.
226 const MCSymbolData *MCAssembler::getAtomForAddress(const MCAsmLayout &Layout,
227                                                    const MCSectionData *Section,
228                                                    uint64_t Address) const {
229   const MCSymbolData *Best = 0;
230   uint64_t BestAddress = 0;
231
232   for (MCAssembler::const_symbol_iterator it = symbol_begin(),
233          ie = symbol_end(); it != ie; ++it) {
234     // Ignore non-linker visible symbols.
235     if (!isSymbolLinkerVisible(it))
236       continue;
237
238     // Ignore symbols not in the same section.
239     if (!it->getFragment() || it->getFragment()->getParent() != Section)
240       continue;
241
242     // Otherwise, find the closest symbol preceding this address (ties are
243     // resolved in favor of the last defined symbol).
244     uint64_t SymbolAddress = Layout.getSymbolAddress(it);
245     if (SymbolAddress <= Address && (!Best || SymbolAddress >= BestAddress)) {
246       Best = it;
247       BestAddress = SymbolAddress;
248     }
249   }
250
251   return Best;
252 }
253
254 // FIXME-PERF: This routine is really slow.
255 const MCSymbolData *MCAssembler::getAtom(const MCAsmLayout &Layout,
256                                          const MCSymbolData *SD) const {
257   // Linker visible symbols define atoms.
258   if (isSymbolLinkerVisible(SD))
259     return SD;
260
261   // Absolute and undefined symbols have no defining atom.
262   if (!SD->getFragment())
263     return 0;
264
265   // Otherwise, search by address.
266   return getAtomForAddress(Layout, SD->getFragment()->getParent(),
267                            Layout.getSymbolAddress(SD));
268 }
269
270 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
271                                 const MCAsmFixup &Fixup, const MCFragment *DF,
272                                 MCValue &Target, uint64_t &Value) const {
273   ++stats::EvaluateFixup;
274
275   if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
276     llvm_report_error("expected relocatable expression");
277
278   // FIXME: How do non-scattered symbols work in ELF? I presume the linker
279   // doesn't support small relocations, but then under what criteria does the
280   // assembler allow symbol differences?
281
282   Value = Target.getConstant();
283
284   bool IsPCRel =
285     Emitter.getFixupKindInfo(Fixup.Kind).Flags & MCFixupKindInfo::FKF_IsPCRel;
286   bool IsResolved = true;
287   if (const MCSymbolRefExpr *A = Target.getSymA()) {
288     if (A->getSymbol().isDefined())
289       Value += Layout.getSymbolAddress(&getSymbolData(A->getSymbol()));
290     else
291       IsResolved = false;
292   }
293   if (const MCSymbolRefExpr *B = Target.getSymB()) {
294     if (B->getSymbol().isDefined())
295       Value -= Layout.getSymbolAddress(&getSymbolData(B->getSymbol()));
296     else
297       IsResolved = false;
298   }
299
300   // If we are using scattered symbols, determine whether this value is actually
301   // resolved; scattering may cause atoms to move.
302   if (IsResolved && getBackend().hasScatteredSymbols()) {
303     if (getBackend().hasReliableSymbolDifference()) {
304       // If this is a PCrel relocation, find the base atom (identified by its
305       // symbol) that the fixup value is relative to.
306       const MCSymbolData *BaseSymbol = 0;
307       if (IsPCRel) {
308         BaseSymbol = getAtomForAddress(
309           Layout, DF->getParent(), Layout.getFragmentAddress(DF)+Fixup.Offset);
310         if (!BaseSymbol)
311           IsResolved = false;
312       }
313
314       if (IsResolved)
315         IsResolved = isScatteredFixupFullyResolved(*this, Layout, Fixup, Target,
316                                                    BaseSymbol);
317     } else {
318       const MCSection *BaseSection = 0;
319       if (IsPCRel)
320         BaseSection = &DF->getParent()->getSection();
321
322       IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, Target,
323                                                        BaseSection);
324     }
325   }
326
327   if (IsPCRel)
328     Value -= Layout.getFragmentAddress(DF) + Fixup.Offset;
329
330   return IsResolved;
331 }
332
333 void MCAssembler::LayoutSection(MCSectionData &SD,
334                                 MCAsmLayout &Layout) {
335   uint64_t Address, StartAddress = Address = Layout.getSectionAddress(&SD);
336
337   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
338     MCFragment &F = *it;
339
340     F.setOffset(Address - StartAddress);
341
342     // Evaluate fragment size.
343     switch (F.getKind()) {
344     case MCFragment::FT_Align: {
345       MCAlignFragment &AF = cast<MCAlignFragment>(F);
346
347       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
348       if (Size > AF.getMaxBytesToEmit())
349         AF.setFileSize(0);
350       else
351         AF.setFileSize(Size);
352       break;
353     }
354
355     case MCFragment::FT_Data:
356       F.setFileSize(cast<MCDataFragment>(F).getContents().size());
357       break;
358
359     case MCFragment::FT_Fill: {
360       MCFillFragment &FF = cast<MCFillFragment>(F);
361       F.setFileSize(FF.getValueSize() * FF.getCount());
362       break;
363     }
364
365     case MCFragment::FT_Inst:
366       F.setFileSize(cast<MCInstFragment>(F).getInstSize());
367       break;
368
369     case MCFragment::FT_Org: {
370       MCOrgFragment &OF = cast<MCOrgFragment>(F);
371
372       int64_t TargetLocation;
373       if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
374         llvm_report_error("expected assembly-time absolute expression");
375
376       // FIXME: We need a way to communicate this error.
377       int64_t Offset = TargetLocation - F.getOffset();
378       if (Offset < 0)
379         llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
380                           "' (at offset '" + Twine(F.getOffset()) + "'");
381
382       F.setFileSize(Offset);
383       break;
384     }
385
386     case MCFragment::FT_ZeroFill: {
387       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
388
389       // Align the fragment offset; it is safe to adjust the offset freely since
390       // this is only in virtual sections.
391       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
392       F.setOffset(Address - StartAddress);
393
394       // FIXME: This is misnamed.
395       F.setFileSize(ZFF.getSize());
396       break;
397     }
398     }
399
400     Address += F.getFileSize();
401   }
402
403   // Set the section sizes.
404   SD.setSize(Address - StartAddress);
405   if (getBackend().isVirtualSection(SD.getSection()))
406     SD.setFileSize(0);
407   else
408     SD.setFileSize(Address - StartAddress);
409 }
410
411 /// WriteFragmentData - Write the \arg F data to the output file.
412 static void WriteFragmentData(const MCAssembler &Asm, const MCFragment &F,
413                               MCObjectWriter *OW) {
414   uint64_t Start = OW->getStream().tell();
415   (void) Start;
416
417   ++stats::EmittedFragments;
418
419   // FIXME: Embed in fragments instead?
420   switch (F.getKind()) {
421   case MCFragment::FT_Align: {
422     MCAlignFragment &AF = cast<MCAlignFragment>(F);
423     uint64_t Count = AF.getFileSize() / AF.getValueSize();
424
425     // FIXME: This error shouldn't actually occur (the front end should emit
426     // multiple .align directives to enforce the semantics it wants), but is
427     // severe enough that we want to report it. How to handle this?
428     if (Count * AF.getValueSize() != AF.getFileSize())
429       llvm_report_error("undefined .align directive, value size '" +
430                         Twine(AF.getValueSize()) +
431                         "' is not a divisor of padding size '" +
432                         Twine(AF.getFileSize()) + "'");
433
434     // See if we are aligning with nops, and if so do that first to try to fill
435     // the Count bytes.  Then if that did not fill any bytes or there are any
436     // bytes left to fill use the the Value and ValueSize to fill the rest.
437     // If we are aligning with nops, ask that target to emit the right data.
438     if (AF.getEmitNops()) {
439       if (!Asm.getBackend().WriteNopData(Count, OW))
440         llvm_report_error("unable to write nop sequence of " +
441                           Twine(Count) + " bytes");
442       break;
443     }
444
445     // Otherwise, write out in multiples of the value size.
446     for (uint64_t i = 0; i != Count; ++i) {
447       switch (AF.getValueSize()) {
448       default:
449         assert(0 && "Invalid size!");
450       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
451       case 2: OW->Write16(uint16_t(AF.getValue())); break;
452       case 4: OW->Write32(uint32_t(AF.getValue())); break;
453       case 8: OW->Write64(uint64_t(AF.getValue())); break;
454       }
455     }
456     break;
457   }
458
459   case MCFragment::FT_Data: {
460     MCDataFragment &DF = cast<MCDataFragment>(F);
461     assert(DF.getFileSize() == DF.getContents().size() && "Invalid size!");
462     OW->WriteBytes(DF.getContents().str());
463     break;
464   }
465
466   case MCFragment::FT_Fill: {
467     MCFillFragment &FF = cast<MCFillFragment>(F);
468     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
469       switch (FF.getValueSize()) {
470       default:
471         assert(0 && "Invalid size!");
472       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
473       case 2: OW->Write16(uint16_t(FF.getValue())); break;
474       case 4: OW->Write32(uint32_t(FF.getValue())); break;
475       case 8: OW->Write64(uint64_t(FF.getValue())); break;
476       }
477     }
478     break;
479   }
480
481   case MCFragment::FT_Inst:
482     llvm_unreachable("unexpected inst fragment after lowering");
483     break;
484
485   case MCFragment::FT_Org: {
486     MCOrgFragment &OF = cast<MCOrgFragment>(F);
487
488     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
489       OW->Write8(uint8_t(OF.getValue()));
490
491     break;
492   }
493
494   case MCFragment::FT_ZeroFill: {
495     assert(0 && "Invalid zero fill fragment in concrete section!");
496     break;
497   }
498   }
499
500   assert(OW->getStream().tell() - Start == F.getFileSize());
501 }
502
503 void MCAssembler::WriteSectionData(const MCSectionData *SD,
504                                    MCObjectWriter *OW) const {
505   // Ignore virtual sections.
506   if (getBackend().isVirtualSection(SD->getSection())) {
507     assert(SD->getFileSize() == 0);
508     return;
509   }
510
511   uint64_t Start = OW->getStream().tell();
512   (void) Start;
513
514   for (MCSectionData::const_iterator it = SD->begin(),
515          ie = SD->end(); it != ie; ++it)
516     WriteFragmentData(*this, *it, OW);
517
518   // Add section padding.
519   assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
520   OW->WriteZeros(SD->getFileSize() - SD->getSize());
521
522   assert(OW->getStream().tell() - Start == SD->getFileSize());
523 }
524
525 void MCAssembler::Finish() {
526   DEBUG_WITH_TYPE("mc-dump", {
527       llvm::errs() << "assembler backend - pre-layout\n--\n";
528       dump(); });
529
530   // Layout until everything fits.
531   MCAsmLayout Layout(*this);
532   while (LayoutOnce(Layout))
533     continue;
534
535   DEBUG_WITH_TYPE("mc-dump", {
536       llvm::errs() << "assembler backend - post-relaxation\n--\n";
537       dump(); });
538
539   // Finalize the layout, including fragment lowering.
540   FinishLayout(Layout);
541
542   DEBUG_WITH_TYPE("mc-dump", {
543       llvm::errs() << "assembler backend - final-layout\n--\n";
544       dump(); });
545
546   uint64_t StartOffset = OS.tell();
547   llvm::OwningPtr<MCObjectWriter> Writer(getBackend().createObjectWriter(OS));
548   if (!Writer)
549     llvm_report_error("unable to create object writer!");
550
551   // Allow the object writer a chance to perform post-layout binding (for
552   // example, to set the index fields in the symbol data).
553   Writer->ExecutePostLayoutBinding(*this);
554
555   // Evaluate and apply the fixups, generating relocation entries as necessary.
556   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
557     for (MCSectionData::iterator it2 = it->begin(),
558            ie2 = it->end(); it2 != ie2; ++it2) {
559       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
560       if (!DF)
561         continue;
562
563       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
564              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
565         MCAsmFixup &Fixup = *it3;
566
567         // Evaluate the fixup.
568         MCValue Target;
569         uint64_t FixedValue;
570         if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
571           // The fixup was unresolved, we need a relocation. Inform the object
572           // writer of the relocation, and give it an opportunity to adjust the
573           // fixup value if need be.
574           Writer->RecordRelocation(*this, Layout, DF, Fixup, Target,FixedValue);
575         }
576
577         getBackend().ApplyFixup(Fixup, *DF, FixedValue);
578       }
579     }
580   }
581
582   // Write the object file.
583   Writer->WriteObject(*this, Layout);
584   OS.flush();
585
586   stats::ObjectBytes += OS.tell() - StartOffset;
587 }
588
589 bool MCAssembler::FixupNeedsRelaxation(const MCAsmFixup &Fixup,
590                                        const MCFragment *DF,
591                                        const MCAsmLayout &Layout) const {
592   // If we cannot resolve the fixup value, it requires relaxation.
593   MCValue Target;
594   uint64_t Value;
595   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
596     return true;
597
598   // Otherwise, relax if the value is too big for a (signed) i8.
599   return int64_t(Value) != int64_t(int8_t(Value));
600 }
601
602 bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
603                                           const MCAsmLayout &Layout) const {
604   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
605   // are intentionally pushing out inst fragments, or because we relaxed a
606   // previous instruction to one that doesn't need relaxation.
607   if (!getBackend().MayNeedRelaxation(IF->getInst(), IF->getFixups()))
608     return false;
609
610   for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
611          ie = IF->fixup_end(); it != ie; ++it)
612     if (FixupNeedsRelaxation(*it, IF, Layout))
613       return true;
614
615   return false;
616 }
617
618 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
619   ++stats::RelaxationSteps;
620
621   // Layout the concrete sections and fragments.
622   uint64_t Address = 0;
623   MCSectionData *Prev = 0;
624   for (iterator it = begin(), ie = end(); it != ie; ++it) {
625     MCSectionData &SD = *it;
626
627     // Skip virtual sections.
628     if (getBackend().isVirtualSection(SD.getSection()))
629       continue;
630
631     // Align this section if necessary by adding padding bytes to the previous
632     // section.
633     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
634       assert(Prev && "Missing prev section!");
635       Prev->setFileSize(Prev->getFileSize() + Pad);
636       Address += Pad;
637     }
638
639     // Layout the section fragments and its size.
640     Layout.setSectionAddress(&SD, Address);
641     LayoutSection(SD, Layout);
642     Address += SD.getFileSize();
643
644     Prev = &SD;
645   }
646
647   // Layout the virtual sections.
648   for (iterator it = begin(), ie = end(); it != ie; ++it) {
649     MCSectionData &SD = *it;
650
651     if (!getBackend().isVirtualSection(SD.getSection()))
652       continue;
653
654     // Align this section if necessary by adding padding bytes to the previous
655     // section.
656     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
657       Address += Pad;
658
659     Layout.setSectionAddress(&SD, Address);
660     LayoutSection(SD, Layout);
661     Address += SD.getSize();
662   }
663
664   // Scan for fragments that need relaxation.
665   for (iterator it = begin(), ie = end(); it != ie; ++it) {
666     MCSectionData &SD = *it;
667
668     for (MCSectionData::iterator it2 = SD.begin(),
669            ie2 = SD.end(); it2 != ie2; ++it2) {
670       // Check if this is an instruction fragment that needs relaxation.
671       MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
672       if (!IF || !FragmentNeedsRelaxation(IF, Layout))
673         continue;
674
675       ++stats::RelaxedInstructions;
676
677       // FIXME-PERF: We could immediately lower out instructions if we can tell
678       // they are fully resolved, to avoid retesting on later passes.
679
680       // Relax the fragment.
681
682       MCInst Relaxed;
683       getBackend().RelaxInstruction(IF, Relaxed);
684
685       // Encode the new instruction.
686       //
687       // FIXME-PERF: If it matters, we could let the target do this. It can
688       // probably do so more efficiently in many cases.
689       SmallVector<MCFixup, 4> Fixups;
690       SmallString<256> Code;
691       raw_svector_ostream VecOS(Code);
692       getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
693       VecOS.flush();
694
695       // Update the instruction fragment.
696       IF->setInst(Relaxed);
697       IF->getCode() = Code;
698       IF->getFixups().clear();
699       for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
700         MCFixup &F = Fixups[i];
701         IF->getFixups().push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
702                                              F.getKind()));
703       }
704
705       // Restart layout.
706       //
707       // FIXME-PERF: This is O(N^2), but will be eliminated once we have a
708       // smart MCAsmLayout object.
709       return true;
710     }
711   }
712
713   return false;
714 }
715
716 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
717   // Lower out any instruction fragments, to simplify the fixup application and
718   // output.
719   //
720   // FIXME-PERF: We don't have to do this, but the assumption is that it is
721   // cheap (we will mostly end up eliminating fragments and appending on to data
722   // fragments), so the extra complexity downstream isn't worth it. Evaluate
723   // this assumption.
724   for (iterator it = begin(), ie = end(); it != ie; ++it) {
725     MCSectionData &SD = *it;
726
727     for (MCSectionData::iterator it2 = SD.begin(),
728            ie2 = SD.end(); it2 != ie2; ++it2) {
729       MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
730       if (!IF)
731         continue;
732
733       // Create a new data fragment for the instruction.
734       //
735       // FIXME-PERF: Reuse previous data fragment if possible.
736       MCDataFragment *DF = new MCDataFragment();
737       SD.getFragmentList().insert(it2, DF);
738
739       // Update the data fragments layout data.
740       DF->setParent(IF->getParent());
741       DF->setOffset(IF->getOffset());
742       DF->setFileSize(IF->getInstSize());
743
744       // Copy in the data and the fixups.
745       DF->getContents().append(IF->getCode().begin(), IF->getCode().end());
746       for (unsigned i = 0, e = IF->getFixups().size(); i != e; ++i)
747         DF->getFixups().push_back(IF->getFixups()[i]);
748
749       // Delete the instruction fragment and update the iterator.
750       SD.getFragmentList().erase(IF);
751       it2 = DF;
752     }
753   }
754 }
755
756 // Debugging methods
757
758 namespace llvm {
759
760 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
761   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
762      << " Kind:" << AF.Kind << ">";
763   return OS;
764 }
765
766 }
767
768 void MCFragment::dump() {
769   raw_ostream &OS = llvm::errs();
770
771   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
772      << " FileSize:" << FileSize;
773
774   OS << ">";
775 }
776
777 void MCAlignFragment::dump() {
778   raw_ostream &OS = llvm::errs();
779
780   OS << "<MCAlignFragment ";
781   this->MCFragment::dump();
782   OS << "\n       ";
783   OS << " Alignment:" << getAlignment()
784      << " Value:" << getValue() << " ValueSize:" << getValueSize()
785      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
786 }
787
788 void MCDataFragment::dump() {
789   raw_ostream &OS = llvm::errs();
790
791   OS << "<MCDataFragment ";
792   this->MCFragment::dump();
793   OS << "\n       ";
794   OS << " Contents:[";
795   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
796     if (i) OS << ",";
797     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
798   }
799   OS << "] (" << getContents().size() << " bytes)";
800
801   if (!getFixups().empty()) {
802     OS << ",\n       ";
803     OS << " Fixups:[";
804     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
805       if (it != fixup_begin()) OS << ",\n                ";
806       OS << *it;
807     }
808     OS << "]";
809   }
810
811   OS << ">";
812 }
813
814 void MCFillFragment::dump() {
815   raw_ostream &OS = llvm::errs();
816
817   OS << "<MCFillFragment ";
818   this->MCFragment::dump();
819   OS << "\n       ";
820   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
821      << " Count:" << getCount() << ">";
822 }
823
824 void MCInstFragment::dump() {
825   raw_ostream &OS = llvm::errs();
826
827   OS << "<MCInstFragment ";
828   this->MCFragment::dump();
829   OS << "\n       ";
830   OS << " Inst:";
831   getInst().dump_pretty(OS);
832   OS << ">";
833 }
834
835 void MCOrgFragment::dump() {
836   raw_ostream &OS = llvm::errs();
837
838   OS << "<MCOrgFragment ";
839   this->MCFragment::dump();
840   OS << "\n       ";
841   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
842 }
843
844 void MCZeroFillFragment::dump() {
845   raw_ostream &OS = llvm::errs();
846
847   OS << "<MCZeroFillFragment ";
848   this->MCFragment::dump();
849   OS << "\n       ";
850   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
851 }
852
853 void MCSectionData::dump() {
854   raw_ostream &OS = llvm::errs();
855
856   OS << "<MCSectionData";
857   OS << " Alignment:" << getAlignment() << " Address:" << Address
858      << " Size:" << Size << " FileSize:" << FileSize
859      << " Fragments:[\n      ";
860   for (iterator it = begin(), ie = end(); it != ie; ++it) {
861     if (it != begin()) OS << ",\n      ";
862     it->dump();
863   }
864   OS << "]>";
865 }
866
867 void MCSymbolData::dump() {
868   raw_ostream &OS = llvm::errs();
869
870   OS << "<MCSymbolData Symbol:" << getSymbol()
871      << " Fragment:" << getFragment() << " Offset:" << getOffset()
872      << " Flags:" << getFlags() << " Index:" << getIndex();
873   if (isCommon())
874     OS << " (common, size:" << getCommonSize()
875        << " align: " << getCommonAlignment() << ")";
876   if (isExternal())
877     OS << " (external)";
878   if (isPrivateExtern())
879     OS << " (private extern)";
880   OS << ">";
881 }
882
883 void MCAssembler::dump() {
884   raw_ostream &OS = llvm::errs();
885
886   OS << "<MCAssembler\n";
887   OS << "  Sections:[\n    ";
888   for (iterator it = begin(), ie = end(); it != ie; ++it) {
889     if (it != begin()) OS << ",\n    ";
890     it->dump();
891   }
892   OS << "],\n";
893   OS << "  Symbols:[";
894
895   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
896     if (it != symbol_begin()) OS << ",\n           ";
897     it->dump();
898   }
899   OS << "]>\n";
900 }