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