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