030ff9873969d62bf7596340ac274089466d475b
[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   }
327
328   assert(0 && "invalid fragment kind");
329   return 0;
330 }
331
332 void MCAsmLayout::LayoutFragment(MCFragment *F) {
333   MCFragment *Prev = F->getPrevNode();
334
335   // We should never try to recompute something which is up-to-date.
336   assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
337   // We should never try to compute the fragment layout if it's predecessor
338   // isn't up-to-date.
339   assert((!Prev || isFragmentUpToDate(Prev)) &&
340          "Attempt to compute fragment before it's predecessor!");
341
342   ++stats::FragmentLayouts;
343
344   // Compute fragment offset and size.
345   uint64_t Offset = 0;
346   if (Prev)
347     Offset += Prev->Offset + getAssembler().ComputeFragmentSize(*this, *Prev);
348
349   F->Offset = Offset;
350   LastValidFragment[F->getParent()] = F;
351 }
352
353 /// WriteFragmentData - Write the \arg F data to the output file.
354 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
355                               const MCFragment &F) {
356   MCObjectWriter *OW = &Asm.getWriter();
357   uint64_t Start = OW->getStream().tell();
358   (void) Start;
359
360   ++stats::EmittedFragments;
361
362   // FIXME: Embed in fragments instead?
363   uint64_t FragmentSize = Asm.ComputeFragmentSize(Layout, F);
364   switch (F.getKind()) {
365   case MCFragment::FT_Align: {
366     MCAlignFragment &AF = cast<MCAlignFragment>(F);
367     uint64_t Count = FragmentSize / AF.getValueSize();
368
369     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
370
371     // FIXME: This error shouldn't actually occur (the front end should emit
372     // multiple .align directives to enforce the semantics it wants), but is
373     // severe enough that we want to report it. How to handle this?
374     if (Count * AF.getValueSize() != FragmentSize)
375       report_fatal_error("undefined .align directive, value size '" +
376                         Twine(AF.getValueSize()) +
377                         "' is not a divisor of padding size '" +
378                         Twine(FragmentSize) + "'");
379
380     // See if we are aligning with nops, and if so do that first to try to fill
381     // the Count bytes.  Then if that did not fill any bytes or there are any
382     // bytes left to fill use the the Value and ValueSize to fill the rest.
383     // If we are aligning with nops, ask that target to emit the right data.
384     if (AF.hasEmitNops()) {
385       if (!Asm.getBackend().WriteNopData(Count, OW))
386         report_fatal_error("unable to write nop sequence of " +
387                           Twine(Count) + " bytes");
388       break;
389     }
390
391     // Otherwise, write out in multiples of the value size.
392     for (uint64_t i = 0; i != Count; ++i) {
393       switch (AF.getValueSize()) {
394       default:
395         assert(0 && "Invalid size!");
396       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
397       case 2: OW->Write16(uint16_t(AF.getValue())); break;
398       case 4: OW->Write32(uint32_t(AF.getValue())); break;
399       case 8: OW->Write64(uint64_t(AF.getValue())); break;
400       }
401     }
402     break;
403   }
404
405   case MCFragment::FT_Data: {
406     MCDataFragment &DF = cast<MCDataFragment>(F);
407     assert(FragmentSize == DF.getContents().size() && "Invalid size!");
408     OW->WriteBytes(DF.getContents().str());
409     break;
410   }
411
412   case MCFragment::FT_Fill: {
413     MCFillFragment &FF = cast<MCFillFragment>(F);
414
415     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
416
417     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
418       switch (FF.getValueSize()) {
419       default:
420         assert(0 && "Invalid size!");
421       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
422       case 2: OW->Write16(uint16_t(FF.getValue())); break;
423       case 4: OW->Write32(uint32_t(FF.getValue())); break;
424       case 8: OW->Write64(uint64_t(FF.getValue())); break;
425       }
426     }
427     break;
428   }
429
430   case MCFragment::FT_Inst: {
431     MCInstFragment &IF = cast<MCInstFragment>(F);
432     OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
433     break;
434   }
435
436   case MCFragment::FT_LEB: {
437     MCLEBFragment &LF = cast<MCLEBFragment>(F);
438     OW->WriteBytes(LF.getContents().str());
439     break;
440   }
441
442   case MCFragment::FT_Org: {
443     MCOrgFragment &OF = cast<MCOrgFragment>(F);
444
445     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
446       OW->Write8(uint8_t(OF.getValue()));
447
448     break;
449   }
450
451   case MCFragment::FT_Dwarf: {
452     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
453     OW->WriteBytes(OF.getContents().str());
454     break;
455   }
456   }
457
458   assert(OW->getStream().tell() - Start == FragmentSize);
459 }
460
461 void MCAssembler::WriteSectionData(const MCSectionData *SD,
462                                    const MCAsmLayout &Layout) const {
463   // Ignore virtual sections.
464   if (SD->getSection().isVirtualSection()) {
465     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
466
467     // Check that contents are only things legal inside a virtual section.
468     for (MCSectionData::const_iterator it = SD->begin(),
469            ie = SD->end(); it != ie; ++it) {
470       switch (it->getKind()) {
471       default:
472         assert(0 && "Invalid fragment in virtual section!");
473       case MCFragment::FT_Data: {
474         // Check that we aren't trying to write a non-zero contents (or fixups)
475         // into a virtual section. This is to support clients which use standard
476         // directives to fill the contents of virtual sections.
477         MCDataFragment &DF = cast<MCDataFragment>(*it);
478         assert(DF.fixup_begin() == DF.fixup_end() &&
479                "Cannot have fixups in virtual section!");
480         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
481           assert(DF.getContents()[i] == 0 &&
482                  "Invalid data value for virtual section!");
483         break;
484       }
485       case MCFragment::FT_Align:
486         // Check that we aren't trying to write a non-zero value into a virtual
487         // section.
488         assert((!cast<MCAlignFragment>(it)->getValueSize() ||
489                 !cast<MCAlignFragment>(it)->getValue()) &&
490                "Invalid align in virtual section!");
491         break;
492       case MCFragment::FT_Fill:
493         assert(!cast<MCFillFragment>(it)->getValueSize() &&
494                "Invalid fill in virtual section!");
495         break;
496       }
497     }
498
499     return;
500   }
501
502   uint64_t Start = getWriter().getStream().tell();
503   (void) Start;
504
505   for (MCSectionData::const_iterator it = SD->begin(),
506          ie = SD->end(); it != ie; ++it)
507     WriteFragmentData(*this, Layout, *it);
508
509   assert(getWriter().getStream().tell() - Start ==
510          Layout.getSectionAddressSize(SD));
511 }
512
513
514 uint64_t MCAssembler::HandleFixup(const MCAsmLayout &Layout,
515                                   MCFragment &F,
516                                   const MCFixup &Fixup) {
517    // Evaluate the fixup.
518    MCValue Target;
519    uint64_t FixedValue;
520    if (!EvaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
521      // The fixup was unresolved, we need a relocation. Inform the object
522      // writer of the relocation, and give it an opportunity to adjust the
523      // fixup value if need be.
524      getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
525    }
526    return FixedValue;
527  }
528
529 void MCAssembler::Finish() {
530   DEBUG_WITH_TYPE("mc-dump", {
531       llvm::errs() << "assembler backend - pre-layout\n--\n";
532       dump(); });
533
534   // Create the layout object.
535   MCAsmLayout Layout(*this);
536
537   // Create dummy fragments and assign section ordinals.
538   unsigned SectionIndex = 0;
539   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
540     // Create dummy fragments to eliminate any empty sections, this simplifies
541     // layout.
542     if (it->getFragmentList().empty())
543       new MCDataFragment(it);
544
545     it->setOrdinal(SectionIndex++);
546   }
547
548   // Assign layout order indices to sections and fragments.
549   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
550     MCSectionData *SD = Layout.getSectionOrder()[i];
551     SD->setLayoutOrder(i);
552
553     unsigned FragmentIndex = 0;
554     for (MCSectionData::iterator it2 = SD->begin(),
555            ie2 = SD->end(); it2 != ie2; ++it2)
556       it2->setLayoutOrder(FragmentIndex++);
557   }
558
559   // Layout until everything fits.
560   while (LayoutOnce(Layout))
561     continue;
562
563   DEBUG_WITH_TYPE("mc-dump", {
564       llvm::errs() << "assembler backend - post-relaxation\n--\n";
565       dump(); });
566
567   // Finalize the layout, including fragment lowering.
568   FinishLayout(Layout);
569
570   DEBUG_WITH_TYPE("mc-dump", {
571       llvm::errs() << "assembler backend - final-layout\n--\n";
572       dump(); });
573
574   uint64_t StartOffset = OS.tell();
575
576   // Allow the object writer a chance to perform post-layout binding (for
577   // example, to set the index fields in the symbol data).
578   getWriter().ExecutePostLayoutBinding(*this, Layout);
579
580   // Evaluate and apply the fixups, generating relocation entries as necessary.
581   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
582     for (MCSectionData::iterator it2 = it->begin(),
583            ie2 = it->end(); it2 != ie2; ++it2) {
584       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
585       if (DF) {
586         for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
587                ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
588           MCFixup &Fixup = *it3;
589           uint64_t FixedValue = HandleFixup(Layout, *DF, Fixup);
590           getBackend().ApplyFixup(Fixup, DF->getContents().data(),
591                                   DF->getContents().size(), FixedValue);
592         }
593       }
594       MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
595       if (IF) {
596         for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
597                ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
598           MCFixup &Fixup = *it3;
599           uint64_t FixedValue = HandleFixup(Layout, *IF, Fixup);
600           getBackend().ApplyFixup(Fixup, IF->getCode().data(),
601                                   IF->getCode().size(), FixedValue);
602         }
603       }
604     }
605   }
606
607   // Write the object file.
608   getWriter().WriteObject(*this, Layout);
609
610   stats::ObjectBytes += OS.tell() - StartOffset;
611 }
612
613 bool MCAssembler::FixupNeedsRelaxation(const MCFixup &Fixup,
614                                        const MCFragment *DF,
615                                        const MCAsmLayout &Layout) const {
616   if (getRelaxAll())
617     return true;
618
619   // If we cannot resolve the fixup value, it requires relaxation.
620   MCValue Target;
621   uint64_t Value;
622   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
623     return true;
624
625   // Otherwise, relax if the value is too big for a (signed) i8.
626   //
627   // FIXME: This is target dependent!
628   return int64_t(Value) != int64_t(int8_t(Value));
629 }
630
631 bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
632                                           const MCAsmLayout &Layout) const {
633   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
634   // are intentionally pushing out inst fragments, or because we relaxed a
635   // previous instruction to one that doesn't need relaxation.
636   if (!getBackend().MayNeedRelaxation(IF->getInst()))
637     return false;
638
639   for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
640          ie = IF->fixup_end(); it != ie; ++it)
641     if (FixupNeedsRelaxation(*it, IF, Layout))
642       return true;
643
644   return false;
645 }
646
647 bool MCAssembler::RelaxInstruction(MCAsmLayout &Layout,
648                                    MCInstFragment &IF) {
649   if (!FragmentNeedsRelaxation(&IF, Layout))
650     return false;
651
652   ++stats::RelaxedInstructions;
653
654   // FIXME-PERF: We could immediately lower out instructions if we can tell
655   // they are fully resolved, to avoid retesting on later passes.
656
657   // Relax the fragment.
658
659   MCInst Relaxed;
660   getBackend().RelaxInstruction(IF.getInst(), Relaxed);
661
662   // Encode the new instruction.
663   //
664   // FIXME-PERF: If it matters, we could let the target do this. It can
665   // probably do so more efficiently in many cases.
666   SmallVector<MCFixup, 4> Fixups;
667   SmallString<256> Code;
668   raw_svector_ostream VecOS(Code);
669   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
670   VecOS.flush();
671
672   // Update the instruction fragment.
673   IF.setInst(Relaxed);
674   IF.getCode() = Code;
675   IF.getFixups().clear();
676   // FIXME: Eliminate copy.
677   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
678     IF.getFixups().push_back(Fixups[i]);
679
680   return true;
681 }
682
683 bool MCAssembler::RelaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
684   int64_t Value = 0;
685   uint64_t OldSize = LF.getContents().size();
686   LF.getValue().EvaluateAsAbsolute(Value, Layout);
687   SmallString<8> &Data = LF.getContents();
688   Data.clear();
689   raw_svector_ostream OSE(Data);
690   if (LF.isSigned())
691     MCObjectWriter::EncodeSLEB128(Value, OSE);
692   else
693     MCObjectWriter::EncodeULEB128(Value, OSE);
694   OSE.flush();
695   return OldSize != LF.getContents().size();
696 }
697
698 bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout &Layout,
699                                      MCDwarfLineAddrFragment &DF) {
700   int64_t AddrDelta = 0;
701   uint64_t OldSize = DF.getContents().size();
702   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
703   (void)IsAbs;
704   assert(IsAbs);
705   int64_t LineDelta;
706   LineDelta = DF.getLineDelta();
707   SmallString<8> &Data = DF.getContents();
708   Data.clear();
709   raw_svector_ostream OSE(Data);
710   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
711   OSE.flush();
712   return OldSize != Data.size();
713 }
714
715 bool MCAssembler::LayoutSectionOnce(MCAsmLayout &Layout,
716                                     MCSectionData &SD) {
717   MCFragment *FirstInvalidFragment = NULL;
718   // Scan for fragments that need relaxation.
719   for (MCSectionData::iterator it2 = SD.begin(),
720          ie2 = SD.end(); it2 != ie2; ++it2) {
721     // Check if this is an fragment that needs relaxation.
722     bool relaxedFrag = false;
723     switch(it2->getKind()) {
724     default:
725           break;
726     case MCFragment::FT_Inst:
727       relaxedFrag = RelaxInstruction(Layout, *cast<MCInstFragment>(it2));
728       break;
729     case MCFragment::FT_Dwarf:
730       relaxedFrag = RelaxDwarfLineAddr(Layout,
731                                        *cast<MCDwarfLineAddrFragment>(it2));
732       break;
733         case MCFragment::FT_LEB:
734           relaxedFrag = RelaxLEB(Layout, *cast<MCLEBFragment>(it2));
735           break;
736     }
737     // Update the layout, and remember that we relaxed.
738     if (relaxedFrag && !FirstInvalidFragment)
739       FirstInvalidFragment = it2;
740   }
741   if (FirstInvalidFragment) {
742     Layout.Invalidate(FirstInvalidFragment);
743     return true;
744   }
745   return false;
746 }
747
748 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
749   ++stats::RelaxationSteps;
750
751   bool WasRelaxed = false;
752   for (iterator it = begin(), ie = end(); it != ie; ++it) {
753     MCSectionData &SD = *it;
754     while(LayoutSectionOnce(Layout, SD))
755       WasRelaxed = true;
756   }
757
758   return WasRelaxed;
759 }
760
761 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
762   // The layout is done. Mark every fragment as valid.
763   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
764     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
765   }
766 }
767
768 // Debugging methods
769
770 namespace llvm {
771
772 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
773   OS << "<MCFixup" << " Offset:" << AF.getOffset()
774      << " Value:" << *AF.getValue()
775      << " Kind:" << AF.getKind() << ">";
776   return OS;
777 }
778
779 }
780
781 void MCFragment::dump() {
782   raw_ostream &OS = llvm::errs();
783
784   OS << "<";
785   switch (getKind()) {
786   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
787   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
788   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
789   case MCFragment::FT_Inst:  OS << "MCInstFragment"; break;
790   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
791   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
792   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
793   }
794
795   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
796      << " Offset:" << Offset << ">";
797
798   switch (getKind()) {
799   case MCFragment::FT_Align: {
800     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
801     if (AF->hasEmitNops())
802       OS << " (emit nops)";
803     OS << "\n       ";
804     OS << " Alignment:" << AF->getAlignment()
805        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
806        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
807     break;
808   }
809   case MCFragment::FT_Data:  {
810     const MCDataFragment *DF = cast<MCDataFragment>(this);
811     OS << "\n       ";
812     OS << " Contents:[";
813     const SmallVectorImpl<char> &Contents = DF->getContents();
814     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
815       if (i) OS << ",";
816       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
817     }
818     OS << "] (" << Contents.size() << " bytes)";
819
820     if (!DF->getFixups().empty()) {
821       OS << ",\n       ";
822       OS << " Fixups:[";
823       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
824              ie = DF->fixup_end(); it != ie; ++it) {
825         if (it != DF->fixup_begin()) OS << ",\n                ";
826         OS << *it;
827       }
828       OS << "]";
829     }
830     break;
831   }
832   case MCFragment::FT_Fill:  {
833     const MCFillFragment *FF = cast<MCFillFragment>(this);
834     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
835        << " Size:" << FF->getSize();
836     break;
837   }
838   case MCFragment::FT_Inst:  {
839     const MCInstFragment *IF = cast<MCInstFragment>(this);
840     OS << "\n       ";
841     OS << " Inst:";
842     IF->getInst().dump_pretty(OS);
843     break;
844   }
845   case MCFragment::FT_Org:  {
846     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
847     OS << "\n       ";
848     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
849     break;
850   }
851   case MCFragment::FT_Dwarf:  {
852     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
853     OS << "\n       ";
854     OS << " AddrDelta:" << OF->getAddrDelta()
855        << " LineDelta:" << OF->getLineDelta();
856     break;
857   }
858   case MCFragment::FT_LEB: {
859     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
860     OS << "\n       ";
861     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
862     break;
863   }
864   }
865   OS << ">";
866 }
867
868 void MCSectionData::dump() {
869   raw_ostream &OS = llvm::errs();
870
871   OS << "<MCSectionData";
872   OS << " Alignment:" << getAlignment() << " Fragments:[\n      ";
873   for (iterator it = begin(), ie = end(); it != ie; ++it) {
874     if (it != begin()) OS << ",\n      ";
875     it->dump();
876   }
877   OS << "]>";
878 }
879
880 void MCSymbolData::dump() {
881   raw_ostream &OS = llvm::errs();
882
883   OS << "<MCSymbolData Symbol:" << getSymbol()
884      << " Fragment:" << getFragment() << " Offset:" << getOffset()
885      << " Flags:" << getFlags() << " Index:" << getIndex();
886   if (isCommon())
887     OS << " (common, size:" << getCommonSize()
888        << " align: " << getCommonAlignment() << ")";
889   if (isExternal())
890     OS << " (external)";
891   if (isPrivateExtern())
892     OS << " (private extern)";
893   OS << ">";
894 }
895
896 void MCAssembler::dump() {
897   raw_ostream &OS = llvm::errs();
898
899   OS << "<MCAssembler\n";
900   OS << "  Sections:[\n    ";
901   for (iterator it = begin(), ie = end(); it != ie; ++it) {
902     if (it != begin()) OS << ",\n    ";
903     it->dump();
904   }
905   OS << "],\n";
906   OS << "  Symbols:[";
907
908   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
909     if (it != symbol_begin()) OS << ",\n           ";
910     it->dump();
911   }
912   OS << "]>\n";
913 }