Change CodeGen to use .loc directives. This produces a lot more readable output
[oota-llvm.git] / lib / MC / MachObjectWriter.cpp
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
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 #include "llvm/ADT/StringMap.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MachO.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 // FIXME: Gross.
25 #include "../Target/X86/X86FixupKinds.h"
26
27 #include <vector>
28 using namespace llvm;
29
30 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
31 static unsigned getFixupKindLog2Size(unsigned Kind) {
32   switch (Kind) {
33   default: llvm_unreachable("invalid fixup kind!");
34   case X86::reloc_pcrel_1byte:
35   case FK_Data_1: return 0;
36   case X86::reloc_pcrel_2byte:
37   case FK_Data_2: return 1;
38   case X86::reloc_pcrel_4byte:
39   case X86::reloc_riprel_4byte:
40   case X86::reloc_riprel_4byte_movq_load:
41   case X86::reloc_signed_4byte:
42   case FK_Data_4: return 2;
43   case FK_Data_8: return 3;
44   }
45 }
46
47 static bool isFixupKindPCRel(unsigned Kind) {
48   switch (Kind) {
49   default:
50     return false;
51   case X86::reloc_pcrel_1byte:
52   case X86::reloc_pcrel_2byte:
53   case X86::reloc_pcrel_4byte:
54   case X86::reloc_riprel_4byte:
55   case X86::reloc_riprel_4byte_movq_load:
56     return true;
57   }
58 }
59
60 static bool isFixupKindRIPRel(unsigned Kind) {
61   return Kind == X86::reloc_riprel_4byte ||
62     Kind == X86::reloc_riprel_4byte_movq_load;
63 }
64
65 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
66   // Undefined symbols are always extern.
67   if (SD->Symbol->isUndefined())
68     return true;
69
70   // References to weak definitions require external relocation entries; the
71   // definition may not always be the one in the same object file.
72   if (SD->getFlags() & SF_WeakDefinition)
73     return true;
74
75   // Otherwise, we can use an internal relocation.
76   return false;
77 }
78
79 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
80                                           const MCValue Target,
81                                           const MCSymbolData *BaseSymbol) {
82   // The effective fixup address is
83   //     addr(atom(A)) + offset(A)
84   //   - addr(atom(B)) - offset(B)
85   //   - addr(BaseSymbol) + <fixup offset from base symbol>
86   // and the offsets are not relocatable, so the fixup is fully resolved when
87   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
88   //
89   // Note that "false" is almost always conservatively correct (it means we emit
90   // a relocation which is unnecessary), except when it would force us to emit a
91   // relocation which the target cannot encode.
92
93   const MCSymbolData *A_Base = 0, *B_Base = 0;
94   if (const MCSymbolRefExpr *A = Target.getSymA()) {
95     // Modified symbol references cannot be resolved.
96     if (A->getKind() != MCSymbolRefExpr::VK_None)
97       return false;
98
99     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
100     if (!A_Base)
101       return false;
102   }
103
104   if (const MCSymbolRefExpr *B = Target.getSymB()) {
105     // Modified symbol references cannot be resolved.
106     if (B->getKind() != MCSymbolRefExpr::VK_None)
107       return false;
108
109     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
110     if (!B_Base)
111       return false;
112   }
113
114   // If there is no base, A and B have to be the same atom for this fixup to be
115   // fully resolved.
116   if (!BaseSymbol)
117     return A_Base == B_Base;
118
119   // Otherwise, B must be missing and A must be the base.
120   return !B_Base && BaseSymbol == A_Base;
121 }
122
123 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
124                                                 const MCValue Target,
125                                                 const MCSection *BaseSection) {
126   // The effective fixup address is
127   //     addr(atom(A)) + offset(A)
128   //   - addr(atom(B)) - offset(B)
129   //   - addr(<base symbol>) + <fixup offset from base symbol>
130   // and the offsets are not relocatable, so the fixup is fully resolved when
131   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
132   //
133   // The simple (Darwin, except on x86_64) way of dealing with this was to
134   // assume that any reference to a temporary symbol *must* be a temporary
135   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
136   // relocation to a temporary symbol (in the same section) is fully
137   // resolved. This also works in conjunction with absolutized .set, which
138   // requires the compiler to use .set to absolutize the differences between
139   // symbols which the compiler knows to be assembly time constants, so we don't
140   // need to worry about considering symbol differences fully resolved.
141
142   // Non-relative fixups are only resolved if constant.
143   if (!BaseSection)
144     return Target.isAbsolute();
145
146   // Otherwise, relative fixups are only resolved if not a difference and the
147   // target is a temporary in the same section.
148   if (Target.isAbsolute() || Target.getSymB())
149     return false;
150
151   const MCSymbol *A = &Target.getSymA()->getSymbol();
152   if (!A->isTemporary() || !A->isInSection() ||
153       &A->getSection() != BaseSection)
154     return false;
155
156   return true;
157 }
158
159 namespace {
160
161 class MachObjectWriter : public MCObjectWriter {
162   // See <mach-o/loader.h>.
163   enum {
164     Header_Magic32 = 0xFEEDFACE,
165     Header_Magic64 = 0xFEEDFACF
166   };
167
168   enum {
169     Header32Size = 28,
170     Header64Size = 32,
171     SegmentLoadCommand32Size = 56,
172     SegmentLoadCommand64Size = 72,
173     Section32Size = 68,
174     Section64Size = 80,
175     SymtabLoadCommandSize = 24,
176     DysymtabLoadCommandSize = 80,
177     Nlist32Size = 12,
178     Nlist64Size = 16,
179     RelocationInfoSize = 8
180   };
181
182   enum HeaderFileType {
183     HFT_Object = 0x1
184   };
185
186   enum HeaderFlags {
187     HF_SubsectionsViaSymbols = 0x2000
188   };
189
190   enum LoadCommandType {
191     LCT_Segment = 0x1,
192     LCT_Symtab = 0x2,
193     LCT_Dysymtab = 0xb,
194     LCT_Segment64 = 0x19
195   };
196
197   // See <mach-o/nlist.h>.
198   enum SymbolTypeType {
199     STT_Undefined = 0x00,
200     STT_Absolute  = 0x02,
201     STT_Section   = 0x0e
202   };
203
204   enum SymbolTypeFlags {
205     // If any of these bits are set, then the entry is a stab entry number (see
206     // <mach-o/stab.h>. Otherwise the other masks apply.
207     STF_StabsEntryMask = 0xe0,
208
209     STF_TypeMask       = 0x0e,
210     STF_External       = 0x01,
211     STF_PrivateExtern  = 0x10
212   };
213
214   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
215   /// symbol entry.
216   enum IndirectSymbolFlags {
217     ISF_Local    = 0x80000000,
218     ISF_Absolute = 0x40000000
219   };
220
221   /// RelocationFlags - Special flags for addresses.
222   enum RelocationFlags {
223     RF_Scattered = 0x80000000
224   };
225
226   enum RelocationInfoType {
227     RIT_Vanilla             = 0,
228     RIT_Pair                = 1,
229     RIT_Difference          = 2,
230     RIT_PreboundLazyPointer = 3,
231     RIT_LocalDifference     = 4,
232     RIT_TLV                 = 5
233   };
234
235   /// X86_64 uses its own relocation types.
236   enum RelocationInfoTypeX86_64 {
237     RIT_X86_64_Unsigned   = 0,
238     RIT_X86_64_Signed     = 1,
239     RIT_X86_64_Branch     = 2,
240     RIT_X86_64_GOTLoad    = 3,
241     RIT_X86_64_GOT        = 4,
242     RIT_X86_64_Subtractor = 5,
243     RIT_X86_64_Signed1    = 6,
244     RIT_X86_64_Signed2    = 7,
245     RIT_X86_64_Signed4    = 8,
246     RIT_X86_64_TLV        = 9
247   };
248
249   /// MachSymbolData - Helper struct for containing some precomputed information
250   /// on symbols.
251   struct MachSymbolData {
252     MCSymbolData *SymbolData;
253     uint64_t StringIndex;
254     uint8_t SectionIndex;
255
256     // Support lexicographic sorting.
257     bool operator<(const MachSymbolData &RHS) const {
258       return SymbolData->getSymbol().getName() <
259              RHS.SymbolData->getSymbol().getName();
260     }
261   };
262
263   /// @name Relocation Data
264   /// @{
265
266   struct MachRelocationEntry {
267     uint32_t Word0;
268     uint32_t Word1;
269   };
270
271   llvm::DenseMap<const MCSectionData*,
272                  std::vector<MachRelocationEntry> > Relocations;
273   llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
274
275   /// @}
276   /// @name Symbol Table Data
277   /// @{
278
279   SmallString<256> StringTable;
280   std::vector<MachSymbolData> LocalSymbolData;
281   std::vector<MachSymbolData> ExternalSymbolData;
282   std::vector<MachSymbolData> UndefinedSymbolData;
283
284   /// @}
285
286   unsigned Is64Bit : 1;
287
288   uint32_t CPUType;
289   uint32_t CPUSubtype;
290
291 public:
292   MachObjectWriter(raw_ostream &_OS,
293                    bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
294                    bool _IsLittleEndian)
295     : MCObjectWriter(_OS, _IsLittleEndian),
296       Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
297   }
298
299   void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
300                    bool SubsectionsViaSymbols) {
301     uint32_t Flags = 0;
302
303     if (SubsectionsViaSymbols)
304       Flags |= HF_SubsectionsViaSymbols;
305
306     // struct mach_header (28 bytes) or
307     // struct mach_header_64 (32 bytes)
308
309     uint64_t Start = OS.tell();
310     (void) Start;
311
312     Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
313
314     Write32(CPUType);
315     Write32(CPUSubtype);
316
317     Write32(HFT_Object);
318     Write32(NumLoadCommands);    // Object files have a single load command, the
319                                  // segment.
320     Write32(LoadCommandsSize);
321     Write32(Flags);
322     if (Is64Bit)
323       Write32(0); // reserved
324
325     assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
326   }
327
328   /// WriteSegmentLoadCommand - Write a segment load command.
329   ///
330   /// \arg NumSections - The number of sections in this segment.
331   /// \arg SectionDataSize - The total size of the sections.
332   void WriteSegmentLoadCommand(unsigned NumSections,
333                                uint64_t VMSize,
334                                uint64_t SectionDataStartOffset,
335                                uint64_t SectionDataSize) {
336     // struct segment_command (56 bytes) or
337     // struct segment_command_64 (72 bytes)
338
339     uint64_t Start = OS.tell();
340     (void) Start;
341
342     unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
343       SegmentLoadCommand32Size;
344     Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
345     Write32(SegmentLoadCommandSize +
346             NumSections * (Is64Bit ? Section64Size : Section32Size));
347
348     WriteBytes("", 16);
349     if (Is64Bit) {
350       Write64(0); // vmaddr
351       Write64(VMSize); // vmsize
352       Write64(SectionDataStartOffset); // file offset
353       Write64(SectionDataSize); // file size
354     } else {
355       Write32(0); // vmaddr
356       Write32(VMSize); // vmsize
357       Write32(SectionDataStartOffset); // file offset
358       Write32(SectionDataSize); // file size
359     }
360     Write32(0x7); // maxprot
361     Write32(0x7); // initprot
362     Write32(NumSections);
363     Write32(0); // flags
364
365     assert(OS.tell() - Start == SegmentLoadCommandSize);
366   }
367
368   void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
369                     const MCSectionData &SD, uint64_t FileOffset,
370                     uint64_t RelocationsStart, unsigned NumRelocations) {
371     uint64_t SectionSize = Layout.getSectionSize(&SD);
372
373     // The offset is unused for virtual sections.
374     if (SD.getSection().isVirtualSection()) {
375       assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
376       FileOffset = 0;
377     }
378
379     // struct section (68 bytes) or
380     // struct section_64 (80 bytes)
381
382     uint64_t Start = OS.tell();
383     (void) Start;
384
385     const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
386     WriteBytes(Section.getSectionName(), 16);
387     WriteBytes(Section.getSegmentName(), 16);
388     if (Is64Bit) {
389       Write64(Layout.getSectionAddress(&SD)); // address
390       Write64(SectionSize); // size
391     } else {
392       Write32(Layout.getSectionAddress(&SD)); // address
393       Write32(SectionSize); // size
394     }
395     Write32(FileOffset);
396
397     unsigned Flags = Section.getTypeAndAttributes();
398     if (SD.hasInstructions())
399       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
400
401     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
402     Write32(Log2_32(SD.getAlignment()));
403     Write32(NumRelocations ? RelocationsStart : 0);
404     Write32(NumRelocations);
405     Write32(Flags);
406     Write32(IndirectSymBase.lookup(&SD)); // reserved1
407     Write32(Section.getStubSize()); // reserved2
408     if (Is64Bit)
409       Write32(0); // reserved3
410
411     assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
412   }
413
414   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
415                               uint32_t StringTableOffset,
416                               uint32_t StringTableSize) {
417     // struct symtab_command (24 bytes)
418
419     uint64_t Start = OS.tell();
420     (void) Start;
421
422     Write32(LCT_Symtab);
423     Write32(SymtabLoadCommandSize);
424     Write32(SymbolOffset);
425     Write32(NumSymbols);
426     Write32(StringTableOffset);
427     Write32(StringTableSize);
428
429     assert(OS.tell() - Start == SymtabLoadCommandSize);
430   }
431
432   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
433                                 uint32_t NumLocalSymbols,
434                                 uint32_t FirstExternalSymbol,
435                                 uint32_t NumExternalSymbols,
436                                 uint32_t FirstUndefinedSymbol,
437                                 uint32_t NumUndefinedSymbols,
438                                 uint32_t IndirectSymbolOffset,
439                                 uint32_t NumIndirectSymbols) {
440     // struct dysymtab_command (80 bytes)
441
442     uint64_t Start = OS.tell();
443     (void) Start;
444
445     Write32(LCT_Dysymtab);
446     Write32(DysymtabLoadCommandSize);
447     Write32(FirstLocalSymbol);
448     Write32(NumLocalSymbols);
449     Write32(FirstExternalSymbol);
450     Write32(NumExternalSymbols);
451     Write32(FirstUndefinedSymbol);
452     Write32(NumUndefinedSymbols);
453     Write32(0); // tocoff
454     Write32(0); // ntoc
455     Write32(0); // modtaboff
456     Write32(0); // nmodtab
457     Write32(0); // extrefsymoff
458     Write32(0); // nextrefsyms
459     Write32(IndirectSymbolOffset);
460     Write32(NumIndirectSymbols);
461     Write32(0); // extreloff
462     Write32(0); // nextrel
463     Write32(0); // locreloff
464     Write32(0); // nlocrel
465
466     assert(OS.tell() - Start == DysymtabLoadCommandSize);
467   }
468
469   void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
470     MCSymbolData &Data = *MSD.SymbolData;
471     const MCSymbol &Symbol = Data.getSymbol();
472     uint8_t Type = 0;
473     uint16_t Flags = Data.getFlags();
474     uint32_t Address = 0;
475
476     // Set the N_TYPE bits. See <mach-o/nlist.h>.
477     //
478     // FIXME: Are the prebound or indirect fields possible here?
479     if (Symbol.isUndefined())
480       Type = STT_Undefined;
481     else if (Symbol.isAbsolute())
482       Type = STT_Absolute;
483     else
484       Type = STT_Section;
485
486     // FIXME: Set STAB bits.
487
488     if (Data.isPrivateExtern())
489       Type |= STF_PrivateExtern;
490
491     // Set external bit.
492     if (Data.isExternal() || Symbol.isUndefined())
493       Type |= STF_External;
494
495     // Compute the symbol address.
496     if (Symbol.isDefined()) {
497       if (Symbol.isAbsolute()) {
498         Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
499       } else {
500         Address = Layout.getSymbolAddress(&Data);
501       }
502     } else if (Data.isCommon()) {
503       // Common symbols are encoded with the size in the address
504       // field, and their alignment in the flags.
505       Address = Data.getCommonSize();
506
507       // Common alignment is packed into the 'desc' bits.
508       if (unsigned Align = Data.getCommonAlignment()) {
509         unsigned Log2Size = Log2_32(Align);
510         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
511         if (Log2Size > 15)
512           report_fatal_error("invalid 'common' alignment '" +
513                             Twine(Align) + "'");
514         // FIXME: Keep this mask with the SymbolFlags enumeration.
515         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
516       }
517     }
518
519     // struct nlist (12 bytes)
520
521     Write32(MSD.StringIndex);
522     Write8(Type);
523     Write8(MSD.SectionIndex);
524
525     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
526     // value.
527     Write16(Flags);
528     if (Is64Bit)
529       Write64(Address);
530     else
531       Write32(Address);
532   }
533
534   // FIXME: We really need to improve the relocation validation. Basically, we
535   // want to implement a separate computation which evaluates the relocation
536   // entry as the linker would, and verifies that the resultant fixup value is
537   // exactly what the encoder wanted. This will catch several classes of
538   // problems:
539   //
540   //  - Relocation entry bugs, the two algorithms are unlikely to have the same
541   //    exact bug.
542   //
543   //  - Relaxation issues, where we forget to relax something.
544   //
545   //  - Input errors, where something cannot be correctly encoded. 'as' allows
546   //    these through in many cases.
547
548   void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
549                               const MCFragment *Fragment,
550                               const MCFixup &Fixup, MCValue Target,
551                               uint64_t &FixedValue) {
552     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
553     unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
554     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
555
556     // See <reloc.h>.
557     uint32_t FixupOffset =
558       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
559     uint32_t FixupAddress =
560       Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
561     int64_t Value = 0;
562     unsigned Index = 0;
563     unsigned IsExtern = 0;
564     unsigned Type = 0;
565
566     Value = Target.getConstant();
567
568     if (IsPCRel) {
569       // Compensate for the relocation offset, Darwin x86_64 relocations only
570       // have the addend and appear to have attempted to define it to be the
571       // actual expression addend without the PCrel bias. However, instructions
572       // with data following the relocation are not accomodated for (see comment
573       // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
574       Value += 1LL << Log2Size;
575     }
576
577     if (Target.isAbsolute()) { // constant
578       // SymbolNum of 0 indicates the absolute section.
579       Type = RIT_X86_64_Unsigned;
580       Index = 0;
581
582       // FIXME: I believe this is broken, I don't think the linker can
583       // understand it. I think it would require a local relocation, but I'm not
584       // sure if that would work either. The official way to get an absolute
585       // PCrel relocation is to use an absolute symbol (which we don't support
586       // yet).
587       if (IsPCRel) {
588         IsExtern = 1;
589         Type = RIT_X86_64_Branch;
590       }
591     } else if (Target.getSymB()) { // A - B + constant
592       const MCSymbol *A = &Target.getSymA()->getSymbol();
593       MCSymbolData &A_SD = Asm.getSymbolData(*A);
594       const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
595
596       const MCSymbol *B = &Target.getSymB()->getSymbol();
597       MCSymbolData &B_SD = Asm.getSymbolData(*B);
598       const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
599
600       // Neither symbol can be modified.
601       if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
602           Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
603         report_fatal_error("unsupported relocation of modified symbol");
604
605       // We don't support PCrel relocations of differences. Darwin 'as' doesn't
606       // implement most of these correctly.
607       if (IsPCRel)
608         report_fatal_error("unsupported pc-relative relocation of difference");
609
610       // The support for the situation where one or both of the symbols would
611       // require a local relocation is handled just like if the symbols were
612       // external.  This is certainly used in the case of debug sections where
613       // the section has only temporary symbols and thus the symbols don't have
614       // base symbols.  This is encoded using the section ordinal and
615       // non-extern relocation entries.
616
617       // Darwin 'as' doesn't emit correct relocations for this (it ends up with
618       // a single SIGNED relocation); reject it for now.  Except the case where
619       // both symbols don't have a base, equal but both NULL.
620       if (A_Base == B_Base && A_Base)
621         report_fatal_error("unsupported relocation with identical base");
622
623       Value += Layout.getSymbolAddress(&A_SD) -
624                (A_Base == NULL ? 0 : Layout.getSymbolAddress(A_Base));
625       Value -= Layout.getSymbolAddress(&B_SD) -
626                (B_Base == NULL ? 0 : Layout.getSymbolAddress(B_Base));
627
628       if (A_Base) {
629         Index = A_Base->getIndex();
630         IsExtern = 1;
631       }
632       else {
633         Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
634         IsExtern = 0;
635       }
636       Type = RIT_X86_64_Unsigned;
637
638       MachRelocationEntry MRE;
639       MRE.Word0 = FixupOffset;
640       MRE.Word1 = ((Index     <<  0) |
641                    (IsPCRel   << 24) |
642                    (Log2Size  << 25) |
643                    (IsExtern  << 27) |
644                    (Type      << 28));
645       Relocations[Fragment->getParent()].push_back(MRE);
646
647       if (B_Base) {
648         Index = B_Base->getIndex();
649         IsExtern = 1;
650       }
651       else {
652         Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
653         IsExtern = 0;
654       }
655       Type = RIT_X86_64_Subtractor;
656     } else {
657       const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
658       MCSymbolData &SD = Asm.getSymbolData(*Symbol);
659       const MCSymbolData *Base = Asm.getAtom(&SD);
660
661       // Relocations inside debug sections always use local relocations when
662       // possible. This seems to be done because the debugger doesn't fully
663       // understand x86_64 relocation entries, and expects to find values that
664       // have already been fixed up.
665       if (Symbol->isInSection()) {
666         const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
667           Fragment->getParent()->getSection());
668         if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
669           Base = 0;
670       }
671
672       // x86_64 almost always uses external relocations, except when there is no
673       // symbol to use as a base address (a local symbol with no preceeding
674       // non-local symbol).
675       if (Base) {
676         Index = Base->getIndex();
677         IsExtern = 1;
678
679         // Add the local offset, if needed.
680         if (Base != &SD)
681           Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
682       } else if (Symbol->isInSection()) {
683         // The index is the section ordinal (1-based).
684         Index = SD.getFragment()->getParent()->getOrdinal() + 1;
685         IsExtern = 0;
686         Value += Layout.getSymbolAddress(&SD);
687
688         if (IsPCRel)
689           Value -= FixupAddress + (1 << Log2Size);
690       } else {
691         report_fatal_error("unsupported relocation of undefined symbol '" +
692                            Symbol->getName() + "'");
693       }
694
695       MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
696       if (IsPCRel) {
697         if (IsRIPRel) {
698           if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
699             // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
700             // rewrite the movq to an leaq at link time if the symbol ends up in
701             // the same linkage unit.
702             if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
703               Type = RIT_X86_64_GOTLoad;
704             else
705               Type = RIT_X86_64_GOT;
706           }  else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
707             Type = RIT_X86_64_TLV;
708           }  else if (Modifier != MCSymbolRefExpr::VK_None) {
709             report_fatal_error("unsupported symbol modifier in relocation");
710           } else {
711             Type = RIT_X86_64_Signed;
712
713             // The Darwin x86_64 relocation format has a problem where it cannot
714             // encode an address (L<foo> + <constant>) which is outside the atom
715             // containing L<foo>. Generally, this shouldn't occur but it does
716             // happen when we have a RIPrel instruction with data following the
717             // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
718             // adjustment Darwin x86_64 uses, the offset is still negative and
719             // the linker has no way to recognize this.
720             //
721             // To work around this, Darwin uses several special relocation types
722             // to indicate the offsets. However, the specification or
723             // implementation of these seems to also be incomplete; they should
724             // adjust the addend as well based on the actual encoded instruction
725             // (the additional bias), but instead appear to just look at the
726             // final offset.
727             switch (-(Target.getConstant() + (1LL << Log2Size))) {
728             case 1: Type = RIT_X86_64_Signed1; break;
729             case 2: Type = RIT_X86_64_Signed2; break;
730             case 4: Type = RIT_X86_64_Signed4; break;
731             }
732           }
733         } else {
734           if (Modifier != MCSymbolRefExpr::VK_None)
735             report_fatal_error("unsupported symbol modifier in branch "
736                               "relocation");
737
738           Type = RIT_X86_64_Branch;
739         }
740       } else {
741         if (Modifier == MCSymbolRefExpr::VK_GOT) {
742           Type = RIT_X86_64_GOT;
743         } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
744           // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
745           // which case all we do is set the PCrel bit in the relocation entry;
746           // this is used with exception handling, for example. The source is
747           // required to include any necessary offset directly.
748           Type = RIT_X86_64_GOT;
749           IsPCRel = 1;
750         } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
751           report_fatal_error("TLVP symbol modifier should have been rip-rel");
752         } else if (Modifier != MCSymbolRefExpr::VK_None)
753           report_fatal_error("unsupported symbol modifier in relocation");
754         else
755           Type = RIT_X86_64_Unsigned;
756       }
757     }
758
759     // x86_64 always writes custom values into the fixups.
760     FixedValue = Value;
761
762     // struct relocation_info (8 bytes)
763     MachRelocationEntry MRE;
764     MRE.Word0 = FixupOffset;
765     MRE.Word1 = ((Index     <<  0) |
766                  (IsPCRel   << 24) |
767                  (Log2Size  << 25) |
768                  (IsExtern  << 27) |
769                  (Type      << 28));
770     Relocations[Fragment->getParent()].push_back(MRE);
771   }
772
773   void RecordScatteredRelocation(const MCAssembler &Asm,
774                                  const MCAsmLayout &Layout,
775                                  const MCFragment *Fragment,
776                                  const MCFixup &Fixup, MCValue Target,
777                                  uint64_t &FixedValue) {
778     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
779     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
780     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
781     unsigned Type = RIT_Vanilla;
782
783     // See <reloc.h>.
784     const MCSymbol *A = &Target.getSymA()->getSymbol();
785     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
786
787     if (!A_SD->getFragment())
788       report_fatal_error("symbol '" + A->getName() +
789                         "' can not be undefined in a subtraction expression");
790
791     uint32_t Value = Layout.getSymbolAddress(A_SD);
792     uint32_t Value2 = 0;
793
794     if (const MCSymbolRefExpr *B = Target.getSymB()) {
795       MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
796
797       if (!B_SD->getFragment())
798         report_fatal_error("symbol '" + B->getSymbol().getName() +
799                           "' can not be undefined in a subtraction expression");
800
801       // Select the appropriate difference relocation type.
802       //
803       // Note that there is no longer any semantic difference between these two
804       // relocation types from the linkers point of view, this is done solely
805       // for pedantic compatibility with 'as'.
806       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
807       Value2 = Layout.getSymbolAddress(B_SD);
808     }
809
810     // Relocations are written out in reverse order, so the PAIR comes first.
811     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
812       MachRelocationEntry MRE;
813       MRE.Word0 = ((0         <<  0) |
814                    (RIT_Pair  << 24) |
815                    (Log2Size  << 28) |
816                    (IsPCRel   << 30) |
817                    RF_Scattered);
818       MRE.Word1 = Value2;
819       Relocations[Fragment->getParent()].push_back(MRE);
820     }
821
822     MachRelocationEntry MRE;
823     MRE.Word0 = ((FixupOffset <<  0) |
824                  (Type        << 24) |
825                  (Log2Size    << 28) |
826                  (IsPCRel     << 30) |
827                  RF_Scattered);
828     MRE.Word1 = Value;
829     Relocations[Fragment->getParent()].push_back(MRE);
830   }
831
832   void RecordTLVPRelocation(const MCAssembler &Asm,
833                             const MCAsmLayout &Layout,
834                             const MCFragment *Fragment,
835                             const MCFixup &Fixup, MCValue Target,
836                             uint64_t &FixedValue) {
837     assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
838            !Is64Bit &&
839            "Should only be called with a 32-bit TLVP relocation!");
840
841     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
842     uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
843     unsigned IsPCRel = 0;
844
845     // Get the symbol data.
846     MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
847     unsigned Index = SD_A->getIndex();
848
849     // We're only going to have a second symbol in pic mode and it'll be a
850     // subtraction from the picbase. For 32-bit pic the addend is the difference
851     // between the picbase and the next address.  For 32-bit static the addend
852     // is zero.
853     if (Target.getSymB()) {
854       // If this is a subtraction then we're pcrel.
855       uint32_t FixupAddress =
856       Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
857       MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
858       IsPCRel = 1;
859       FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
860                     Target.getConstant());
861       FixedValue += 1ULL << Log2Size;
862     } else {
863       FixedValue = 0;
864     }
865
866     // struct relocation_info (8 bytes)
867     MachRelocationEntry MRE;
868     MRE.Word0 = Value;
869     MRE.Word1 = ((Index     <<  0) |
870                  (IsPCRel   << 24) |
871                  (Log2Size  << 25) |
872                  (1         << 27) | // Extern
873                  (RIT_TLV   << 28)); // Type
874     Relocations[Fragment->getParent()].push_back(MRE);
875   }
876
877   void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
878                         const MCFragment *Fragment, const MCFixup &Fixup,
879                         MCValue Target, uint64_t &FixedValue) {
880     if (Is64Bit) {
881       RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
882       return;
883     }
884
885     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
886     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
887
888     // If this is a 32-bit TLVP reloc it's handled a bit differently.
889     if (Target.getSymA() &&
890         Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
891       RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
892       return;
893     }
894
895     // If this is a difference or a defined symbol plus an offset, then we need
896     // a scattered relocation entry.
897     // Differences always require scattered relocations.
898     if (Target.getSymB())
899         return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
900                                          Target, FixedValue);
901
902     // Get the symbol data, if any.
903     MCSymbolData *SD = 0;
904     if (Target.getSymA())
905       SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
906
907     // If this is an internal relocation with an offset, it also needs a
908     // scattered relocation entry.
909     uint32_t Offset = Target.getConstant();
910     if (IsPCRel)
911       Offset += 1 << Log2Size;
912     if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
913       return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
914                                        Target, FixedValue);
915
916     // See <reloc.h>.
917     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
918     unsigned Index = 0;
919     unsigned IsExtern = 0;
920     unsigned Type = 0;
921
922     if (Target.isAbsolute()) { // constant
923       // SymbolNum of 0 indicates the absolute section.
924       //
925       // FIXME: Currently, these are never generated (see code below). I cannot
926       // find a case where they are actually emitted.
927       Type = RIT_Vanilla;
928     } else {
929       // Check whether we need an external or internal relocation.
930       if (doesSymbolRequireExternRelocation(SD)) {
931         IsExtern = 1;
932         Index = SD->getIndex();
933         // For external relocations, make sure to offset the fixup value to
934         // compensate for the addend of the symbol address, if it was
935         // undefined. This occurs with weak definitions, for example.
936         if (!SD->Symbol->isUndefined())
937           FixedValue -= Layout.getSymbolAddress(SD);
938       } else {
939         // The index is the section ordinal (1-based).
940         Index = SD->getFragment()->getParent()->getOrdinal() + 1;
941       }
942
943       Type = RIT_Vanilla;
944     }
945
946     // struct relocation_info (8 bytes)
947     MachRelocationEntry MRE;
948     MRE.Word0 = FixupOffset;
949     MRE.Word1 = ((Index     <<  0) |
950                  (IsPCRel   << 24) |
951                  (Log2Size  << 25) |
952                  (IsExtern  << 27) |
953                  (Type      << 28));
954     Relocations[Fragment->getParent()].push_back(MRE);
955   }
956
957   void BindIndirectSymbols(MCAssembler &Asm) {
958     // This is the point where 'as' creates actual symbols for indirect symbols
959     // (in the following two passes). It would be easier for us to do this
960     // sooner when we see the attribute, but that makes getting the order in the
961     // symbol table much more complicated than it is worth.
962     //
963     // FIXME: Revisit this when the dust settles.
964
965     // Bind non lazy symbol pointers first.
966     unsigned IndirectIndex = 0;
967     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
968            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
969       const MCSectionMachO &Section =
970         cast<MCSectionMachO>(it->SectionData->getSection());
971
972       if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
973         continue;
974
975       // Initialize the section indirect symbol base, if necessary.
976       if (!IndirectSymBase.count(it->SectionData))
977         IndirectSymBase[it->SectionData] = IndirectIndex;
978
979       Asm.getOrCreateSymbolData(*it->Symbol);
980     }
981
982     // Then lazy symbol pointers and symbol stubs.
983     IndirectIndex = 0;
984     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
985            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
986       const MCSectionMachO &Section =
987         cast<MCSectionMachO>(it->SectionData->getSection());
988
989       if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
990           Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
991         continue;
992
993       // Initialize the section indirect symbol base, if necessary.
994       if (!IndirectSymBase.count(it->SectionData))
995         IndirectSymBase[it->SectionData] = IndirectIndex;
996
997       // Set the symbol type to undefined lazy, but only on construction.
998       //
999       // FIXME: Do not hardcode.
1000       bool Created;
1001       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1002       if (Created)
1003         Entry.setFlags(Entry.getFlags() | 0x0001);
1004     }
1005   }
1006
1007   /// ComputeSymbolTable - Compute the symbol table data
1008   ///
1009   /// \param StringTable [out] - The string table data.
1010   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1011   /// string table.
1012   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1013                           std::vector<MachSymbolData> &LocalSymbolData,
1014                           std::vector<MachSymbolData> &ExternalSymbolData,
1015                           std::vector<MachSymbolData> &UndefinedSymbolData) {
1016     // Build section lookup table.
1017     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1018     unsigned Index = 1;
1019     for (MCAssembler::iterator it = Asm.begin(),
1020            ie = Asm.end(); it != ie; ++it, ++Index)
1021       SectionIndexMap[&it->getSection()] = Index;
1022     assert(Index <= 256 && "Too many sections!");
1023
1024     // Index 0 is always the empty string.
1025     StringMap<uint64_t> StringIndexMap;
1026     StringTable += '\x00';
1027
1028     // Build the symbol arrays and the string table, but only for non-local
1029     // symbols.
1030     //
1031     // The particular order that we collect the symbols and create the string
1032     // table, then sort the symbols is chosen to match 'as'. Even though it
1033     // doesn't matter for correctness, this is important for letting us diff .o
1034     // files.
1035     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1036            ie = Asm.symbol_end(); it != ie; ++it) {
1037       const MCSymbol &Symbol = it->getSymbol();
1038
1039       // Ignore non-linker visible symbols.
1040       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1041         continue;
1042
1043       if (!it->isExternal() && !Symbol.isUndefined())
1044         continue;
1045
1046       uint64_t &Entry = StringIndexMap[Symbol.getName()];
1047       if (!Entry) {
1048         Entry = StringTable.size();
1049         StringTable += Symbol.getName();
1050         StringTable += '\x00';
1051       }
1052
1053       MachSymbolData MSD;
1054       MSD.SymbolData = it;
1055       MSD.StringIndex = Entry;
1056
1057       if (Symbol.isUndefined()) {
1058         MSD.SectionIndex = 0;
1059         UndefinedSymbolData.push_back(MSD);
1060       } else if (Symbol.isAbsolute()) {
1061         MSD.SectionIndex = 0;
1062         ExternalSymbolData.push_back(MSD);
1063       } else {
1064         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1065         assert(MSD.SectionIndex && "Invalid section index!");
1066         ExternalSymbolData.push_back(MSD);
1067       }
1068     }
1069
1070     // Now add the data for local symbols.
1071     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1072            ie = Asm.symbol_end(); it != ie; ++it) {
1073       const MCSymbol &Symbol = it->getSymbol();
1074
1075       // Ignore non-linker visible symbols.
1076       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1077         continue;
1078
1079       if (it->isExternal() || Symbol.isUndefined())
1080         continue;
1081
1082       uint64_t &Entry = StringIndexMap[Symbol.getName()];
1083       if (!Entry) {
1084         Entry = StringTable.size();
1085         StringTable += Symbol.getName();
1086         StringTable += '\x00';
1087       }
1088
1089       MachSymbolData MSD;
1090       MSD.SymbolData = it;
1091       MSD.StringIndex = Entry;
1092
1093       if (Symbol.isAbsolute()) {
1094         MSD.SectionIndex = 0;
1095         LocalSymbolData.push_back(MSD);
1096       } else {
1097         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1098         assert(MSD.SectionIndex && "Invalid section index!");
1099         LocalSymbolData.push_back(MSD);
1100       }
1101     }
1102
1103     // External and undefined symbols are required to be in lexicographic order.
1104     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1105     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1106
1107     // Set the symbol indices.
1108     Index = 0;
1109     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1110       LocalSymbolData[i].SymbolData->setIndex(Index++);
1111     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1112       ExternalSymbolData[i].SymbolData->setIndex(Index++);
1113     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1114       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1115
1116     // The string table is padded to a multiple of 4.
1117     while (StringTable.size() % 4)
1118       StringTable += '\x00';
1119   }
1120
1121   void ExecutePostLayoutBinding(MCAssembler &Asm) {
1122     // Create symbol data for any indirect symbols.
1123     BindIndirectSymbols(Asm);
1124
1125     // Compute symbol table information and bind symbol indices.
1126     ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1127                        UndefinedSymbolData);
1128   }
1129
1130
1131   bool IsFixupFullyResolved(const MCAssembler &Asm,
1132                             const MCValue Target,
1133                             bool IsPCRel,
1134                             const MCFragment *DF) const {
1135     // If we are using scattered symbols, determine whether this value is
1136     // actually resolved; scattering may cause atoms to move.
1137     if (Asm.getBackend().hasScatteredSymbols()) {
1138       if (Asm.getBackend().hasReliableSymbolDifference()) {
1139         // If this is a PCrel relocation, find the base atom (identified by its
1140         // symbol) that the fixup value is relative to.
1141         const MCSymbolData *BaseSymbol = 0;
1142         if (IsPCRel) {
1143           BaseSymbol = DF->getAtom();
1144           if (!BaseSymbol)
1145             return false;
1146         }
1147
1148         return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1149       } else {
1150         const MCSection *BaseSection = 0;
1151         if (IsPCRel)
1152           BaseSection = &DF->getParent()->getSection();
1153
1154         return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1155       }
1156     }
1157     return true;
1158   }
1159
1160   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1161     unsigned NumSections = Asm.size();
1162
1163     // The section data starts after the header, the segment load command (and
1164     // section headers) and the symbol table.
1165     unsigned NumLoadCommands = 1;
1166     uint64_t LoadCommandsSize = Is64Bit ?
1167       SegmentLoadCommand64Size + NumSections * Section64Size :
1168       SegmentLoadCommand32Size + NumSections * Section32Size;
1169
1170     // Add the symbol table load command sizes, if used.
1171     unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1172       UndefinedSymbolData.size();
1173     if (NumSymbols) {
1174       NumLoadCommands += 2;
1175       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1176     }
1177
1178     // Compute the total size of the section data, as well as its file size and
1179     // vm size.
1180     uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1181       + LoadCommandsSize;
1182     uint64_t SectionDataSize = 0;
1183     uint64_t SectionDataFileSize = 0;
1184     uint64_t VMSize = 0;
1185     for (MCAssembler::const_iterator it = Asm.begin(),
1186            ie = Asm.end(); it != ie; ++it) {
1187       const MCSectionData &SD = *it;
1188       uint64_t Address = Layout.getSectionAddress(&SD);
1189       uint64_t Size = Layout.getSectionSize(&SD);
1190       uint64_t FileSize = Layout.getSectionFileSize(&SD);
1191
1192       VMSize = std::max(VMSize, Address + Size);
1193
1194       if (SD.getSection().isVirtualSection())
1195         continue;
1196
1197       SectionDataSize = std::max(SectionDataSize, Address + Size);
1198       SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1199     }
1200
1201     // The section data is padded to 4 bytes.
1202     //
1203     // FIXME: Is this machine dependent?
1204     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1205     SectionDataFileSize += SectionDataPadding;
1206
1207     // Write the prolog, starting with the header and load command...
1208     WriteHeader(NumLoadCommands, LoadCommandsSize,
1209                 Asm.getSubsectionsViaSymbols());
1210     WriteSegmentLoadCommand(NumSections, VMSize,
1211                             SectionDataStart, SectionDataSize);
1212
1213     // ... and then the section headers.
1214     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1215     for (MCAssembler::const_iterator it = Asm.begin(),
1216            ie = Asm.end(); it != ie; ++it) {
1217       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1218       unsigned NumRelocs = Relocs.size();
1219       uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1220       WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1221       RelocTableEnd += NumRelocs * RelocationInfoSize;
1222     }
1223
1224     // Write the symbol table load command, if used.
1225     if (NumSymbols) {
1226       unsigned FirstLocalSymbol = 0;
1227       unsigned NumLocalSymbols = LocalSymbolData.size();
1228       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1229       unsigned NumExternalSymbols = ExternalSymbolData.size();
1230       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1231       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1232       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1233       unsigned NumSymTabSymbols =
1234         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1235       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1236       uint64_t IndirectSymbolOffset = 0;
1237
1238       // If used, the indirect symbols are written after the section data.
1239       if (NumIndirectSymbols)
1240         IndirectSymbolOffset = RelocTableEnd;
1241
1242       // The symbol table is written after the indirect symbol data.
1243       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1244
1245       // The string table is written after symbol table.
1246       uint64_t StringTableOffset =
1247         SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1248                                                 Nlist32Size);
1249       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1250                              StringTableOffset, StringTable.size());
1251
1252       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1253                                FirstExternalSymbol, NumExternalSymbols,
1254                                FirstUndefinedSymbol, NumUndefinedSymbols,
1255                                IndirectSymbolOffset, NumIndirectSymbols);
1256     }
1257
1258     // Write the actual section data.
1259     for (MCAssembler::const_iterator it = Asm.begin(),
1260            ie = Asm.end(); it != ie; ++it)
1261       Asm.WriteSectionData(it, Layout, this);
1262
1263     // Write the extra padding.
1264     WriteZeros(SectionDataPadding);
1265
1266     // Write the relocation entries.
1267     for (MCAssembler::const_iterator it = Asm.begin(),
1268            ie = Asm.end(); it != ie; ++it) {
1269       // Write the section relocation entries, in reverse order to match 'as'
1270       // (approximately, the exact algorithm is more complicated than this).
1271       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1272       for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1273         Write32(Relocs[e - i - 1].Word0);
1274         Write32(Relocs[e - i - 1].Word1);
1275       }
1276     }
1277
1278     // Write the symbol table data, if used.
1279     if (NumSymbols) {
1280       // Write the indirect symbol entries.
1281       for (MCAssembler::const_indirect_symbol_iterator
1282              it = Asm.indirect_symbol_begin(),
1283              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1284         // Indirect symbols in the non lazy symbol pointer section have some
1285         // special handling.
1286         const MCSectionMachO &Section =
1287           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1288         if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1289           // If this symbol is defined and internal, mark it as such.
1290           if (it->Symbol->isDefined() &&
1291               !Asm.getSymbolData(*it->Symbol).isExternal()) {
1292             uint32_t Flags = ISF_Local;
1293             if (it->Symbol->isAbsolute())
1294               Flags |= ISF_Absolute;
1295             Write32(Flags);
1296             continue;
1297           }
1298         }
1299
1300         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1301       }
1302
1303       // FIXME: Check that offsets match computed ones.
1304
1305       // Write the symbol table entries.
1306       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1307         WriteNlist(LocalSymbolData[i], Layout);
1308       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1309         WriteNlist(ExternalSymbolData[i], Layout);
1310       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1311         WriteNlist(UndefinedSymbolData[i], Layout);
1312
1313       // Write the string table.
1314       OS << StringTable.str();
1315     }
1316   }
1317 };
1318
1319 }
1320
1321 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1322                                              uint32_t CPUType,
1323                                              uint32_t CPUSubtype,
1324                                              bool IsLittleEndian) {
1325   return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
1326 }