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