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