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