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