MC/Mach-O: Start emitting fixups/relocations for instructions.
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCExpr.h"
13 #include "llvm/MC/MCSectionMachO.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCValue.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MachO.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/Debug.h"
26
27 // FIXME: Gross.
28 #include "../Target/X86/X86FixupKinds.h"
29
30 #include <vector>
31 using namespace llvm;
32
33 class MachObjectWriter;
34
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36
37 // FIXME FIXME FIXME: There are number of places in this file where we convert
38 // what is a 64-bit assembler value used for computation into a value in the
39 // object file, which may truncate it. We should detect that truncation where
40 // invalid and report errors back.
41
42 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
43                           MachObjectWriter &MOW);
44
45 /// isVirtualSection - Check if this is a section which does not actually exist
46 /// in the object file.
47 static bool isVirtualSection(const MCSection &Section) {
48   // FIXME: Lame.
49   const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
50   unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
51   return (Type == MCSectionMachO::S_ZEROFILL);
52 }
53
54 static unsigned getFixupKindLog2Size(MCFixupKind Kind) {
55   switch (Kind) {
56   default: llvm_unreachable("invalid fixup kind!");
57   case X86::reloc_pcrel_1byte:
58   case FK_Data_1: return 0;
59   case FK_Data_2: return 1;
60   case X86::reloc_pcrel_4byte:
61   case X86::reloc_riprel_4byte:
62   case FK_Data_4: return 2;
63   case FK_Data_8: return 3;
64   }
65 }
66
67 class MachObjectWriter {
68   // See <mach-o/loader.h>.
69   enum {
70     Header_Magic32 = 0xFEEDFACE,
71     Header_Magic64 = 0xFEEDFACF
72   };
73
74   static const unsigned Header32Size = 28;
75   static const unsigned Header64Size = 32;
76   static const unsigned SegmentLoadCommand32Size = 56;
77   static const unsigned Section32Size = 68;
78   static const unsigned SymtabLoadCommandSize = 24;
79   static const unsigned DysymtabLoadCommandSize = 80;
80   static const unsigned Nlist32Size = 12;
81   static const unsigned RelocationInfoSize = 8;
82
83   enum HeaderFileType {
84     HFT_Object = 0x1
85   };
86
87   enum HeaderFlags {
88     HF_SubsectionsViaSymbols = 0x2000
89   };
90
91   enum LoadCommandType {
92     LCT_Segment = 0x1,
93     LCT_Symtab = 0x2,
94     LCT_Dysymtab = 0xb
95   };
96
97   // See <mach-o/nlist.h>.
98   enum SymbolTypeType {
99     STT_Undefined = 0x00,
100     STT_Absolute  = 0x02,
101     STT_Section   = 0x0e
102   };
103
104   enum SymbolTypeFlags {
105     // If any of these bits are set, then the entry is a stab entry number (see
106     // <mach-o/stab.h>. Otherwise the other masks apply.
107     STF_StabsEntryMask = 0xe0,
108
109     STF_TypeMask       = 0x0e,
110     STF_External       = 0x01,
111     STF_PrivateExtern  = 0x10
112   };
113
114   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
115   /// symbol entry.
116   enum IndirectSymbolFlags {
117     ISF_Local    = 0x80000000,
118     ISF_Absolute = 0x40000000
119   };
120
121   /// RelocationFlags - Special flags for addresses.
122   enum RelocationFlags {
123     RF_Scattered = 0x80000000
124   };
125
126   enum RelocationInfoType {
127     RIT_Vanilla             = 0,
128     RIT_Pair                = 1,
129     RIT_Difference          = 2,
130     RIT_PreboundLazyPointer = 3,
131     RIT_LocalDifference     = 4
132   };
133
134   /// MachSymbolData - Helper struct for containing some precomputed information
135   /// on symbols.
136   struct MachSymbolData {
137     MCSymbolData *SymbolData;
138     uint64_t StringIndex;
139     uint8_t SectionIndex;
140
141     // Support lexicographic sorting.
142     bool operator<(const MachSymbolData &RHS) const {
143       const std::string &Name = SymbolData->getSymbol().getName();
144       return Name < RHS.SymbolData->getSymbol().getName();
145     }
146   };
147
148   raw_ostream &OS;
149   bool IsLSB;
150
151 public:
152   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
153     : OS(_OS), IsLSB(_IsLSB) {
154   }
155
156   /// @name Helper Methods
157   /// @{
158
159   void Write8(uint8_t Value) {
160     OS << char(Value);
161   }
162
163   void Write16(uint16_t Value) {
164     if (IsLSB) {
165       Write8(uint8_t(Value >> 0));
166       Write8(uint8_t(Value >> 8));
167     } else {
168       Write8(uint8_t(Value >> 8));
169       Write8(uint8_t(Value >> 0));
170     }
171   }
172
173   void Write32(uint32_t Value) {
174     if (IsLSB) {
175       Write16(uint16_t(Value >> 0));
176       Write16(uint16_t(Value >> 16));
177     } else {
178       Write16(uint16_t(Value >> 16));
179       Write16(uint16_t(Value >> 0));
180     }
181   }
182
183   void Write64(uint64_t Value) {
184     if (IsLSB) {
185       Write32(uint32_t(Value >> 0));
186       Write32(uint32_t(Value >> 32));
187     } else {
188       Write32(uint32_t(Value >> 32));
189       Write32(uint32_t(Value >> 0));
190     }
191   }
192
193   void WriteZeros(unsigned N) {
194     const char Zeros[16] = { 0 };
195
196     for (unsigned i = 0, e = N / 16; i != e; ++i)
197       OS << StringRef(Zeros, 16);
198
199     OS << StringRef(Zeros, N % 16);
200   }
201
202   void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
203     OS << Str;
204     if (ZeroFillSize)
205       WriteZeros(ZeroFillSize - Str.size());
206   }
207
208   /// @}
209
210   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
211                      bool SubsectionsViaSymbols) {
212     uint32_t Flags = 0;
213
214     if (SubsectionsViaSymbols)
215       Flags |= HF_SubsectionsViaSymbols;
216
217     // struct mach_header (28 bytes)
218
219     uint64_t Start = OS.tell();
220     (void) Start;
221
222     Write32(Header_Magic32);
223
224     // FIXME: Support cputype.
225     Write32(MachO::CPUTypeI386);
226     // FIXME: Support cpusubtype.
227     Write32(MachO::CPUSubType_I386_ALL);
228     Write32(HFT_Object);
229     Write32(NumLoadCommands);    // Object files have a single load command, the
230                                  // segment.
231     Write32(LoadCommandsSize);
232     Write32(Flags);
233
234     assert(OS.tell() - Start == Header32Size);
235   }
236
237   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
238   ///
239   /// \arg NumSections - The number of sections in this segment.
240   /// \arg SectionDataSize - The total size of the sections.
241   void WriteSegmentLoadCommand32(unsigned NumSections,
242                                  uint64_t VMSize,
243                                  uint64_t SectionDataStartOffset,
244                                  uint64_t SectionDataSize) {
245     // struct segment_command (56 bytes)
246
247     uint64_t Start = OS.tell();
248     (void) Start;
249
250     Write32(LCT_Segment);
251     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
252
253     WriteString("", 16);
254     Write32(0); // vmaddr
255     Write32(VMSize); // vmsize
256     Write32(SectionDataStartOffset); // file offset
257     Write32(SectionDataSize); // file size
258     Write32(0x7); // maxprot
259     Write32(0x7); // initprot
260     Write32(NumSections);
261     Write32(0); // flags
262
263     assert(OS.tell() - Start == SegmentLoadCommand32Size);
264   }
265
266   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
267                       uint64_t RelocationsStart, unsigned NumRelocations) {
268     // The offset is unused for virtual sections.
269     if (isVirtualSection(SD.getSection())) {
270       assert(SD.getFileSize() == 0 && "Invalid file size!");
271       FileOffset = 0;
272     }
273
274     // struct section (68 bytes)
275
276     uint64_t Start = OS.tell();
277     (void) Start;
278
279     // FIXME: cast<> support!
280     const MCSectionMachO &Section =
281       static_cast<const MCSectionMachO&>(SD.getSection());
282     WriteString(Section.getSectionName(), 16);
283     WriteString(Section.getSegmentName(), 16);
284     Write32(SD.getAddress()); // address
285     Write32(SD.getSize()); // size
286     Write32(FileOffset);
287
288     unsigned Flags = Section.getTypeAndAttributes();
289     if (SD.hasInstructions())
290       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
291
292     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
293     Write32(Log2_32(SD.getAlignment()));
294     Write32(NumRelocations ? RelocationsStart : 0);
295     Write32(NumRelocations);
296     Write32(Flags);
297     Write32(0); // reserved1
298     Write32(Section.getStubSize()); // reserved2
299
300     assert(OS.tell() - Start == Section32Size);
301   }
302
303   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
304                               uint32_t StringTableOffset,
305                               uint32_t StringTableSize) {
306     // struct symtab_command (24 bytes)
307
308     uint64_t Start = OS.tell();
309     (void) Start;
310
311     Write32(LCT_Symtab);
312     Write32(SymtabLoadCommandSize);
313     Write32(SymbolOffset);
314     Write32(NumSymbols);
315     Write32(StringTableOffset);
316     Write32(StringTableSize);
317
318     assert(OS.tell() - Start == SymtabLoadCommandSize);
319   }
320
321   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
322                                 uint32_t NumLocalSymbols,
323                                 uint32_t FirstExternalSymbol,
324                                 uint32_t NumExternalSymbols,
325                                 uint32_t FirstUndefinedSymbol,
326                                 uint32_t NumUndefinedSymbols,
327                                 uint32_t IndirectSymbolOffset,
328                                 uint32_t NumIndirectSymbols) {
329     // struct dysymtab_command (80 bytes)
330
331     uint64_t Start = OS.tell();
332     (void) Start;
333
334     Write32(LCT_Dysymtab);
335     Write32(DysymtabLoadCommandSize);
336     Write32(FirstLocalSymbol);
337     Write32(NumLocalSymbols);
338     Write32(FirstExternalSymbol);
339     Write32(NumExternalSymbols);
340     Write32(FirstUndefinedSymbol);
341     Write32(NumUndefinedSymbols);
342     Write32(0); // tocoff
343     Write32(0); // ntoc
344     Write32(0); // modtaboff
345     Write32(0); // nmodtab
346     Write32(0); // extrefsymoff
347     Write32(0); // nextrefsyms
348     Write32(IndirectSymbolOffset);
349     Write32(NumIndirectSymbols);
350     Write32(0); // extreloff
351     Write32(0); // nextrel
352     Write32(0); // locreloff
353     Write32(0); // nlocrel
354
355     assert(OS.tell() - Start == DysymtabLoadCommandSize);
356   }
357
358   void WriteNlist32(MachSymbolData &MSD) {
359     MCSymbolData &Data = *MSD.SymbolData;
360     const MCSymbol &Symbol = Data.getSymbol();
361     uint8_t Type = 0;
362     uint16_t Flags = Data.getFlags();
363     uint32_t Address = 0;
364
365     // Set the N_TYPE bits. See <mach-o/nlist.h>.
366     //
367     // FIXME: Are the prebound or indirect fields possible here?
368     if (Symbol.isUndefined())
369       Type = STT_Undefined;
370     else if (Symbol.isAbsolute())
371       Type = STT_Absolute;
372     else
373       Type = STT_Section;
374
375     // FIXME: Set STAB bits.
376
377     if (Data.isPrivateExtern())
378       Type |= STF_PrivateExtern;
379
380     // Set external bit.
381     if (Data.isExternal() || Symbol.isUndefined())
382       Type |= STF_External;
383
384     // Compute the symbol address.
385     if (Symbol.isDefined()) {
386       if (Symbol.isAbsolute()) {
387         llvm_unreachable("FIXME: Not yet implemented!");
388       } else {
389         Address = Data.getFragment()->getAddress() + Data.getOffset();
390       }
391     } else if (Data.isCommon()) {
392       // Common symbols are encoded with the size in the address
393       // field, and their alignment in the flags.
394       Address = Data.getCommonSize();
395
396       // Common alignment is packed into the 'desc' bits.
397       if (unsigned Align = Data.getCommonAlignment()) {
398         unsigned Log2Size = Log2_32(Align);
399         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
400         if (Log2Size > 15)
401           llvm_report_error("invalid 'common' alignment '" +
402                             Twine(Align) + "'");
403         // FIXME: Keep this mask with the SymbolFlags enumeration.
404         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
405       }
406     }
407
408     // struct nlist (12 bytes)
409
410     Write32(MSD.StringIndex);
411     Write8(Type);
412     Write8(MSD.SectionIndex);
413
414     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
415     // value.
416     Write16(Flags);
417     Write32(Address);
418   }
419
420   struct MachRelocationEntry {
421     uint32_t Word0;
422     uint32_t Word1;
423   };
424   void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
425                                       MCAsmFixup &Fixup,
426                                       const MCValue &Target,
427                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
428                                      std::vector<MachRelocationEntry> &Relocs) {
429     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
430     unsigned IsPCRel = 0;
431     unsigned Type = RIT_Vanilla;
432
433     // See <reloc.h>.
434     const MCSymbol *A = Target.getSymA();
435     MCSymbolData *SD = SymbolMap.lookup(A);
436     uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
437     uint32_t Value2 = 0;
438
439     if (const MCSymbol *B = Target.getSymB()) {
440       Type = RIT_LocalDifference;
441
442       MCSymbolData *SD = SymbolMap.lookup(B);
443       Value2 = SD->getFragment()->getAddress() + SD->getOffset();
444     }
445
446     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
447
448     // The value which goes in the fixup is current value of the expression.
449     Fixup.FixedValue = Value - Value2 + Target.getConstant();
450
451     MachRelocationEntry MRE;
452     MRE.Word0 = ((Address   <<  0) |
453                  (Type      << 24) |
454                  (Log2Size  << 28) |
455                  (IsPCRel   << 30) |
456                  RF_Scattered);
457     MRE.Word1 = Value;
458     Relocs.push_back(MRE);
459
460     if (Type == RIT_LocalDifference) {
461       Type = RIT_Pair;
462
463       MachRelocationEntry MRE;
464       MRE.Word0 = ((0         <<  0) |
465                    (Type      << 24) |
466                    (Log2Size  << 28) |
467                    (0   << 30) |
468                    RF_Scattered);
469       MRE.Word1 = Value2;
470       Relocs.push_back(MRE);
471     }
472   }
473
474   void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
475                              MCAsmFixup &Fixup,
476                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
477                              std::vector<MachRelocationEntry> &Relocs) {
478     MCValue Target;
479     if (!Fixup.Value->EvaluateAsRelocatable(Target))
480       llvm_report_error("expected relocatable expression");
481
482     // If this is a difference or a local symbol plus an offset, then we need a
483     // scattered relocation entry.
484     if (Target.getSymB() ||
485         (Target.getSymA() && !Target.getSymA()->isUndefined() &&
486          Target.getConstant()))
487       return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
488                                             SymbolMap, Relocs);
489
490     // See <reloc.h>.
491     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
492     uint32_t Value = 0;
493     unsigned Index = 0;
494     unsigned IsPCRel = 0;
495     unsigned IsExtern = 0;
496     unsigned Type = 0;
497
498     if (Target.isAbsolute()) { // constant
499       // SymbolNum of 0 indicates the absolute section.
500       //
501       // FIXME: When is this generated?
502       Type = RIT_Vanilla;
503       Value = 0;
504       llvm_unreachable("FIXME: Not yet implemented!");
505     } else {
506       const MCSymbol *Symbol = Target.getSymA();
507       MCSymbolData *SD = SymbolMap.lookup(Symbol);
508
509       if (Symbol->isUndefined()) {
510         IsExtern = 1;
511         Index = SD->getIndex();
512         Value = 0;
513       } else {
514         // The index is the section ordinal.
515         //
516         // FIXME: O(N)
517         Index = 1;
518         for (MCAssembler::iterator it = Asm.begin(),
519                ie = Asm.end(); it != ie; ++it, ++Index)
520           if (&*it == SD->getFragment()->getParent())
521             break;
522         Value = SD->getFragment()->getAddress() + SD->getOffset();
523       }
524
525       Type = RIT_Vanilla;
526     }
527
528     // The value which goes in the fixup is current value of the expression.
529     Fixup.FixedValue = Value + Target.getConstant();
530
531     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
532
533     // struct relocation_info (8 bytes)
534     MachRelocationEntry MRE;
535     MRE.Word0 = Address;
536     MRE.Word1 = ((Index     <<  0) |
537                  (IsPCRel   << 24) |
538                  (Log2Size  << 25) |
539                  (IsExtern  << 27) |
540                  (Type      << 28));
541     Relocs.push_back(MRE);
542   }
543
544   void BindIndirectSymbols(MCAssembler &Asm,
545                            DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
546     // This is the point where 'as' creates actual symbols for indirect symbols
547     // (in the following two passes). It would be easier for us to do this
548     // sooner when we see the attribute, but that makes getting the order in the
549     // symbol table much more complicated than it is worth.
550     //
551     // FIXME: Revisit this when the dust settles.
552
553     // Bind non lazy symbol pointers first.
554     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
555            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
556       // FIXME: cast<> support!
557       const MCSectionMachO &Section =
558         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
559
560       unsigned Type =
561         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
562       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
563         continue;
564
565       MCSymbolData *&Entry = SymbolMap[it->Symbol];
566       if (!Entry)
567         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
568     }
569
570     // Then lazy symbol pointers and symbol stubs.
571     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
572            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
573       // FIXME: cast<> support!
574       const MCSectionMachO &Section =
575         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
576
577       unsigned Type =
578         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
579       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
580           Type != MCSectionMachO::S_SYMBOL_STUBS)
581         continue;
582
583       MCSymbolData *&Entry = SymbolMap[it->Symbol];
584       if (!Entry) {
585         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
586
587         // Set the symbol type to undefined lazy, but only on construction.
588         //
589         // FIXME: Do not hardcode.
590         Entry->setFlags(Entry->getFlags() | 0x0001);
591       }
592     }
593   }
594
595   /// ComputeSymbolTable - Compute the symbol table data
596   ///
597   /// \param StringTable [out] - The string table data.
598   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
599   /// string table.
600   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
601                           std::vector<MachSymbolData> &LocalSymbolData,
602                           std::vector<MachSymbolData> &ExternalSymbolData,
603                           std::vector<MachSymbolData> &UndefinedSymbolData) {
604     // Build section lookup table.
605     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
606     unsigned Index = 1;
607     for (MCAssembler::iterator it = Asm.begin(),
608            ie = Asm.end(); it != ie; ++it, ++Index)
609       SectionIndexMap[&it->getSection()] = Index;
610     assert(Index <= 256 && "Too many sections!");
611
612     // Index 0 is always the empty string.
613     StringMap<uint64_t> StringIndexMap;
614     StringTable += '\x00';
615
616     // Build the symbol arrays and the string table, but only for non-local
617     // symbols.
618     //
619     // The particular order that we collect the symbols and create the string
620     // table, then sort the symbols is chosen to match 'as'. Even though it
621     // doesn't matter for correctness, this is important for letting us diff .o
622     // files.
623     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
624            ie = Asm.symbol_end(); it != ie; ++it) {
625       const MCSymbol &Symbol = it->getSymbol();
626
627       // Ignore assembler temporaries.
628       if (it->getSymbol().isTemporary())
629         continue;
630
631       if (!it->isExternal() && !Symbol.isUndefined())
632         continue;
633
634       uint64_t &Entry = StringIndexMap[Symbol.getName()];
635       if (!Entry) {
636         Entry = StringTable.size();
637         StringTable += Symbol.getName();
638         StringTable += '\x00';
639       }
640
641       MachSymbolData MSD;
642       MSD.SymbolData = it;
643       MSD.StringIndex = Entry;
644
645       if (Symbol.isUndefined()) {
646         MSD.SectionIndex = 0;
647         UndefinedSymbolData.push_back(MSD);
648       } else if (Symbol.isAbsolute()) {
649         MSD.SectionIndex = 0;
650         ExternalSymbolData.push_back(MSD);
651       } else {
652         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
653         assert(MSD.SectionIndex && "Invalid section index!");
654         ExternalSymbolData.push_back(MSD);
655       }
656     }
657
658     // Now add the data for local symbols.
659     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
660            ie = Asm.symbol_end(); it != ie; ++it) {
661       const MCSymbol &Symbol = it->getSymbol();
662
663       // Ignore assembler temporaries.
664       if (it->getSymbol().isTemporary())
665         continue;
666
667       if (it->isExternal() || Symbol.isUndefined())
668         continue;
669
670       uint64_t &Entry = StringIndexMap[Symbol.getName()];
671       if (!Entry) {
672         Entry = StringTable.size();
673         StringTable += Symbol.getName();
674         StringTable += '\x00';
675       }
676
677       MachSymbolData MSD;
678       MSD.SymbolData = it;
679       MSD.StringIndex = Entry;
680
681       if (Symbol.isAbsolute()) {
682         MSD.SectionIndex = 0;
683         LocalSymbolData.push_back(MSD);
684       } else {
685         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
686         assert(MSD.SectionIndex && "Invalid section index!");
687         LocalSymbolData.push_back(MSD);
688       }
689     }
690
691     // External and undefined symbols are required to be in lexicographic order.
692     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
693     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
694
695     // Set the symbol indices.
696     Index = 0;
697     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
698       LocalSymbolData[i].SymbolData->setIndex(Index++);
699     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
700       ExternalSymbolData[i].SymbolData->setIndex(Index++);
701     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
702       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
703
704     // The string table is padded to a multiple of 4.
705     while (StringTable.size() % 4)
706       StringTable += '\x00';
707   }
708
709   void WriteObject(MCAssembler &Asm) {
710     unsigned NumSections = Asm.size();
711
712     // Compute the symbol -> symbol data map.
713     //
714     // FIXME: This should not be here.
715     DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
716     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
717            ie = Asm.symbol_end(); it != ie; ++it)
718       SymbolMap[&it->getSymbol()] = it;
719
720     // Create symbol data for any indirect symbols.
721     BindIndirectSymbols(Asm, SymbolMap);
722
723     // Compute symbol table information.
724     SmallString<256> StringTable;
725     std::vector<MachSymbolData> LocalSymbolData;
726     std::vector<MachSymbolData> ExternalSymbolData;
727     std::vector<MachSymbolData> UndefinedSymbolData;
728     unsigned NumSymbols = Asm.symbol_size();
729
730     // No symbol table command is written if there are no symbols.
731     if (NumSymbols)
732       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
733                          UndefinedSymbolData);
734
735     // The section data starts after the header, the segment load command (and
736     // section headers) and the symbol table.
737     unsigned NumLoadCommands = 1;
738     uint64_t LoadCommandsSize =
739       SegmentLoadCommand32Size + NumSections * Section32Size;
740
741     // Add the symbol table load command sizes, if used.
742     if (NumSymbols) {
743       NumLoadCommands += 2;
744       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
745     }
746
747     // Compute the total size of the section data, as well as its file size and
748     // vm size.
749     uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
750     uint64_t SectionDataSize = 0;
751     uint64_t SectionDataFileSize = 0;
752     uint64_t VMSize = 0;
753     for (MCAssembler::iterator it = Asm.begin(),
754            ie = Asm.end(); it != ie; ++it) {
755       MCSectionData &SD = *it;
756
757       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
758
759       if (isVirtualSection(SD.getSection()))
760         continue;
761
762       SectionDataSize = std::max(SectionDataSize,
763                                  SD.getAddress() + SD.getSize());
764       SectionDataFileSize = std::max(SectionDataFileSize,
765                                      SD.getAddress() + SD.getFileSize());
766     }
767
768     // The section data is padded to 4 bytes.
769     //
770     // FIXME: Is this machine dependent?
771     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
772     SectionDataFileSize += SectionDataPadding;
773
774     // Write the prolog, starting with the header and load command...
775     WriteHeader32(NumLoadCommands, LoadCommandsSize,
776                   Asm.getSubsectionsViaSymbols());
777     WriteSegmentLoadCommand32(NumSections, VMSize,
778                               SectionDataStart, SectionDataSize);
779
780     // ... and then the section headers.
781     //
782     // We also compute the section relocations while we do this. Note that
783     // computing relocation info will also update the fixup to have the correct
784     // value; this will overwrite the appropriate data in the fragment when it
785     // is written.
786     std::vector<MachRelocationEntry> RelocInfos;
787     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
788     for (MCAssembler::iterator it = Asm.begin(),
789            ie = Asm.end(); it != ie; ++it) {
790       MCSectionData &SD = *it;
791
792       // The assembler writes relocations in the reverse order they were seen.
793       //
794       // FIXME: It is probably more complicated than this.
795       unsigned NumRelocsStart = RelocInfos.size();
796       for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
797              ie2 = SD.rend(); it2 != ie2; ++it2)
798         if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
799           for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
800             ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
801                                   SymbolMap, RelocInfos);
802
803       unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
804       uint64_t SectionStart = SectionDataStart + SD.getAddress();
805       WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
806       RelocTableEnd += NumRelocs * RelocationInfoSize;
807     }
808
809     // Write the symbol table load command, if used.
810     if (NumSymbols) {
811       unsigned FirstLocalSymbol = 0;
812       unsigned NumLocalSymbols = LocalSymbolData.size();
813       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
814       unsigned NumExternalSymbols = ExternalSymbolData.size();
815       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
816       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
817       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
818       unsigned NumSymTabSymbols =
819         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
820       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
821       uint64_t IndirectSymbolOffset = 0;
822
823       // If used, the indirect symbols are written after the section data.
824       if (NumIndirectSymbols)
825         IndirectSymbolOffset = RelocTableEnd;
826
827       // The symbol table is written after the indirect symbol data.
828       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
829
830       // The string table is written after symbol table.
831       uint64_t StringTableOffset =
832         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
833       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
834                              StringTableOffset, StringTable.size());
835
836       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
837                                FirstExternalSymbol, NumExternalSymbols,
838                                FirstUndefinedSymbol, NumUndefinedSymbols,
839                                IndirectSymbolOffset, NumIndirectSymbols);
840     }
841
842     // Write the actual section data.
843     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
844       WriteFileData(OS, *it, *this);
845
846     // Write the extra padding.
847     WriteZeros(SectionDataPadding);
848
849     // Write the relocation entries.
850     for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
851       Write32(RelocInfos[i].Word0);
852       Write32(RelocInfos[i].Word1);
853     }
854
855     // Write the symbol table data, if used.
856     if (NumSymbols) {
857       // Write the indirect symbol entries.
858       for (MCAssembler::indirect_symbol_iterator
859              it = Asm.indirect_symbol_begin(),
860              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
861         // Indirect symbols in the non lazy symbol pointer section have some
862         // special handling.
863         const MCSectionMachO &Section =
864           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
865         unsigned Type =
866           Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
867         if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
868           // If this symbol is defined and internal, mark it as such.
869           if (it->Symbol->isDefined() &&
870               !SymbolMap.lookup(it->Symbol)->isExternal()) {
871             uint32_t Flags = ISF_Local;
872             if (it->Symbol->isAbsolute())
873               Flags |= ISF_Absolute;
874             Write32(Flags);
875             continue;
876           }
877         }
878
879         Write32(SymbolMap[it->Symbol]->getIndex());
880       }
881
882       // FIXME: Check that offsets match computed ones.
883
884       // Write the symbol table entries.
885       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
886         WriteNlist32(LocalSymbolData[i]);
887       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
888         WriteNlist32(ExternalSymbolData[i]);
889       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
890         WriteNlist32(UndefinedSymbolData[i]);
891
892       // Write the string table.
893       OS << StringTable.str();
894     }
895   }
896
897   void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
898     unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
899
900     // FIXME: Endianness assumption.
901     assert(Fixup.Offset + Size <= DF.getContents().size() &&
902            "Invalid fixup offset!");
903     for (unsigned i = 0; i != Size; ++i)
904       DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
905   }
906 };
907
908 /* *** */
909
910 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
911 }
912
913 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
914   : Kind(_Kind),
915     Parent(_Parent),
916     FileSize(~UINT64_C(0))
917 {
918   if (Parent)
919     Parent->getFragmentList().push_back(this);
920 }
921
922 MCFragment::~MCFragment() {
923 }
924
925 uint64_t MCFragment::getAddress() const {
926   assert(getParent() && "Missing Section!");
927   return getParent()->getAddress() + Offset;
928 }
929
930 /* *** */
931
932 MCSectionData::MCSectionData() : Section(0) {}
933
934 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
935   : Section(&_Section),
936     Alignment(1),
937     Address(~UINT64_C(0)),
938     Size(~UINT64_C(0)),
939     FileSize(~UINT64_C(0)),
940     HasInstructions(false)
941 {
942   if (A)
943     A->getSectionList().push_back(this);
944 }
945
946 /* *** */
947
948 MCSymbolData::MCSymbolData() : Symbol(0) {}
949
950 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
951                            uint64_t _Offset, MCAssembler *A)
952   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
953     IsExternal(false), IsPrivateExtern(false),
954     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
955 {
956   if (A)
957     A->getSymbolList().push_back(this);
958 }
959
960 /* *** */
961
962 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
963   : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
964 {
965 }
966
967 MCAssembler::~MCAssembler() {
968 }
969
970 void MCAssembler::LayoutSection(MCSectionData &SD) {
971   uint64_t Address = SD.getAddress();
972
973   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
974     MCFragment &F = *it;
975
976     F.setOffset(Address - SD.getAddress());
977
978     // Evaluate fragment size.
979     switch (F.getKind()) {
980     case MCFragment::FT_Align: {
981       MCAlignFragment &AF = cast<MCAlignFragment>(F);
982
983       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
984       if (Size > AF.getMaxBytesToEmit())
985         AF.setFileSize(0);
986       else
987         AF.setFileSize(Size);
988       break;
989     }
990
991     case MCFragment::FT_Data:
992     case MCFragment::FT_Fill:
993       F.setFileSize(F.getMaxFileSize());
994       break;
995
996     case MCFragment::FT_Org: {
997       MCOrgFragment &OF = cast<MCOrgFragment>(F);
998
999       MCValue Target;
1000       if (!OF.getOffset().EvaluateAsRelocatable(Target))
1001         llvm_report_error("expected relocatable expression");
1002
1003       if (!Target.isAbsolute())
1004         llvm_unreachable("FIXME: Not yet implemented!");
1005       uint64_t OrgOffset = Target.getConstant();
1006       uint64_t Offset = Address - SD.getAddress();
1007
1008       // FIXME: We need a way to communicate this error.
1009       if (OrgOffset < Offset)
1010         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1011                           "' (at offset '" + Twine(Offset) + "'");
1012
1013       F.setFileSize(OrgOffset - Offset);
1014       break;
1015     }
1016
1017     case MCFragment::FT_ZeroFill: {
1018       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1019
1020       // Align the fragment offset; it is safe to adjust the offset freely since
1021       // this is only in virtual sections.
1022       uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1023       F.setOffset(Aligned - SD.getAddress());
1024
1025       // FIXME: This is misnamed.
1026       F.setFileSize(ZFF.getSize());
1027       break;
1028     }
1029     }
1030
1031     Address += F.getFileSize();
1032   }
1033
1034   // Set the section sizes.
1035   SD.setSize(Address - SD.getAddress());
1036   if (isVirtualSection(SD.getSection()))
1037     SD.setFileSize(0);
1038   else
1039     SD.setFileSize(Address - SD.getAddress());
1040 }
1041
1042 /// WriteFileData - Write the \arg F data to the output file.
1043 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1044                           MachObjectWriter &MOW) {
1045   uint64_t Start = OS.tell();
1046   (void) Start;
1047
1048   ++EmittedFragments;
1049
1050   // FIXME: Embed in fragments instead?
1051   switch (F.getKind()) {
1052   case MCFragment::FT_Align: {
1053     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1054     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1055
1056     // FIXME: This error shouldn't actually occur (the front end should emit
1057     // multiple .align directives to enforce the semantics it wants), but is
1058     // severe enough that we want to report it. How to handle this?
1059     if (Count * AF.getValueSize() != AF.getFileSize())
1060       llvm_report_error("undefined .align directive, value size '" +
1061                         Twine(AF.getValueSize()) +
1062                         "' is not a divisor of padding size '" +
1063                         Twine(AF.getFileSize()) + "'");
1064
1065     for (uint64_t i = 0; i != Count; ++i) {
1066       switch (AF.getValueSize()) {
1067       default:
1068         assert(0 && "Invalid size!");
1069       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1070       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1071       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1072       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1073       }
1074     }
1075     break;
1076   }
1077
1078   case MCFragment::FT_Data: {
1079     MCDataFragment &DF = cast<MCDataFragment>(F);
1080
1081     // Apply the fixups.
1082     //
1083     // FIXME: Move elsewhere.
1084     for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1085            ie = DF.fixup_end(); it != ie; ++it)
1086       MOW.ApplyFixup(*it, DF);
1087
1088     OS << cast<MCDataFragment>(F).getContents().str();
1089     break;
1090   }
1091
1092   case MCFragment::FT_Fill: {
1093     MCFillFragment &FF = cast<MCFillFragment>(F);
1094     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1095       switch (FF.getValueSize()) {
1096       default:
1097         assert(0 && "Invalid size!");
1098       case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1099       case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1100       case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1101       case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1102       }
1103     }
1104     break;
1105   }
1106
1107   case MCFragment::FT_Org: {
1108     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1109
1110     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1111       MOW.Write8(uint8_t(OF.getValue()));
1112
1113     break;
1114   }
1115
1116   case MCFragment::FT_ZeroFill: {
1117     assert(0 && "Invalid zero fill fragment in concrete section!");
1118     break;
1119   }
1120   }
1121
1122   assert(OS.tell() - Start == F.getFileSize());
1123 }
1124
1125 /// WriteFileData - Write the \arg SD data to the output file.
1126 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1127                           MachObjectWriter &MOW) {
1128   // Ignore virtual sections.
1129   if (isVirtualSection(SD.getSection())) {
1130     assert(SD.getFileSize() == 0);
1131     return;
1132   }
1133
1134   uint64_t Start = OS.tell();
1135   (void) Start;
1136
1137   for (MCSectionData::const_iterator it = SD.begin(),
1138          ie = SD.end(); it != ie; ++it)
1139     WriteFileData(OS, *it, MOW);
1140
1141   // Add section padding.
1142   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1143   MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1144
1145   assert(OS.tell() - Start == SD.getFileSize());
1146 }
1147
1148 void MCAssembler::Finish() {
1149   DEBUG_WITH_TYPE("mc-dump", {
1150       llvm::errs() << "assembler backend - pre-layout\n--\n";
1151       dump(); });
1152
1153   // Layout the concrete sections and fragments.
1154   uint64_t Address = 0;
1155   MCSectionData *Prev = 0;
1156   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1157     MCSectionData &SD = *it;
1158
1159     // Skip virtual sections.
1160     if (isVirtualSection(SD.getSection()))
1161       continue;
1162
1163     // Align this section if necessary by adding padding bytes to the previous
1164     // section.
1165     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1166       assert(Prev && "Missing prev section!");
1167       Prev->setFileSize(Prev->getFileSize() + Pad);
1168       Address += Pad;
1169     }
1170
1171     // Layout the section fragments and its size.
1172     SD.setAddress(Address);
1173     LayoutSection(SD);
1174     Address += SD.getFileSize();
1175
1176     Prev = &SD;
1177   }
1178
1179   // Layout the virtual sections.
1180   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1181     MCSectionData &SD = *it;
1182
1183     if (!isVirtualSection(SD.getSection()))
1184       continue;
1185
1186     SD.setAddress(Address);
1187     LayoutSection(SD);
1188     Address += SD.getSize();
1189   }
1190
1191   DEBUG_WITH_TYPE("mc-dump", {
1192       llvm::errs() << "assembler backend - post-layout\n--\n";
1193       dump(); });
1194
1195   // Write the object file.
1196   MachObjectWriter MOW(OS);
1197   MOW.WriteObject(*this);
1198
1199   OS.flush();
1200 }
1201
1202
1203 // Debugging methods
1204
1205 namespace llvm {
1206
1207 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1208   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1209      << " Kind:" << AF.Kind << ">";
1210   return OS;
1211 }
1212
1213 }
1214
1215 void MCFragment::dump() {
1216   raw_ostream &OS = llvm::errs();
1217
1218   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1219      << " FileSize:" << FileSize;
1220
1221   OS << ">";
1222 }
1223
1224 void MCAlignFragment::dump() {
1225   raw_ostream &OS = llvm::errs();
1226
1227   OS << "<MCAlignFragment ";
1228   this->MCFragment::dump();
1229   OS << "\n       ";
1230   OS << " Alignment:" << getAlignment()
1231      << " Value:" << getValue() << " ValueSize:" << getValueSize()
1232      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1233 }
1234
1235 void MCDataFragment::dump() {
1236   raw_ostream &OS = llvm::errs();
1237
1238   OS << "<MCDataFragment ";
1239   this->MCFragment::dump();
1240   OS << "\n       ";
1241   OS << " Contents:[";
1242   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1243     if (i) OS << ",";
1244     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1245   }
1246   OS << "] (" << getContents().size() << " bytes)";
1247
1248   if (!getFixups().empty()) {
1249     OS << ",\n       ";
1250     OS << " Fixups:[";
1251     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1252       if (it != fixup_begin()) OS << ",\n            ";
1253       OS << *it;
1254     }
1255     OS << "]";
1256   }
1257
1258   OS << ">";
1259 }
1260
1261 void MCFillFragment::dump() {
1262   raw_ostream &OS = llvm::errs();
1263
1264   OS << "<MCFillFragment ";
1265   this->MCFragment::dump();
1266   OS << "\n       ";
1267   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1268      << " Count:" << getCount() << ">";
1269 }
1270
1271 void MCOrgFragment::dump() {
1272   raw_ostream &OS = llvm::errs();
1273
1274   OS << "<MCOrgFragment ";
1275   this->MCFragment::dump();
1276   OS << "\n       ";
1277   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1278 }
1279
1280 void MCZeroFillFragment::dump() {
1281   raw_ostream &OS = llvm::errs();
1282
1283   OS << "<MCZeroFillFragment ";
1284   this->MCFragment::dump();
1285   OS << "\n       ";
1286   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1287 }
1288
1289 void MCSectionData::dump() {
1290   raw_ostream &OS = llvm::errs();
1291
1292   OS << "<MCSectionData";
1293   OS << " Alignment:" << getAlignment() << " Address:" << Address
1294      << " Size:" << Size << " FileSize:" << FileSize
1295      << " Fragments:[";
1296   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1297     if (it != begin()) OS << ",\n      ";
1298     it->dump();
1299   }
1300   OS << "]>";
1301 }
1302
1303 void MCSymbolData::dump() {
1304   raw_ostream &OS = llvm::errs();
1305
1306   OS << "<MCSymbolData Symbol:" << getSymbol()
1307      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1308      << " Flags:" << getFlags() << " Index:" << getIndex();
1309   if (isCommon())
1310     OS << " (common, size:" << getCommonSize()
1311        << " align: " << getCommonAlignment() << ")";
1312   if (isExternal())
1313     OS << " (external)";
1314   if (isPrivateExtern())
1315     OS << " (private extern)";
1316   OS << ">";
1317 }
1318
1319 void MCAssembler::dump() {
1320   raw_ostream &OS = llvm::errs();
1321
1322   OS << "<MCAssembler\n";
1323   OS << "  Sections:[";
1324   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1325     if (it != begin()) OS << ",\n    ";
1326     it->dump();
1327   }
1328   OS << "],\n";
1329   OS << "  Symbols:[";
1330
1331   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1332     if (it != symbol_begin()) OS << ",\n    ";
1333     it->dump();
1334   }
1335   OS << "]>\n";
1336 }