Reimplement CTPOP legalization with the "best" algorithm from
[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/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetAsmBackend.h"
30
31 #include <vector>
32 using namespace llvm;
33
34 namespace {
35 namespace stats {
36 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
37 STATISTIC(EvaluateFixup, "Number of evaluated fixups");
38 STATISTIC(FragmentLayouts, "Number of fragment layouts");
39 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
40 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
41 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
42 }
43 }
44
45 // FIXME FIXME FIXME: There are number of places in this file where we convert
46 // what is a 64-bit assembler value used for computation into a value in the
47 // object file, which may truncate it. We should detect that truncation where
48 // invalid and report errors back.
49
50 /* *** */
51
52 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
53   : Assembler(Asm), LastValidFragment()
54  {
55   // Compute the section layout order. Virtual sections must go last.
56   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
57     if (!it->getSection().isVirtualSection())
58       SectionOrder.push_back(&*it);
59   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
60     if (it->getSection().isVirtualSection())
61       SectionOrder.push_back(&*it);
62 }
63
64 bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
65   const MCSectionData &SD = *F->getParent();
66   const MCFragment *LastValid = LastValidFragment.lookup(&SD);
67   if (!LastValid)
68     return false;
69   assert(LastValid->getParent() == F->getParent());
70   return F->getLayoutOrder() <= LastValid->getLayoutOrder();
71 }
72
73 void MCAsmLayout::Invalidate(MCFragment *F) {
74   // If this fragment wasn't already up-to-date, we don't need to do anything.
75   if (!isFragmentUpToDate(F))
76     return;
77
78   // Otherwise, reset the last valid fragment to this fragment.
79   const MCSectionData &SD = *F->getParent();
80   LastValidFragment[&SD] = F;
81 }
82
83 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
84   MCSectionData &SD = *F->getParent();
85
86   MCFragment *Cur = LastValidFragment[&SD];
87   if (!Cur)
88     Cur = &*SD.begin();
89   else
90     Cur = Cur->getNextNode();
91
92   // Advance the layout position until the fragment is up-to-date.
93   while (!isFragmentUpToDate(F)) {
94     const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
95     Cur = Cur->getNextNode();
96   }
97 }
98
99 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
100   EnsureValid(F);
101   assert(F->Offset != ~UINT64_C(0) && "Address not set!");
102   return F->Offset;
103 }
104
105 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
106   assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
107   return getFragmentOffset(SD->getFragment()) + SD->getOffset();
108 }
109
110 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
111   // The size is the last fragment's end offset.
112   const MCFragment &F = SD->getFragmentList().back();
113   return getFragmentOffset(&F) + getAssembler().ComputeFragmentSize(*this, F);
114 }
115
116 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
117   // Virtual sections have no file size.
118   if (SD->getSection().isVirtualSection())
119     return 0;
120
121   // Otherwise, the file size is the same as the address space size.
122   return getSectionAddressSize(SD);
123 }
124
125 /* *** */
126
127 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
128 }
129
130 MCFragment::~MCFragment() {
131 }
132
133 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
134   : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
135 {
136   if (Parent)
137     Parent->getFragmentList().push_back(this);
138 }
139
140 /* *** */
141
142 MCSectionData::MCSectionData() : Section(0) {}
143
144 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
145   : Section(&_Section),
146     Ordinal(~UINT32_C(0)),
147     Alignment(1),
148     HasInstructions(false)
149 {
150   if (A)
151     A->getSectionList().push_back(this);
152 }
153
154 /* *** */
155
156 MCSymbolData::MCSymbolData() : Symbol(0) {}
157
158 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
159                            uint64_t _Offset, MCAssembler *A)
160   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
161     IsExternal(false), IsPrivateExtern(false),
162     CommonSize(0), SymbolSize(0), CommonAlign(0),
163     Flags(0), Index(0)
164 {
165   if (A)
166     A->getSymbolList().push_back(this);
167 }
168
169 /* *** */
170
171 MCAssembler::MCAssembler(MCContext &Context_, TargetAsmBackend &Backend_,
172                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
173                          raw_ostream &OS_)
174   : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
175     OS(OS_), RelaxAll(false), SubsectionsViaSymbols(false)
176 {
177 }
178
179 MCAssembler::~MCAssembler() {
180 }
181
182 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
183   // Non-temporary labels should always be visible to the linker.
184   if (!Symbol.isTemporary())
185     return true;
186
187   // Absolute temporary labels are never visible.
188   if (!Symbol.isInSection())
189     return false;
190
191   // Otherwise, check if the section requires symbols even for temporary labels.
192   return getBackend().doesSectionRequireSymbols(Symbol.getSection());
193 }
194
195 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
196   // Linker visible symbols define atoms.
197   if (isSymbolLinkerVisible(SD->getSymbol()))
198     return SD;
199
200   // Absolute and undefined symbols have no defining atom.
201   if (!SD->getFragment())
202     return 0;
203
204   // Non-linker visible symbols in sections which can't be atomized have no
205   // defining atom.
206   if (!getBackend().isSectionAtomizable(
207         SD->getFragment()->getParent()->getSection()))
208     return 0;
209
210   // Otherwise, return the atom for the containing fragment.
211   return SD->getFragment()->getAtom();
212 }
213
214 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
215                                 const MCFixup &Fixup, const MCFragment *DF,
216                                 MCValue &Target, uint64_t &Value) const {
217   ++stats::EvaluateFixup;
218
219   if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
220     report_fatal_error("expected relocatable expression");
221
222   bool IsPCRel = Backend.getFixupKindInfo(
223     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
224
225   bool IsResolved;
226   if (IsPCRel) {
227     if (Target.getSymB()) {
228       IsResolved = false;
229     } else if (!Target.getSymA()) {
230       IsResolved = false;
231     } else {
232       const MCSymbol &SA = Target.getSymA()->getSymbol();
233       if (SA.AliasedSymbol().isUndefined()) {
234         IsResolved = false;
235       } else {
236         const MCSymbolData &DataA = getSymbolData(SA);
237         IsResolved =
238           getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
239                                                              *DF, false, true);
240       }
241     }
242   } else {
243     IsResolved = Target.isAbsolute();
244   }
245
246   Value = Target.getConstant();
247
248   bool IsThumb = false;
249   if (const MCSymbolRefExpr *A = Target.getSymA()) {
250     const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
251     if (Sym.isDefined())
252       Value += Layout.getSymbolOffset(&getSymbolData(Sym));
253     if (isThumbFunc(&Sym))
254       IsThumb = true;
255   }
256   if (const MCSymbolRefExpr *B = Target.getSymB()) {
257     const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
258     if (Sym.isDefined())
259       Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
260   }
261
262
263   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
264                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
265   assert((ShouldAlignPC ? IsPCRel : true) &&
266     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
267
268   if (IsPCRel) {
269     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
270     
271     // A number of ARM fixups in Thumb mode require that the effective PC
272     // address be determined as the 32-bit aligned version of the actual offset.
273     if (ShouldAlignPC) Offset &= ~0x3;
274     Value -= Offset;
275   }
276
277   // ARM fixups based from a thumb function address need to have the low
278   // bit set. The actual value is always at least 16-bit aligned, so the
279   // low bit is normally clear and available for use as an ISA flag for
280   // interworking.
281   if (IsThumb)
282     Value |= 1;
283
284   return IsResolved;
285 }
286
287 uint64_t MCAssembler::ComputeFragmentSize(const MCAsmLayout &Layout,
288                                           const MCFragment &F) const {
289   switch (F.getKind()) {
290   case MCFragment::FT_Data:
291     return cast<MCDataFragment>(F).getContents().size();
292   case MCFragment::FT_Fill:
293     return cast<MCFillFragment>(F).getSize();
294   case MCFragment::FT_Inst:
295     return cast<MCInstFragment>(F).getInstSize();
296
297   case MCFragment::FT_LEB:
298     return cast<MCLEBFragment>(F).getContents().size();
299
300   case MCFragment::FT_Align: {
301     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
302     unsigned Offset = Layout.getFragmentOffset(&AF);
303     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
304     if (Size > AF.getMaxBytesToEmit())
305       return 0;
306     return Size;
307   }
308
309   case MCFragment::FT_Org: {
310     MCOrgFragment &OF = cast<MCOrgFragment>(F);
311     int64_t TargetLocation;
312     if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
313       report_fatal_error("expected assembly-time absolute expression");
314
315     // FIXME: We need a way to communicate this error.
316     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
317     int64_t Size = TargetLocation - FragmentOffset;
318     if (Size < 0 || Size >= 0x40000000)
319       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
320                          "' (at offset '" + Twine(FragmentOffset) + "')");
321     return Size;
322   }
323
324   case MCFragment::FT_Dwarf:
325     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
326   case MCFragment::FT_DwarfFrame:
327     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
328   }
329
330   assert(0 && "invalid fragment kind");
331   return 0;
332 }
333
334 void MCAsmLayout::LayoutFragment(MCFragment *F) {
335   MCFragment *Prev = F->getPrevNode();
336
337   // We should never try to recompute something which is up-to-date.
338   assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
339   // We should never try to compute the fragment layout if it's predecessor
340   // isn't up-to-date.
341   assert((!Prev || isFragmentUpToDate(Prev)) &&
342          "Attempt to compute fragment before it's predecessor!");
343
344   ++stats::FragmentLayouts;
345
346   // Compute fragment offset and size.
347   uint64_t Offset = 0;
348   if (Prev)
349     Offset += Prev->Offset + getAssembler().ComputeFragmentSize(*this, *Prev);
350
351   F->Offset = Offset;
352   LastValidFragment[F->getParent()] = F;
353 }
354
355 /// WriteFragmentData - Write the \arg F data to the output file.
356 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
357                               const MCFragment &F) {
358   MCObjectWriter *OW = &Asm.getWriter();
359   uint64_t Start = OW->getStream().tell();
360   (void) Start;
361
362   ++stats::EmittedFragments;
363
364   // FIXME: Embed in fragments instead?
365   uint64_t FragmentSize = Asm.ComputeFragmentSize(Layout, F);
366   switch (F.getKind()) {
367   case MCFragment::FT_Align: {
368     MCAlignFragment &AF = cast<MCAlignFragment>(F);
369     uint64_t Count = FragmentSize / AF.getValueSize();
370
371     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
372
373     // FIXME: This error shouldn't actually occur (the front end should emit
374     // multiple .align directives to enforce the semantics it wants), but is
375     // severe enough that we want to report it. How to handle this?
376     if (Count * AF.getValueSize() != FragmentSize)
377       report_fatal_error("undefined .align directive, value size '" +
378                         Twine(AF.getValueSize()) +
379                         "' is not a divisor of padding size '" +
380                         Twine(FragmentSize) + "'");
381
382     // See if we are aligning with nops, and if so do that first to try to fill
383     // the Count bytes.  Then if that did not fill any bytes or there are any
384     // bytes left to fill use the the Value and ValueSize to fill the rest.
385     // If we are aligning with nops, ask that target to emit the right data.
386     if (AF.hasEmitNops()) {
387       if (!Asm.getBackend().WriteNopData(Count, OW))
388         report_fatal_error("unable to write nop sequence of " +
389                           Twine(Count) + " bytes");
390       break;
391     }
392
393     // Otherwise, write out in multiples of the value size.
394     for (uint64_t i = 0; i != Count; ++i) {
395       switch (AF.getValueSize()) {
396       default:
397         assert(0 && "Invalid size!");
398       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
399       case 2: OW->Write16(uint16_t(AF.getValue())); break;
400       case 4: OW->Write32(uint32_t(AF.getValue())); break;
401       case 8: OW->Write64(uint64_t(AF.getValue())); break;
402       }
403     }
404     break;
405   }
406
407   case MCFragment::FT_Data: {
408     MCDataFragment &DF = cast<MCDataFragment>(F);
409     assert(FragmentSize == DF.getContents().size() && "Invalid size!");
410     OW->WriteBytes(DF.getContents().str());
411     break;
412   }
413
414   case MCFragment::FT_Fill: {
415     MCFillFragment &FF = cast<MCFillFragment>(F);
416
417     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
418
419     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
420       switch (FF.getValueSize()) {
421       default:
422         assert(0 && "Invalid size!");
423       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
424       case 2: OW->Write16(uint16_t(FF.getValue())); break;
425       case 4: OW->Write32(uint32_t(FF.getValue())); break;
426       case 8: OW->Write64(uint64_t(FF.getValue())); break;
427       }
428     }
429     break;
430   }
431
432   case MCFragment::FT_Inst: {
433     MCInstFragment &IF = cast<MCInstFragment>(F);
434     OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
435     break;
436   }
437
438   case MCFragment::FT_LEB: {
439     MCLEBFragment &LF = cast<MCLEBFragment>(F);
440     OW->WriteBytes(LF.getContents().str());
441     break;
442   }
443
444   case MCFragment::FT_Org: {
445     MCOrgFragment &OF = cast<MCOrgFragment>(F);
446
447     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
448       OW->Write8(uint8_t(OF.getValue()));
449
450     break;
451   }
452
453   case MCFragment::FT_Dwarf: {
454     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
455     OW->WriteBytes(OF.getContents().str());
456     break;
457   }
458   case MCFragment::FT_DwarfFrame: {
459     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
460     OW->WriteBytes(CF.getContents().str());
461     break;
462   }
463   }
464
465   assert(OW->getStream().tell() - Start == FragmentSize);
466 }
467
468 void MCAssembler::WriteSectionData(const MCSectionData *SD,
469                                    const MCAsmLayout &Layout) const {
470   // Ignore virtual sections.
471   if (SD->getSection().isVirtualSection()) {
472     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
473
474     // Check that contents are only things legal inside a virtual section.
475     for (MCSectionData::const_iterator it = SD->begin(),
476            ie = SD->end(); it != ie; ++it) {
477       switch (it->getKind()) {
478       default:
479         assert(0 && "Invalid fragment in virtual section!");
480       case MCFragment::FT_Data: {
481         // Check that we aren't trying to write a non-zero contents (or fixups)
482         // into a virtual section. This is to support clients which use standard
483         // directives to fill the contents of virtual sections.
484         MCDataFragment &DF = cast<MCDataFragment>(*it);
485         assert(DF.fixup_begin() == DF.fixup_end() &&
486                "Cannot have fixups in virtual section!");
487         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
488           assert(DF.getContents()[i] == 0 &&
489                  "Invalid data value for virtual section!");
490         break;
491       }
492       case MCFragment::FT_Align:
493         // Check that we aren't trying to write a non-zero value into a virtual
494         // section.
495         assert((!cast<MCAlignFragment>(it)->getValueSize() ||
496                 !cast<MCAlignFragment>(it)->getValue()) &&
497                "Invalid align in virtual section!");
498         break;
499       case MCFragment::FT_Fill:
500         assert(!cast<MCFillFragment>(it)->getValueSize() &&
501                "Invalid fill in virtual section!");
502         break;
503       }
504     }
505
506     return;
507   }
508
509   uint64_t Start = getWriter().getStream().tell();
510   (void) Start;
511
512   for (MCSectionData::const_iterator it = SD->begin(),
513          ie = SD->end(); it != ie; ++it)
514     WriteFragmentData(*this, Layout, *it);
515
516   assert(getWriter().getStream().tell() - Start ==
517          Layout.getSectionAddressSize(SD));
518 }
519
520
521 uint64_t MCAssembler::HandleFixup(const MCAsmLayout &Layout,
522                                   MCFragment &F,
523                                   const MCFixup &Fixup) {
524    // Evaluate the fixup.
525    MCValue Target;
526    uint64_t FixedValue;
527    if (!EvaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
528      // The fixup was unresolved, we need a relocation. Inform the object
529      // writer of the relocation, and give it an opportunity to adjust the
530      // fixup value if need be.
531      getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
532    }
533    return FixedValue;
534  }
535
536 void MCAssembler::Finish() {
537   DEBUG_WITH_TYPE("mc-dump", {
538       llvm::errs() << "assembler backend - pre-layout\n--\n";
539       dump(); });
540
541   // Create the layout object.
542   MCAsmLayout Layout(*this);
543
544   // Create dummy fragments and assign section ordinals.
545   unsigned SectionIndex = 0;
546   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
547     // Create dummy fragments to eliminate any empty sections, this simplifies
548     // layout.
549     if (it->getFragmentList().empty())
550       new MCDataFragment(it);
551
552     it->setOrdinal(SectionIndex++);
553   }
554
555   // Assign layout order indices to sections and fragments.
556   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
557     MCSectionData *SD = Layout.getSectionOrder()[i];
558     SD->setLayoutOrder(i);
559
560     unsigned FragmentIndex = 0;
561     for (MCSectionData::iterator it2 = SD->begin(),
562            ie2 = SD->end(); it2 != ie2; ++it2)
563       it2->setLayoutOrder(FragmentIndex++);
564   }
565
566   // Layout until everything fits.
567   while (LayoutOnce(Layout))
568     continue;
569
570   DEBUG_WITH_TYPE("mc-dump", {
571       llvm::errs() << "assembler backend - post-relaxation\n--\n";
572       dump(); });
573
574   // Finalize the layout, including fragment lowering.
575   FinishLayout(Layout);
576
577   DEBUG_WITH_TYPE("mc-dump", {
578       llvm::errs() << "assembler backend - final-layout\n--\n";
579       dump(); });
580
581   uint64_t StartOffset = OS.tell();
582
583   // Allow the object writer a chance to perform post-layout binding (for
584   // example, to set the index fields in the symbol data).
585   getWriter().ExecutePostLayoutBinding(*this, Layout);
586
587   // Evaluate and apply the fixups, generating relocation entries as necessary.
588   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
589     for (MCSectionData::iterator it2 = it->begin(),
590            ie2 = it->end(); it2 != ie2; ++it2) {
591       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
592       if (DF) {
593         for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
594                ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
595           MCFixup &Fixup = *it3;
596           uint64_t FixedValue = HandleFixup(Layout, *DF, Fixup);
597           getBackend().ApplyFixup(Fixup, DF->getContents().data(),
598                                   DF->getContents().size(), FixedValue);
599         }
600       }
601       MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
602       if (IF) {
603         for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
604                ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
605           MCFixup &Fixup = *it3;
606           uint64_t FixedValue = HandleFixup(Layout, *IF, Fixup);
607           getBackend().ApplyFixup(Fixup, IF->getCode().data(),
608                                   IF->getCode().size(), FixedValue);
609         }
610       }
611     }
612   }
613
614   // Write the object file.
615   getWriter().WriteObject(*this, Layout);
616
617   stats::ObjectBytes += OS.tell() - StartOffset;
618 }
619
620 bool MCAssembler::FixupNeedsRelaxation(const MCFixup &Fixup,
621                                        const MCFragment *DF,
622                                        const MCAsmLayout &Layout) const {
623   if (getRelaxAll())
624     return true;
625
626   // If we cannot resolve the fixup value, it requires relaxation.
627   MCValue Target;
628   uint64_t Value;
629   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
630     return true;
631
632   // Otherwise, relax if the value is too big for a (signed) i8.
633   //
634   // FIXME: This is target dependent!
635   return int64_t(Value) != int64_t(int8_t(Value));
636 }
637
638 bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
639                                           const MCAsmLayout &Layout) const {
640   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
641   // are intentionally pushing out inst fragments, or because we relaxed a
642   // previous instruction to one that doesn't need relaxation.
643   if (!getBackend().MayNeedRelaxation(IF->getInst()))
644     return false;
645
646   for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
647          ie = IF->fixup_end(); it != ie; ++it)
648     if (FixupNeedsRelaxation(*it, IF, Layout))
649       return true;
650
651   return false;
652 }
653
654 bool MCAssembler::RelaxInstruction(MCAsmLayout &Layout,
655                                    MCInstFragment &IF) {
656   if (!FragmentNeedsRelaxation(&IF, Layout))
657     return false;
658
659   ++stats::RelaxedInstructions;
660
661   // FIXME-PERF: We could immediately lower out instructions if we can tell
662   // they are fully resolved, to avoid retesting on later passes.
663
664   // Relax the fragment.
665
666   MCInst Relaxed;
667   getBackend().RelaxInstruction(IF.getInst(), Relaxed);
668
669   // Encode the new instruction.
670   //
671   // FIXME-PERF: If it matters, we could let the target do this. It can
672   // probably do so more efficiently in many cases.
673   SmallVector<MCFixup, 4> Fixups;
674   SmallString<256> Code;
675   raw_svector_ostream VecOS(Code);
676   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
677   VecOS.flush();
678
679   // Update the instruction fragment.
680   IF.setInst(Relaxed);
681   IF.getCode() = Code;
682   IF.getFixups().clear();
683   // FIXME: Eliminate copy.
684   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
685     IF.getFixups().push_back(Fixups[i]);
686
687   return true;
688 }
689
690 bool MCAssembler::RelaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
691   int64_t Value = 0;
692   uint64_t OldSize = LF.getContents().size();
693   LF.getValue().EvaluateAsAbsolute(Value, Layout);
694   SmallString<8> &Data = LF.getContents();
695   Data.clear();
696   raw_svector_ostream OSE(Data);
697   if (LF.isSigned())
698     MCObjectWriter::EncodeSLEB128(Value, OSE);
699   else
700     MCObjectWriter::EncodeULEB128(Value, OSE);
701   OSE.flush();
702   return OldSize != LF.getContents().size();
703 }
704
705 bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout &Layout,
706                                      MCDwarfLineAddrFragment &DF) {
707   int64_t AddrDelta = 0;
708   uint64_t OldSize = DF.getContents().size();
709   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
710   (void)IsAbs;
711   assert(IsAbs);
712   int64_t LineDelta;
713   LineDelta = DF.getLineDelta();
714   SmallString<8> &Data = DF.getContents();
715   Data.clear();
716   raw_svector_ostream OSE(Data);
717   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
718   OSE.flush();
719   return OldSize != Data.size();
720 }
721
722 bool MCAssembler::RelaxDwarfCallFrameFragment(MCAsmLayout &Layout,
723                                               MCDwarfCallFrameFragment &DF) {
724   int64_t AddrDelta = 0;
725   uint64_t OldSize = DF.getContents().size();
726   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
727   (void)IsAbs;
728   assert(IsAbs);
729   SmallString<8> &Data = DF.getContents();
730   Data.clear();
731   raw_svector_ostream OSE(Data);
732   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
733   OSE.flush();
734   return OldSize != Data.size();
735 }
736
737 bool MCAssembler::LayoutSectionOnce(MCAsmLayout &Layout,
738                                     MCSectionData &SD) {
739   MCFragment *FirstInvalidFragment = NULL;
740   // Scan for fragments that need relaxation.
741   for (MCSectionData::iterator it2 = SD.begin(),
742          ie2 = SD.end(); it2 != ie2; ++it2) {
743     // Check if this is an fragment that needs relaxation.
744     bool relaxedFrag = false;
745     switch(it2->getKind()) {
746     default:
747           break;
748     case MCFragment::FT_Inst:
749       relaxedFrag = RelaxInstruction(Layout, *cast<MCInstFragment>(it2));
750       break;
751     case MCFragment::FT_Dwarf:
752       relaxedFrag = RelaxDwarfLineAddr(Layout,
753                                        *cast<MCDwarfLineAddrFragment>(it2));
754       break;
755     case MCFragment::FT_DwarfFrame:
756       relaxedFrag =
757         RelaxDwarfCallFrameFragment(Layout,
758                                     *cast<MCDwarfCallFrameFragment>(it2));
759       break;
760     case MCFragment::FT_LEB:
761       relaxedFrag = RelaxLEB(Layout, *cast<MCLEBFragment>(it2));
762       break;
763     }
764     // Update the layout, and remember that we relaxed.
765     if (relaxedFrag && !FirstInvalidFragment)
766       FirstInvalidFragment = it2;
767   }
768   if (FirstInvalidFragment) {
769     Layout.Invalidate(FirstInvalidFragment);
770     return true;
771   }
772   return false;
773 }
774
775 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
776   ++stats::RelaxationSteps;
777
778   bool WasRelaxed = false;
779   for (iterator it = begin(), ie = end(); it != ie; ++it) {
780     MCSectionData &SD = *it;
781     while(LayoutSectionOnce(Layout, SD))
782       WasRelaxed = true;
783   }
784
785   return WasRelaxed;
786 }
787
788 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
789   // The layout is done. Mark every fragment as valid.
790   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
791     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
792   }
793 }
794
795 // Debugging methods
796
797 namespace llvm {
798
799 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
800   OS << "<MCFixup" << " Offset:" << AF.getOffset()
801      << " Value:" << *AF.getValue()
802      << " Kind:" << AF.getKind() << ">";
803   return OS;
804 }
805
806 }
807
808 void MCFragment::dump() {
809   raw_ostream &OS = llvm::errs();
810
811   OS << "<";
812   switch (getKind()) {
813   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
814   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
815   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
816   case MCFragment::FT_Inst:  OS << "MCInstFragment"; break;
817   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
818   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
819   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
820   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
821   }
822
823   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
824      << " Offset:" << Offset << ">";
825
826   switch (getKind()) {
827   case MCFragment::FT_Align: {
828     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
829     if (AF->hasEmitNops())
830       OS << " (emit nops)";
831     OS << "\n       ";
832     OS << " Alignment:" << AF->getAlignment()
833        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
834        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
835     break;
836   }
837   case MCFragment::FT_Data:  {
838     const MCDataFragment *DF = cast<MCDataFragment>(this);
839     OS << "\n       ";
840     OS << " Contents:[";
841     const SmallVectorImpl<char> &Contents = DF->getContents();
842     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
843       if (i) OS << ",";
844       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
845     }
846     OS << "] (" << Contents.size() << " bytes)";
847
848     if (!DF->getFixups().empty()) {
849       OS << ",\n       ";
850       OS << " Fixups:[";
851       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
852              ie = DF->fixup_end(); it != ie; ++it) {
853         if (it != DF->fixup_begin()) OS << ",\n                ";
854         OS << *it;
855       }
856       OS << "]";
857     }
858     break;
859   }
860   case MCFragment::FT_Fill:  {
861     const MCFillFragment *FF = cast<MCFillFragment>(this);
862     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
863        << " Size:" << FF->getSize();
864     break;
865   }
866   case MCFragment::FT_Inst:  {
867     const MCInstFragment *IF = cast<MCInstFragment>(this);
868     OS << "\n       ";
869     OS << " Inst:";
870     IF->getInst().dump_pretty(OS);
871     break;
872   }
873   case MCFragment::FT_Org:  {
874     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
875     OS << "\n       ";
876     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
877     break;
878   }
879   case MCFragment::FT_Dwarf:  {
880     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
881     OS << "\n       ";
882     OS << " AddrDelta:" << OF->getAddrDelta()
883        << " LineDelta:" << OF->getLineDelta();
884     break;
885   }
886   case MCFragment::FT_DwarfFrame:  {
887     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
888     OS << "\n       ";
889     OS << " AddrDelta:" << CF->getAddrDelta();
890     break;
891   }
892   case MCFragment::FT_LEB: {
893     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
894     OS << "\n       ";
895     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
896     break;
897   }
898   }
899   OS << ">";
900 }
901
902 void MCSectionData::dump() {
903   raw_ostream &OS = llvm::errs();
904
905   OS << "<MCSectionData";
906   OS << " Alignment:" << getAlignment() << " Fragments:[\n      ";
907   for (iterator it = begin(), ie = end(); it != ie; ++it) {
908     if (it != begin()) OS << ",\n      ";
909     it->dump();
910   }
911   OS << "]>";
912 }
913
914 void MCSymbolData::dump() {
915   raw_ostream &OS = llvm::errs();
916
917   OS << "<MCSymbolData Symbol:" << getSymbol()
918      << " Fragment:" << getFragment() << " Offset:" << getOffset()
919      << " Flags:" << getFlags() << " Index:" << getIndex();
920   if (isCommon())
921     OS << " (common, size:" << getCommonSize()
922        << " align: " << getCommonAlignment() << ")";
923   if (isExternal())
924     OS << " (external)";
925   if (isPrivateExtern())
926     OS << " (private extern)";
927   OS << ">";
928 }
929
930 void MCAssembler::dump() {
931   raw_ostream &OS = llvm::errs();
932
933   OS << "<MCAssembler\n";
934   OS << "  Sections:[\n    ";
935   for (iterator it = begin(), ie = end(); it != ie; ++it) {
936     if (it != begin()) OS << ",\n    ";
937     it->dump();
938   }
939   OS << "],\n";
940   OS << "  Symbols:[";
941
942   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
943     if (it != symbol_begin()) OS << ",\n           ";
944     it->dump();
945   }
946   OS << "]>\n";
947 }