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