MCAssembler: Pull out MCObjectWriter class.
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCSectionMachO.h"
15 #include "llvm/MC/MCSymbol.h"
16 #include "llvm/MC/MCValue.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MachO.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetAsmBackend.h"
29
30 // FIXME: Gross.
31 #include "../Target/X86/X86FixupKinds.h"
32
33 #include <vector>
34 using namespace llvm;
35
36 class MachObjectWriter;
37
38 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
39
40 // FIXME FIXME FIXME: There are number of places in this file where we convert
41 // what is a 64-bit assembler value used for computation into a value in the
42 // object file, which may truncate it. We should detect that truncation where
43 // invalid and report errors back.
44
45 class MCObjectWriter;
46 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
47                           MCObjectWriter *MOW);
48
49 /// isVirtualSection - Check if this is a section which does not actually exist
50 /// in the object file.
51 static bool isVirtualSection(const MCSection &Section) {
52   // FIXME: Lame.
53   const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
54   return (SMO.getType() == MCSectionMachO::S_ZEROFILL);
55 }
56
57 static unsigned getFixupKindLog2Size(unsigned Kind) {
58   switch (Kind) {
59   default: llvm_unreachable("invalid fixup kind!");
60   case X86::reloc_pcrel_1byte:
61   case FK_Data_1: return 0;
62   case FK_Data_2: return 1;
63   case X86::reloc_pcrel_4byte:
64   case X86::reloc_riprel_4byte:
65   case FK_Data_4: return 2;
66   case FK_Data_8: return 3;
67   }
68 }
69
70 static bool isFixupKindPCRel(unsigned Kind) {
71   switch (Kind) {
72   default:
73     return false;
74   case X86::reloc_pcrel_1byte:
75   case X86::reloc_pcrel_4byte:
76   case X86::reloc_riprel_4byte:
77     return true;
78   }
79 }
80
81 class MCObjectWriter {
82   MCObjectWriter(const MCObjectWriter &); // DO NOT IMPLEMENT
83   void operator=(const MCObjectWriter &); // DO NOT IMPLEMENT
84
85 protected:
86   raw_ostream &OS;
87
88   unsigned IsLittleEndian : 1;
89
90 protected: // Can only create subclasses.
91   MCObjectWriter(raw_ostream &_OS, bool _IsLittleEndian)
92     : OS(_OS), IsLittleEndian(_IsLittleEndian) {}
93   virtual ~MCObjectWriter();
94
95 public:
96
97   bool isLittleEndian() { return IsLittleEndian; }
98
99   raw_ostream &getStream() { return OS; }
100
101   /// @name Binary Output Methods
102   /// @{
103
104   void Write8(uint8_t Value) {
105     OS << char(Value);
106   }
107
108   void WriteLE16(uint16_t Value) {
109     Write8(uint8_t(Value >> 0));
110     Write8(uint8_t(Value >> 8));
111   }
112
113   void WriteLE32(uint32_t Value) {
114     WriteLE16(uint16_t(Value >> 0));
115     WriteLE16(uint16_t(Value >> 16));
116   }
117
118   void WriteLE64(uint64_t Value) {
119     WriteLE32(uint32_t(Value >> 0));
120     WriteLE32(uint32_t(Value >> 32));
121   }
122
123   void WriteBE16(uint16_t Value) {
124     Write8(uint8_t(Value >> 8));
125     Write8(uint8_t(Value >> 0));
126   }
127
128   void WriteBE32(uint32_t Value) {
129     WriteBE16(uint16_t(Value >> 16));
130     WriteBE16(uint16_t(Value >> 0));
131   }
132
133   void WriteBE64(uint64_t Value) {
134     WriteBE32(uint32_t(Value >> 32));
135     WriteBE32(uint32_t(Value >> 0));
136   }
137
138   void Write16(uint16_t Value) {
139     if (IsLittleEndian)
140       WriteLE16(Value);
141     else
142       WriteBE16(Value);
143   }
144
145   void Write32(uint32_t Value) {
146     if (IsLittleEndian)
147       WriteLE32(Value);
148     else
149       WriteBE32(Value);
150   }
151
152   void Write64(uint64_t Value) {
153     if (IsLittleEndian)
154       WriteLE64(Value);
155     else
156       WriteBE64(Value);
157   }
158
159   void WriteZeros(unsigned N) {
160     const char Zeros[16] = { 0 };
161
162     for (unsigned i = 0, e = N / 16; i != e; ++i)
163       OS << StringRef(Zeros, 16);
164
165     OS << StringRef(Zeros, N % 16);
166   }
167
168   void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
169     OS << Str;
170     if (ZeroFillSize)
171       WriteZeros(ZeroFillSize - Str.size());
172   }
173
174   /// @}
175 };
176
177 MCObjectWriter::~MCObjectWriter() {
178 }
179
180 class MachObjectWriter : public MCObjectWriter {
181   // See <mach-o/loader.h>.
182   enum {
183     Header_Magic32 = 0xFEEDFACE,
184     Header_Magic64 = 0xFEEDFACF
185   };
186
187   enum {
188     Header32Size = 28,
189     Header64Size = 32,
190     SegmentLoadCommand32Size = 56,
191     SegmentLoadCommand64Size = 72,
192     Section32Size = 68,
193     Section64Size = 80,
194     SymtabLoadCommandSize = 24,
195     DysymtabLoadCommandSize = 80,
196     Nlist32Size = 12,
197     Nlist64Size = 16,
198     RelocationInfoSize = 8
199   };
200
201   enum HeaderFileType {
202     HFT_Object = 0x1
203   };
204
205   enum HeaderFlags {
206     HF_SubsectionsViaSymbols = 0x2000
207   };
208
209   enum LoadCommandType {
210     LCT_Segment = 0x1,
211     LCT_Symtab = 0x2,
212     LCT_Dysymtab = 0xb,
213     LCT_Segment64 = 0x19
214   };
215
216   // See <mach-o/nlist.h>.
217   enum SymbolTypeType {
218     STT_Undefined = 0x00,
219     STT_Absolute  = 0x02,
220     STT_Section   = 0x0e
221   };
222
223   enum SymbolTypeFlags {
224     // If any of these bits are set, then the entry is a stab entry number (see
225     // <mach-o/stab.h>. Otherwise the other masks apply.
226     STF_StabsEntryMask = 0xe0,
227
228     STF_TypeMask       = 0x0e,
229     STF_External       = 0x01,
230     STF_PrivateExtern  = 0x10
231   };
232
233   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
234   /// symbol entry.
235   enum IndirectSymbolFlags {
236     ISF_Local    = 0x80000000,
237     ISF_Absolute = 0x40000000
238   };
239
240   /// RelocationFlags - Special flags for addresses.
241   enum RelocationFlags {
242     RF_Scattered = 0x80000000
243   };
244
245   enum RelocationInfoType {
246     RIT_Vanilla             = 0,
247     RIT_Pair                = 1,
248     RIT_Difference          = 2,
249     RIT_PreboundLazyPointer = 3,
250     RIT_LocalDifference     = 4
251   };
252
253   /// MachSymbolData - Helper struct for containing some precomputed information
254   /// on symbols.
255   struct MachSymbolData {
256     MCSymbolData *SymbolData;
257     uint64_t StringIndex;
258     uint8_t SectionIndex;
259
260     // Support lexicographic sorting.
261     bool operator<(const MachSymbolData &RHS) const {
262       const std::string &Name = SymbolData->getSymbol().getName();
263       return Name < RHS.SymbolData->getSymbol().getName();
264     }
265   };
266
267   unsigned Is64Bit : 1;
268
269   /// @name Relocation Data
270   /// @{
271
272   struct MachRelocationEntry {
273     uint32_t Word0;
274     uint32_t Word1;
275   };
276
277   llvm::DenseMap<const MCSectionData*,
278                  std::vector<MachRelocationEntry> > Relocations;
279
280   /// @}
281   /// @name Symbol Table Data
282
283   SmallString<256> StringTable;
284   std::vector<MachSymbolData> LocalSymbolData;
285   std::vector<MachSymbolData> ExternalSymbolData;
286   std::vector<MachSymbolData> UndefinedSymbolData;
287
288   /// @}
289
290 public:
291   MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLittleEndian = true)
292     : MCObjectWriter(_OS, _IsLittleEndian), Is64Bit(_Is64Bit) {
293   }
294
295   void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
296                    bool SubsectionsViaSymbols) {
297     uint32_t Flags = 0;
298
299     if (SubsectionsViaSymbols)
300       Flags |= HF_SubsectionsViaSymbols;
301
302     // struct mach_header (28 bytes) or
303     // struct mach_header_64 (32 bytes)
304
305     uint64_t Start = OS.tell();
306     (void) Start;
307
308     Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
309
310     // FIXME: Support cputype.
311     Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
312     // FIXME: Support cpusubtype.
313     Write32(MachO::CPUSubType_I386_ALL);
314     Write32(HFT_Object);
315     Write32(NumLoadCommands);    // Object files have a single load command, the
316                                  // segment.
317     Write32(LoadCommandsSize);
318     Write32(Flags);
319     if (Is64Bit)
320       Write32(0); // reserved
321
322     assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
323   }
324
325   /// WriteSegmentLoadCommand - Write a segment load command.
326   ///
327   /// \arg NumSections - The number of sections in this segment.
328   /// \arg SectionDataSize - The total size of the sections.
329   void WriteSegmentLoadCommand(unsigned NumSections,
330                                uint64_t VMSize,
331                                uint64_t SectionDataStartOffset,
332                                uint64_t SectionDataSize) {
333     // struct segment_command (56 bytes) or
334     // struct segment_command_64 (72 bytes)
335
336     uint64_t Start = OS.tell();
337     (void) Start;
338
339     unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
340       SegmentLoadCommand32Size;
341     Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
342     Write32(SegmentLoadCommandSize +
343             NumSections * (Is64Bit ? Section64Size : Section32Size));
344
345     WriteBytes("", 16);
346     if (Is64Bit) {
347       Write64(0); // vmaddr
348       Write64(VMSize); // vmsize
349       Write64(SectionDataStartOffset); // file offset
350       Write64(SectionDataSize); // file size
351     } else {
352       Write32(0); // vmaddr
353       Write32(VMSize); // vmsize
354       Write32(SectionDataStartOffset); // file offset
355       Write32(SectionDataSize); // file size
356     }
357     Write32(0x7); // maxprot
358     Write32(0x7); // initprot
359     Write32(NumSections);
360     Write32(0); // flags
361
362     assert(OS.tell() - Start == SegmentLoadCommandSize);
363   }
364
365   void WriteSection(const MCSectionData &SD, uint64_t FileOffset,
366                     uint64_t RelocationsStart, unsigned NumRelocations) {
367     // The offset is unused for virtual sections.
368     if (isVirtualSection(SD.getSection())) {
369       assert(SD.getFileSize() == 0 && "Invalid file size!");
370       FileOffset = 0;
371     }
372
373     // struct section (68 bytes) or
374     // struct section_64 (80 bytes)
375
376     uint64_t Start = OS.tell();
377     (void) Start;
378
379     // FIXME: cast<> support!
380     const MCSectionMachO &Section =
381       static_cast<const MCSectionMachO&>(SD.getSection());
382     WriteBytes(Section.getSectionName(), 16);
383     WriteBytes(Section.getSegmentName(), 16);
384     if (Is64Bit) {
385       Write64(SD.getAddress()); // address
386       Write64(SD.getSize()); // size
387     } else {
388       Write32(SD.getAddress()); // address
389       Write32(SD.getSize()); // size
390     }
391     Write32(FileOffset);
392
393     unsigned Flags = Section.getTypeAndAttributes();
394     if (SD.hasInstructions())
395       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
396
397     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
398     Write32(Log2_32(SD.getAlignment()));
399     Write32(NumRelocations ? RelocationsStart : 0);
400     Write32(NumRelocations);
401     Write32(Flags);
402     Write32(0); // reserved1
403     Write32(Section.getStubSize()); // reserved2
404     if (Is64Bit)
405       Write32(0); // reserved3
406
407     assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
408   }
409
410   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
411                               uint32_t StringTableOffset,
412                               uint32_t StringTableSize) {
413     // struct symtab_command (24 bytes)
414
415     uint64_t Start = OS.tell();
416     (void) Start;
417
418     Write32(LCT_Symtab);
419     Write32(SymtabLoadCommandSize);
420     Write32(SymbolOffset);
421     Write32(NumSymbols);
422     Write32(StringTableOffset);
423     Write32(StringTableSize);
424
425     assert(OS.tell() - Start == SymtabLoadCommandSize);
426   }
427
428   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
429                                 uint32_t NumLocalSymbols,
430                                 uint32_t FirstExternalSymbol,
431                                 uint32_t NumExternalSymbols,
432                                 uint32_t FirstUndefinedSymbol,
433                                 uint32_t NumUndefinedSymbols,
434                                 uint32_t IndirectSymbolOffset,
435                                 uint32_t NumIndirectSymbols) {
436     // struct dysymtab_command (80 bytes)
437
438     uint64_t Start = OS.tell();
439     (void) Start;
440
441     Write32(LCT_Dysymtab);
442     Write32(DysymtabLoadCommandSize);
443     Write32(FirstLocalSymbol);
444     Write32(NumLocalSymbols);
445     Write32(FirstExternalSymbol);
446     Write32(NumExternalSymbols);
447     Write32(FirstUndefinedSymbol);
448     Write32(NumUndefinedSymbols);
449     Write32(0); // tocoff
450     Write32(0); // ntoc
451     Write32(0); // modtaboff
452     Write32(0); // nmodtab
453     Write32(0); // extrefsymoff
454     Write32(0); // nextrefsyms
455     Write32(IndirectSymbolOffset);
456     Write32(NumIndirectSymbols);
457     Write32(0); // extreloff
458     Write32(0); // nextrel
459     Write32(0); // locreloff
460     Write32(0); // nlocrel
461
462     assert(OS.tell() - Start == DysymtabLoadCommandSize);
463   }
464
465   void WriteNlist(MachSymbolData &MSD) {
466     MCSymbolData &Data = *MSD.SymbolData;
467     const MCSymbol &Symbol = Data.getSymbol();
468     uint8_t Type = 0;
469     uint16_t Flags = Data.getFlags();
470     uint32_t Address = 0;
471
472     // Set the N_TYPE bits. See <mach-o/nlist.h>.
473     //
474     // FIXME: Are the prebound or indirect fields possible here?
475     if (Symbol.isUndefined())
476       Type = STT_Undefined;
477     else if (Symbol.isAbsolute())
478       Type = STT_Absolute;
479     else
480       Type = STT_Section;
481
482     // FIXME: Set STAB bits.
483
484     if (Data.isPrivateExtern())
485       Type |= STF_PrivateExtern;
486
487     // Set external bit.
488     if (Data.isExternal() || Symbol.isUndefined())
489       Type |= STF_External;
490
491     // Compute the symbol address.
492     if (Symbol.isDefined()) {
493       if (Symbol.isAbsolute()) {
494         llvm_unreachable("FIXME: Not yet implemented!");
495       } else {
496         Address = Data.getAddress();
497       }
498     } else if (Data.isCommon()) {
499       // Common symbols are encoded with the size in the address
500       // field, and their alignment in the flags.
501       Address = Data.getCommonSize();
502
503       // Common alignment is packed into the 'desc' bits.
504       if (unsigned Align = Data.getCommonAlignment()) {
505         unsigned Log2Size = Log2_32(Align);
506         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
507         if (Log2Size > 15)
508           llvm_report_error("invalid 'common' alignment '" +
509                             Twine(Align) + "'");
510         // FIXME: Keep this mask with the SymbolFlags enumeration.
511         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
512       }
513     }
514
515     // struct nlist (12 bytes)
516
517     Write32(MSD.StringIndex);
518     Write8(Type);
519     Write8(MSD.SectionIndex);
520
521     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
522     // value.
523     Write16(Flags);
524     if (Is64Bit)
525       Write64(Address);
526     else
527       Write32(Address);
528   }
529
530   void RecordScatteredRelocation(MCAssembler &Asm, MCFragment &Fragment,
531                                  const MCAsmFixup &Fixup, MCValue Target,
532                                  uint64_t &FixedValue) {
533     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
534     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
535     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
536     unsigned Type = RIT_Vanilla;
537
538     // See <reloc.h>.
539     const MCSymbol *A = &Target.getSymA()->getSymbol();
540     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
541
542     if (!A_SD->getFragment())
543       llvm_report_error("symbol '" + A->getName() +
544                         "' can not be undefined in a subtraction expression");
545
546     uint32_t Value = A_SD->getAddress();
547     uint32_t Value2 = 0;
548
549     if (const MCSymbolRefExpr *B = Target.getSymB()) {
550       MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
551
552       if (!B_SD->getFragment())
553         llvm_report_error("symbol '" + B->getSymbol().getName() +
554                           "' can not be undefined in a subtraction expression");
555
556       // Select the appropriate difference relocation type.
557       //
558       // Note that there is no longer any semantic difference between these two
559       // relocation types from the linkers point of view, this is done solely
560       // for pedantic compatibility with 'as'.
561       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
562       Value2 = B_SD->getAddress();
563     }
564
565     // Relocations are written out in reverse order, so the PAIR comes first.
566     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
567       MachRelocationEntry MRE;
568       MRE.Word0 = ((0         <<  0) |
569                    (RIT_Pair  << 24) |
570                    (Log2Size  << 28) |
571                    (IsPCRel   << 30) |
572                    RF_Scattered);
573       MRE.Word1 = Value2;
574       Relocations[Fragment.getParent()].push_back(MRE);
575     }
576
577     MachRelocationEntry MRE;
578     MRE.Word0 = ((Address   <<  0) |
579                  (Type      << 24) |
580                  (Log2Size  << 28) |
581                  (IsPCRel   << 30) |
582                  RF_Scattered);
583     MRE.Word1 = Value;
584     Relocations[Fragment.getParent()].push_back(MRE);
585   }
586
587   void RecordRelocation(MCAssembler &Asm, MCDataFragment &Fragment,
588                         const MCAsmFixup &Fixup, MCValue Target,
589                         uint64_t &FixedValue) {
590     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
591     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
592
593     // If this is a difference or a defined symbol plus an offset, then we need
594     // a scattered relocation entry.
595     uint32_t Offset = Target.getConstant();
596     if (IsPCRel)
597       Offset += 1 << Log2Size;
598     if (Target.getSymB() ||
599         (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
600          Offset)) {
601       RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
602       return;
603     }
604
605     // See <reloc.h>.
606     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
607     uint32_t Value = 0;
608     unsigned Index = 0;
609     unsigned IsExtern = 0;
610     unsigned Type = 0;
611
612     if (Target.isAbsolute()) { // constant
613       // SymbolNum of 0 indicates the absolute section.
614       //
615       // FIXME: Currently, these are never generated (see code below). I cannot
616       // find a case where they are actually emitted.
617       Type = RIT_Vanilla;
618       Value = 0;
619     } else {
620       const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
621       MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
622
623       if (Symbol->isUndefined()) {
624         IsExtern = 1;
625         Index = SD->getIndex();
626         Value = 0;
627       } else {
628         // The index is the section ordinal.
629         //
630         // FIXME: O(N)
631         Index = 1;
632         MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
633         for (; it != ie; ++it, ++Index)
634           if (&*it == SD->getFragment()->getParent())
635             break;
636         assert(it != ie && "Unable to find section index!");
637         Value = SD->getAddress();
638       }
639
640       Type = RIT_Vanilla;
641     }
642
643     // struct relocation_info (8 bytes)
644     MachRelocationEntry MRE;
645     MRE.Word0 = Address;
646     MRE.Word1 = ((Index     <<  0) |
647                  (IsPCRel   << 24) |
648                  (Log2Size  << 25) |
649                  (IsExtern  << 27) |
650                  (Type      << 28));
651     Relocations[Fragment.getParent()].push_back(MRE);
652   }
653
654   void BindIndirectSymbols(MCAssembler &Asm) {
655     // This is the point where 'as' creates actual symbols for indirect symbols
656     // (in the following two passes). It would be easier for us to do this
657     // sooner when we see the attribute, but that makes getting the order in the
658     // symbol table much more complicated than it is worth.
659     //
660     // FIXME: Revisit this when the dust settles.
661
662     // Bind non lazy symbol pointers first.
663     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
664            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
665       // FIXME: cast<> support!
666       const MCSectionMachO &Section =
667         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
668
669       if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
670         continue;
671
672       Asm.getOrCreateSymbolData(*it->Symbol);
673     }
674
675     // Then lazy symbol pointers and symbol stubs.
676     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
677            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
678       // FIXME: cast<> support!
679       const MCSectionMachO &Section =
680         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
681
682       if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
683           Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
684         continue;
685
686       // Set the symbol type to undefined lazy, but only on construction.
687       //
688       // FIXME: Do not hardcode.
689       bool Created;
690       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
691       if (Created)
692         Entry.setFlags(Entry.getFlags() | 0x0001);
693     }
694   }
695
696   /// ComputeSymbolTable - Compute the symbol table data
697   ///
698   /// \param StringTable [out] - The string table data.
699   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
700   /// string table.
701   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
702                           std::vector<MachSymbolData> &LocalSymbolData,
703                           std::vector<MachSymbolData> &ExternalSymbolData,
704                           std::vector<MachSymbolData> &UndefinedSymbolData) {
705     // Build section lookup table.
706     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
707     unsigned Index = 1;
708     for (MCAssembler::iterator it = Asm.begin(),
709            ie = Asm.end(); it != ie; ++it, ++Index)
710       SectionIndexMap[&it->getSection()] = Index;
711     assert(Index <= 256 && "Too many sections!");
712
713     // Index 0 is always the empty string.
714     StringMap<uint64_t> StringIndexMap;
715     StringTable += '\x00';
716
717     // Build the symbol arrays and the string table, but only for non-local
718     // symbols.
719     //
720     // The particular order that we collect the symbols and create the string
721     // table, then sort the symbols is chosen to match 'as'. Even though it
722     // doesn't matter for correctness, this is important for letting us diff .o
723     // files.
724     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
725            ie = Asm.symbol_end(); it != ie; ++it) {
726       const MCSymbol &Symbol = it->getSymbol();
727
728       // Ignore non-linker visible symbols.
729       if (!Asm.isSymbolLinkerVisible(it))
730         continue;
731
732       if (!it->isExternal() && !Symbol.isUndefined())
733         continue;
734
735       uint64_t &Entry = StringIndexMap[Symbol.getName()];
736       if (!Entry) {
737         Entry = StringTable.size();
738         StringTable += Symbol.getName();
739         StringTable += '\x00';
740       }
741
742       MachSymbolData MSD;
743       MSD.SymbolData = it;
744       MSD.StringIndex = Entry;
745
746       if (Symbol.isUndefined()) {
747         MSD.SectionIndex = 0;
748         UndefinedSymbolData.push_back(MSD);
749       } else if (Symbol.isAbsolute()) {
750         MSD.SectionIndex = 0;
751         ExternalSymbolData.push_back(MSD);
752       } else {
753         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
754         assert(MSD.SectionIndex && "Invalid section index!");
755         ExternalSymbolData.push_back(MSD);
756       }
757     }
758
759     // Now add the data for local symbols.
760     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
761            ie = Asm.symbol_end(); it != ie; ++it) {
762       const MCSymbol &Symbol = it->getSymbol();
763
764       // Ignore non-linker visible symbols.
765       if (!Asm.isSymbolLinkerVisible(it))
766         continue;
767
768       if (it->isExternal() || Symbol.isUndefined())
769         continue;
770
771       uint64_t &Entry = StringIndexMap[Symbol.getName()];
772       if (!Entry) {
773         Entry = StringTable.size();
774         StringTable += Symbol.getName();
775         StringTable += '\x00';
776       }
777
778       MachSymbolData MSD;
779       MSD.SymbolData = it;
780       MSD.StringIndex = Entry;
781
782       if (Symbol.isAbsolute()) {
783         MSD.SectionIndex = 0;
784         LocalSymbolData.push_back(MSD);
785       } else {
786         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
787         assert(MSD.SectionIndex && "Invalid section index!");
788         LocalSymbolData.push_back(MSD);
789       }
790     }
791
792     // External and undefined symbols are required to be in lexicographic order.
793     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
794     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
795
796     // Set the symbol indices.
797     Index = 0;
798     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
799       LocalSymbolData[i].SymbolData->setIndex(Index++);
800     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
801       ExternalSymbolData[i].SymbolData->setIndex(Index++);
802     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
803       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
804
805     // The string table is padded to a multiple of 4.
806     while (StringTable.size() % 4)
807       StringTable += '\x00';
808   }
809
810   void ExecutePostLayoutBinding(MCAssembler &Asm) {
811     // Create symbol data for any indirect symbols.
812     BindIndirectSymbols(Asm);
813
814     // Compute symbol table information and bind symbol indices.
815     ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
816                        UndefinedSymbolData);
817   }
818
819   void WriteObject(const MCAssembler &Asm) {
820     unsigned NumSections = Asm.size();
821
822     // The section data starts after the header, the segment load command (and
823     // section headers) and the symbol table.
824     unsigned NumLoadCommands = 1;
825     uint64_t LoadCommandsSize = Is64Bit ?
826       SegmentLoadCommand64Size + NumSections * Section64Size :
827       SegmentLoadCommand32Size + NumSections * Section32Size;
828
829     // Add the symbol table load command sizes, if used.
830     unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
831       UndefinedSymbolData.size();
832     if (NumSymbols) {
833       NumLoadCommands += 2;
834       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
835     }
836
837     // Compute the total size of the section data, as well as its file size and
838     // vm size.
839     uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
840       + LoadCommandsSize;
841     uint64_t SectionDataSize = 0;
842     uint64_t SectionDataFileSize = 0;
843     uint64_t VMSize = 0;
844     for (MCAssembler::const_iterator it = Asm.begin(),
845            ie = Asm.end(); it != ie; ++it) {
846       const MCSectionData &SD = *it;
847
848       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
849
850       if (isVirtualSection(SD.getSection()))
851         continue;
852
853       SectionDataSize = std::max(SectionDataSize,
854                                  SD.getAddress() + SD.getSize());
855       SectionDataFileSize = std::max(SectionDataFileSize,
856                                      SD.getAddress() + SD.getFileSize());
857     }
858
859     // The section data is padded to 4 bytes.
860     //
861     // FIXME: Is this machine dependent?
862     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
863     SectionDataFileSize += SectionDataPadding;
864
865     // Write the prolog, starting with the header and load command...
866     WriteHeader(NumLoadCommands, LoadCommandsSize,
867                 Asm.getSubsectionsViaSymbols());
868     WriteSegmentLoadCommand(NumSections, VMSize,
869                             SectionDataStart, SectionDataSize);
870
871     // ... and then the section headers.
872     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
873     for (MCAssembler::const_iterator it = Asm.begin(),
874            ie = Asm.end(); it != ie; ++it) {
875       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
876       unsigned NumRelocs = Relocs.size();
877       uint64_t SectionStart = SectionDataStart + it->getAddress();
878       WriteSection(*it, SectionStart, RelocTableEnd, NumRelocs);
879       RelocTableEnd += NumRelocs * RelocationInfoSize;
880     }
881
882     // Write the symbol table load command, if used.
883     if (NumSymbols) {
884       unsigned FirstLocalSymbol = 0;
885       unsigned NumLocalSymbols = LocalSymbolData.size();
886       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
887       unsigned NumExternalSymbols = ExternalSymbolData.size();
888       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
889       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
890       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
891       unsigned NumSymTabSymbols =
892         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
893       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
894       uint64_t IndirectSymbolOffset = 0;
895
896       // If used, the indirect symbols are written after the section data.
897       if (NumIndirectSymbols)
898         IndirectSymbolOffset = RelocTableEnd;
899
900       // The symbol table is written after the indirect symbol data.
901       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
902
903       // The string table is written after symbol table.
904       uint64_t StringTableOffset =
905         SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
906                                                 Nlist32Size);
907       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
908                              StringTableOffset, StringTable.size());
909
910       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
911                                FirstExternalSymbol, NumExternalSymbols,
912                                FirstUndefinedSymbol, NumUndefinedSymbols,
913                                IndirectSymbolOffset, NumIndirectSymbols);
914     }
915
916     // Write the actual section data.
917     for (MCAssembler::const_iterator it = Asm.begin(),
918            ie = Asm.end(); it != ie; ++it)
919       WriteFileData(OS, *it, this);
920
921     // Write the extra padding.
922     WriteZeros(SectionDataPadding);
923
924     // Write the relocation entries.
925     for (MCAssembler::const_iterator it = Asm.begin(),
926            ie = Asm.end(); it != ie; ++it) {
927       // Write the section relocation entries, in reverse order to match 'as'
928       // (approximately, the exact algorithm is more complicated than this).
929       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
930       for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
931         Write32(Relocs[e - i - 1].Word0);
932         Write32(Relocs[e - i - 1].Word1);
933       }
934     }
935
936     // Write the symbol table data, if used.
937     if (NumSymbols) {
938       // Write the indirect symbol entries.
939       for (MCAssembler::const_indirect_symbol_iterator
940              it = Asm.indirect_symbol_begin(),
941              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
942         // Indirect symbols in the non lazy symbol pointer section have some
943         // special handling.
944         const MCSectionMachO &Section =
945           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
946         if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
947           // If this symbol is defined and internal, mark it as such.
948           if (it->Symbol->isDefined() &&
949               !Asm.getSymbolData(*it->Symbol).isExternal()) {
950             uint32_t Flags = ISF_Local;
951             if (it->Symbol->isAbsolute())
952               Flags |= ISF_Absolute;
953             Write32(Flags);
954             continue;
955           }
956         }
957
958         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
959       }
960
961       // FIXME: Check that offsets match computed ones.
962
963       // Write the symbol table entries.
964       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
965         WriteNlist(LocalSymbolData[i]);
966       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
967         WriteNlist(ExternalSymbolData[i]);
968       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
969         WriteNlist(UndefinedSymbolData[i]);
970
971       // Write the string table.
972       OS << StringTable.str();
973     }
974   }
975 };
976
977 /* *** */
978
979 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
980 }
981
982 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
983   : Kind(_Kind),
984     Parent(_Parent),
985     FileSize(~UINT64_C(0))
986 {
987   if (Parent)
988     Parent->getFragmentList().push_back(this);
989 }
990
991 MCFragment::~MCFragment() {
992 }
993
994 uint64_t MCFragment::getAddress() const {
995   assert(getParent() && "Missing Section!");
996   return getParent()->getAddress() + Offset;
997 }
998
999 /* *** */
1000
1001 MCSectionData::MCSectionData() : Section(0) {}
1002
1003 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
1004   : Section(&_Section),
1005     Alignment(1),
1006     Address(~UINT64_C(0)),
1007     Size(~UINT64_C(0)),
1008     FileSize(~UINT64_C(0)),
1009     HasInstructions(false)
1010 {
1011   if (A)
1012     A->getSectionList().push_back(this);
1013 }
1014
1015 /* *** */
1016
1017 MCSymbolData::MCSymbolData() : Symbol(0) {}
1018
1019 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
1020                            uint64_t _Offset, MCAssembler *A)
1021   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
1022     IsExternal(false), IsPrivateExtern(false),
1023     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
1024 {
1025   if (A)
1026     A->getSymbolList().push_back(this);
1027 }
1028
1029 /* *** */
1030
1031 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
1032                          raw_ostream &_OS)
1033   : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
1034 {
1035 }
1036
1037 MCAssembler::~MCAssembler() {
1038 }
1039
1040 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
1041                                                 const MCAsmFixup &Fixup,
1042                                                 const MCDataFragment *DF,
1043                                                 const MCValue Target,
1044                                                 const MCSection *BaseSection) {
1045   // The effective fixup address is
1046   //     addr(atom(A)) + offset(A)
1047   //   - addr(atom(B)) - offset(B)
1048   //   - addr(<base symbol>) + <fixup offset from base symbol>
1049   // and the offsets are not relocatable, so the fixup is fully resolved when
1050   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
1051   //
1052   // The simple (Darwin, except on x86_64) way of dealing with this was to
1053   // assume that any reference to a temporary symbol *must* be a temporary
1054   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
1055   // relocation to a temporary symbol (in the same section) is fully
1056   // resolved. This also works in conjunction with absolutized .set, which
1057   // requires the compiler to use .set to absolutize the differences between
1058   // symbols which the compiler knows to be assembly time constants, so we don't
1059   // need to worry about consider symbol differences fully resolved.
1060
1061   // Non-relative fixups are only resolved if constant.
1062   if (!BaseSection)
1063     return Target.isAbsolute();
1064
1065   // Otherwise, relative fixups are only resolved if not a difference and the
1066   // target is a temporary in the same section.
1067   if (Target.isAbsolute() || Target.getSymB())
1068     return false;
1069
1070   const MCSymbol *A = &Target.getSymA()->getSymbol();
1071   if (!A->isTemporary() || !A->isInSection() ||
1072       &A->getSection() != BaseSection)
1073     return false;
1074
1075   return true;
1076 }
1077
1078 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
1079                                           const MCAsmFixup &Fixup,
1080                                           const MCDataFragment *DF,
1081                                           const MCValue Target,
1082                                           const MCSymbolData *BaseSymbol) {
1083   // The effective fixup address is
1084   //     addr(atom(A)) + offset(A)
1085   //   - addr(atom(B)) - offset(B)
1086   //   - addr(BaseSymbol) + <fixup offset from base symbol>
1087   // and the offsets are not relocatable, so the fixup is fully resolved when
1088   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
1089   //
1090   // Note that "false" is almost always conservatively correct (it means we emit
1091   // a relocation which is unnecessary), except when it would force us to emit a
1092   // relocation which the target cannot encode.
1093
1094   const MCSymbolData *A_Base = 0, *B_Base = 0;
1095   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1096     // Modified symbol references cannot be resolved.
1097     if (A->getKind() != MCSymbolRefExpr::VK_None)
1098       return false;
1099
1100     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1101     if (!A_Base)
1102       return false;
1103   }
1104
1105   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1106     // Modified symbol references cannot be resolved.
1107     if (B->getKind() != MCSymbolRefExpr::VK_None)
1108       return false;
1109
1110     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1111     if (!B_Base)
1112       return false;
1113   }
1114
1115   // If there is no base, A and B have to be the same atom for this fixup to be
1116   // fully resolved.
1117   if (!BaseSymbol)
1118     return A_Base == B_Base;
1119
1120   // Otherwise, B must be missing and A must be the base.
1121   return !B_Base && BaseSymbol == A_Base;
1122 }
1123
1124 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
1125   // Non-temporary labels should always be visible to the linker.
1126   if (!SD->getSymbol().isTemporary())
1127     return true;
1128
1129   // Absolute temporary labels are never visible.
1130   if (!SD->getFragment())
1131     return false;
1132
1133   // Otherwise, check if the section requires symbols even for temporary labels.
1134   return getBackend().doesSectionRequireSymbols(
1135     SD->getFragment()->getParent()->getSection());
1136 }
1137
1138 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
1139                                                    uint64_t Address) const {
1140   const MCSymbolData *Best = 0;
1141   for (MCAssembler::const_symbol_iterator it = symbol_begin(),
1142          ie = symbol_end(); it != ie; ++it) {
1143     // Ignore non-linker visible symbols.
1144     if (!isSymbolLinkerVisible(it))
1145       continue;
1146
1147     // Ignore symbols not in the same section.
1148     if (!it->getFragment() || it->getFragment()->getParent() != Section)
1149       continue;
1150
1151     // Otherwise, find the closest symbol preceding this address (ties are
1152     // resolved in favor of the last defined symbol).
1153     if (it->getAddress() <= Address &&
1154         (!Best || it->getAddress() >= Best->getAddress()))
1155       Best = it;
1156   }
1157
1158   return Best;
1159 }
1160
1161 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
1162   // Linker visible symbols define atoms.
1163   if (isSymbolLinkerVisible(SD))
1164     return SD;
1165
1166   // Absolute and undefined symbols have no defining atom.
1167   if (!SD->getFragment())
1168     return 0;
1169
1170   // Otherwise, search by address.
1171   return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
1172 }
1173
1174 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1175                                 MCDataFragment *DF,
1176                                 MCValue &Target, uint64_t &Value) const {
1177   if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1178     llvm_report_error("expected relocatable expression");
1179
1180   // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1181   // doesn't support small relocations, but then under what criteria does the
1182   // assembler allow symbol differences?
1183
1184   Value = Target.getConstant();
1185
1186   bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1187   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1188     if (A->getSymbol().isDefined())
1189       Value += getSymbolData(A->getSymbol()).getAddress();
1190     else
1191       IsResolved = false;
1192   }
1193   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1194     if (B->getSymbol().isDefined())
1195       Value -= getSymbolData(B->getSymbol()).getAddress();
1196     else
1197       IsResolved = false;
1198   }
1199
1200   // If we are using scattered symbols, determine whether this value is actually
1201   // resolved; scattering may cause atoms to move.
1202   if (IsResolved && getBackend().hasScatteredSymbols()) {
1203     if (getBackend().hasReliableSymbolDifference()) {
1204       // If this is a PCrel relocation, find the base atom (identified by its
1205       // symbol) that the fixup value is relative to.
1206       const MCSymbolData *BaseSymbol = 0;
1207       if (IsPCRel) {
1208         BaseSymbol = getAtomForAddress(
1209           DF->getParent(), DF->getAddress() + Fixup.Offset);
1210         if (!BaseSymbol)
1211           IsResolved = false;
1212       }
1213
1214       if (IsResolved)
1215         IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
1216                                                    BaseSymbol);
1217     } else {
1218       const MCSection *BaseSection = 0;
1219       if (IsPCRel)
1220         BaseSection = &DF->getParent()->getSection();
1221
1222       IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
1223                                                        BaseSection);
1224     }
1225   }
1226
1227   if (IsPCRel)
1228     Value -= DF->getAddress() + Fixup.Offset;
1229
1230   return IsResolved;
1231 }
1232
1233 void MCAssembler::LayoutSection(MCSectionData &SD) {
1234   MCAsmLayout Layout(*this);
1235   uint64_t Address = SD.getAddress();
1236
1237   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1238     MCFragment &F = *it;
1239
1240     F.setOffset(Address - SD.getAddress());
1241
1242     // Evaluate fragment size.
1243     switch (F.getKind()) {
1244     case MCFragment::FT_Align: {
1245       MCAlignFragment &AF = cast<MCAlignFragment>(F);
1246
1247       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1248       if (Size > AF.getMaxBytesToEmit())
1249         AF.setFileSize(0);
1250       else
1251         AF.setFileSize(Size);
1252       break;
1253     }
1254
1255     case MCFragment::FT_Data:
1256     case MCFragment::FT_Fill:
1257       F.setFileSize(F.getMaxFileSize());
1258       break;
1259
1260     case MCFragment::FT_Org: {
1261       MCOrgFragment &OF = cast<MCOrgFragment>(F);
1262
1263       int64_t TargetLocation;
1264       if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1265         llvm_report_error("expected assembly-time absolute expression");
1266
1267       // FIXME: We need a way to communicate this error.
1268       int64_t Offset = TargetLocation - F.getOffset();
1269       if (Offset < 0)
1270         llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1271                           "' (at offset '" + Twine(F.getOffset()) + "'");
1272
1273       F.setFileSize(Offset);
1274       break;
1275     }
1276
1277     case MCFragment::FT_ZeroFill: {
1278       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1279
1280       // Align the fragment offset; it is safe to adjust the offset freely since
1281       // this is only in virtual sections.
1282       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1283       F.setOffset(Address - SD.getAddress());
1284
1285       // FIXME: This is misnamed.
1286       F.setFileSize(ZFF.getSize());
1287       break;
1288     }
1289     }
1290
1291     Address += F.getFileSize();
1292   }
1293
1294   // Set the section sizes.
1295   SD.setSize(Address - SD.getAddress());
1296   if (isVirtualSection(SD.getSection()))
1297     SD.setFileSize(0);
1298   else
1299     SD.setFileSize(Address - SD.getAddress());
1300 }
1301
1302 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1303 /// bytes.  This returns the number of bytes written.  It may return 0 if
1304 /// the \arg Count is more than the maximum optimal nops.
1305 ///
1306 /// FIXME this is X86 32-bit specific and should move to a better place.
1307 static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
1308   static const uint8_t Nops[16][16] = {
1309     // nop
1310     {0x90},
1311     // xchg %ax,%ax
1312     {0x66, 0x90},
1313     // nopl (%[re]ax)
1314     {0x0f, 0x1f, 0x00},
1315     // nopl 0(%[re]ax)
1316     {0x0f, 0x1f, 0x40, 0x00},
1317     // nopl 0(%[re]ax,%[re]ax,1)
1318     {0x0f, 0x1f, 0x44, 0x00, 0x00},
1319     // nopw 0(%[re]ax,%[re]ax,1)
1320     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1321     // nopl 0L(%[re]ax)
1322     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1323     // nopl 0L(%[re]ax,%[re]ax,1)
1324     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1325     // nopw 0L(%[re]ax,%[re]ax,1)
1326     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1327     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1328     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1329     // nopl 0(%[re]ax,%[re]ax,1)
1330     // nopw 0(%[re]ax,%[re]ax,1)
1331     {0x0f, 0x1f, 0x44, 0x00, 0x00,
1332      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1333     // nopw 0(%[re]ax,%[re]ax,1)
1334     // nopw 0(%[re]ax,%[re]ax,1)
1335     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1336      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1337     // nopw 0(%[re]ax,%[re]ax,1)
1338     // nopl 0L(%[re]ax) */
1339     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1340      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1341     // nopl 0L(%[re]ax)
1342     // nopl 0L(%[re]ax)
1343     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1344      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1345     // nopl 0L(%[re]ax)
1346     // nopl 0L(%[re]ax,%[re]ax,1)
1347     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1348      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1349   };
1350
1351   if (Count > 15)
1352     return 0;
1353
1354   for (uint64_t i = 0; i < Count; i++)
1355     OW->Write8(uint8_t(Nops[Count - 1][i]));
1356
1357   return Count;
1358 }
1359
1360 /// WriteFileData - Write the \arg F data to the output file.
1361 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1362                           MCObjectWriter *OW) {
1363   uint64_t Start = OS.tell();
1364   (void) Start;
1365
1366   ++EmittedFragments;
1367
1368   // FIXME: Embed in fragments instead?
1369   switch (F.getKind()) {
1370   case MCFragment::FT_Align: {
1371     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1372     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1373
1374     // FIXME: This error shouldn't actually occur (the front end should emit
1375     // multiple .align directives to enforce the semantics it wants), but is
1376     // severe enough that we want to report it. How to handle this?
1377     if (Count * AF.getValueSize() != AF.getFileSize())
1378       llvm_report_error("undefined .align directive, value size '" +
1379                         Twine(AF.getValueSize()) +
1380                         "' is not a divisor of padding size '" +
1381                         Twine(AF.getFileSize()) + "'");
1382
1383     // See if we are aligning with nops, and if so do that first to try to fill
1384     // the Count bytes.  Then if that did not fill any bytes or there are any
1385     // bytes left to fill use the the Value and ValueSize to fill the rest.
1386     if (AF.getEmitNops()) {
1387       uint64_t NopByteCount = WriteNopData(Count, OW);
1388       Count -= NopByteCount;
1389     }
1390
1391     for (uint64_t i = 0; i != Count; ++i) {
1392       switch (AF.getValueSize()) {
1393       default:
1394         assert(0 && "Invalid size!");
1395       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
1396       case 2: OW->Write16(uint16_t(AF.getValue())); break;
1397       case 4: OW->Write32(uint32_t(AF.getValue())); break;
1398       case 8: OW->Write64(uint64_t(AF.getValue())); break;
1399       }
1400     }
1401     break;
1402   }
1403
1404   case MCFragment::FT_Data: {
1405     OS << cast<MCDataFragment>(F).getContents().str();
1406     break;
1407   }
1408
1409   case MCFragment::FT_Fill: {
1410     MCFillFragment &FF = cast<MCFillFragment>(F);
1411     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1412       switch (FF.getValueSize()) {
1413       default:
1414         assert(0 && "Invalid size!");
1415       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
1416       case 2: OW->Write16(uint16_t(FF.getValue())); break;
1417       case 4: OW->Write32(uint32_t(FF.getValue())); break;
1418       case 8: OW->Write64(uint64_t(FF.getValue())); break;
1419       }
1420     }
1421     break;
1422   }
1423
1424   case MCFragment::FT_Org: {
1425     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1426
1427     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1428       OW->Write8(uint8_t(OF.getValue()));
1429
1430     break;
1431   }
1432
1433   case MCFragment::FT_ZeroFill: {
1434     assert(0 && "Invalid zero fill fragment in concrete section!");
1435     break;
1436   }
1437   }
1438
1439   assert(OS.tell() - Start == F.getFileSize());
1440 }
1441
1442 /// WriteFileData - Write the \arg SD data to the output file.
1443 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1444                           MCObjectWriter *OW) {
1445   // Ignore virtual sections.
1446   if (isVirtualSection(SD.getSection())) {
1447     assert(SD.getFileSize() == 0);
1448     return;
1449   }
1450
1451   uint64_t Start = OS.tell();
1452   (void) Start;
1453
1454   for (MCSectionData::const_iterator it = SD.begin(),
1455          ie = SD.end(); it != ie; ++it)
1456     WriteFileData(OS, *it, OW);
1457
1458   // Add section padding.
1459   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1460   OW->WriteZeros(SD.getFileSize() - SD.getSize());
1461
1462   assert(OS.tell() - Start == SD.getFileSize());
1463 }
1464
1465 void MCAssembler::Finish() {
1466   DEBUG_WITH_TYPE("mc-dump", {
1467       llvm::errs() << "assembler backend - pre-layout\n--\n";
1468       dump(); });
1469
1470   // Layout until everything fits.
1471   while (LayoutOnce())
1472     continue;
1473
1474   DEBUG_WITH_TYPE("mc-dump", {
1475       llvm::errs() << "assembler backend - post-layout\n--\n";
1476       dump(); });
1477
1478   // FIXME: Factor out MCObjectWriter.
1479   bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1480   MachObjectWriter MOW(OS, Is64Bit);
1481
1482   // Allow the object writer a chance to perform post-layout binding (for
1483   // example, to set the index fields in the symbol data).
1484   MOW.ExecutePostLayoutBinding(*this);
1485
1486   // Evaluate and apply the fixups, generating relocation entries as necessary.
1487   //
1488   // FIXME: Share layout object.
1489   MCAsmLayout Layout(*this);
1490   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
1491     for (MCSectionData::iterator it2 = it->begin(),
1492            ie2 = it->end(); it2 != ie2; ++it2) {
1493       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1494       if (!DF)
1495         continue;
1496
1497       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1498              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1499         MCAsmFixup &Fixup = *it3;
1500
1501         // Evaluate the fixup.
1502         MCValue Target;
1503         uint64_t FixedValue;
1504         if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
1505           // The fixup was unresolved, we need a relocation. Inform the object
1506           // writer of the relocation, and give it an opportunity to adjust the
1507           // fixup value if need be.
1508           MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
1509         }
1510
1511         getBackend().ApplyFixup(Fixup, *DF, FixedValue);
1512       }
1513     }
1514   }
1515
1516   // Write the object file.
1517   MOW.WriteObject(*this);
1518
1519   OS.flush();
1520 }
1521
1522 bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1523   // FIXME: Share layout object.
1524   MCAsmLayout Layout(*this);
1525
1526   // Currently we only need to relax X86::reloc_pcrel_1byte.
1527   if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1528     return false;
1529
1530   // If we cannot resolve the fixup value, it requires relaxation.
1531   MCValue Target;
1532   uint64_t Value;
1533   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1534     return true;
1535
1536   // Otherwise, relax if the value is too big for a (signed) i8.
1537   return int64_t(Value) != int64_t(int8_t(Value));
1538 }
1539
1540 bool MCAssembler::LayoutOnce() {
1541   // Layout the concrete sections and fragments.
1542   uint64_t Address = 0;
1543   MCSectionData *Prev = 0;
1544   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1545     MCSectionData &SD = *it;
1546
1547     // Skip virtual sections.
1548     if (isVirtualSection(SD.getSection()))
1549       continue;
1550
1551     // Align this section if necessary by adding padding bytes to the previous
1552     // section.
1553     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1554       assert(Prev && "Missing prev section!");
1555       Prev->setFileSize(Prev->getFileSize() + Pad);
1556       Address += Pad;
1557     }
1558
1559     // Layout the section fragments and its size.
1560     SD.setAddress(Address);
1561     LayoutSection(SD);
1562     Address += SD.getFileSize();
1563
1564     Prev = &SD;
1565   }
1566
1567   // Layout the virtual sections.
1568   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1569     MCSectionData &SD = *it;
1570
1571     if (!isVirtualSection(SD.getSection()))
1572       continue;
1573
1574     // Align this section if necessary by adding padding bytes to the previous
1575     // section.
1576     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1577       Address += Pad;
1578
1579     SD.setAddress(Address);
1580     LayoutSection(SD);
1581     Address += SD.getSize();
1582   }
1583
1584   // Scan the fixups in order and relax any that don't fit.
1585   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1586     MCSectionData &SD = *it;
1587
1588     for (MCSectionData::iterator it2 = SD.begin(),
1589            ie2 = SD.end(); it2 != ie2; ++it2) {
1590       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1591       if (!DF)
1592         continue;
1593
1594       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1595              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1596         MCAsmFixup &Fixup = *it3;
1597
1598         // Check whether we need to relax this fixup.
1599         if (!FixupNeedsRelaxation(Fixup, DF))
1600           continue;
1601
1602         // Relax the instruction.
1603         //
1604         // FIXME: This is a huge temporary hack which just looks for x86
1605         // branches; the only thing we need to relax on x86 is
1606         // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1607         // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1608         // an individual MCInst.
1609         SmallVectorImpl<char> &C = DF->getContents();
1610         uint64_t PrevOffset = Fixup.Offset;
1611         unsigned Amt = 0;
1612
1613           // jcc instructions
1614         if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1615             unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1616           C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1617           C[Fixup.Offset-1] = char(0x0f);
1618           ++Fixup.Offset;
1619           Amt = 4;
1620
1621           // jmp rel8
1622         } else if (C[Fixup.Offset-1] == char(0xeb)) {
1623           C[Fixup.Offset-1] = char(0xe9);
1624           Amt = 3;
1625
1626         } else
1627           llvm_unreachable("unknown 1 byte pcrel instruction!");
1628
1629         Fixup.Value = MCBinaryExpr::Create(
1630           MCBinaryExpr::Sub, Fixup.Value,
1631           MCConstantExpr::Create(3, getContext()),
1632           getContext());
1633         C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1634         Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1635
1636         // Update the remaining fixups, which have slid.
1637         //
1638         // FIXME: This is bad for performance, but will be eliminated by the
1639         // move to MCInst specific fragments.
1640         ++it3;
1641         for (; it3 != ie3; ++it3)
1642           it3->Offset += Amt;
1643
1644         // Update all the symbols for this fragment, which may have slid.
1645         //
1646         // FIXME: This is really really bad for performance, but will be
1647         // eliminated by the move to MCInst specific fragments.
1648         for (MCAssembler::symbol_iterator it = symbol_begin(),
1649                ie = symbol_end(); it != ie; ++it) {
1650           MCSymbolData &SD = *it;
1651
1652           if (it->getFragment() != DF)
1653             continue;
1654
1655           if (SD.getOffset() > PrevOffset)
1656             SD.setOffset(SD.getOffset() + Amt);
1657         }
1658
1659         // Restart layout.
1660         //
1661         // FIXME: This is O(N^2), but will be eliminated once we have a smart
1662         // MCAsmLayout object.
1663         return true;
1664       }
1665     }
1666   }
1667
1668   return false;
1669 }
1670
1671 // Debugging methods
1672
1673 namespace llvm {
1674
1675 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1676   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1677      << " Kind:" << AF.Kind << ">";
1678   return OS;
1679 }
1680
1681 }
1682
1683 void MCFragment::dump() {
1684   raw_ostream &OS = llvm::errs();
1685
1686   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1687      << " FileSize:" << FileSize;
1688
1689   OS << ">";
1690 }
1691
1692 void MCAlignFragment::dump() {
1693   raw_ostream &OS = llvm::errs();
1694
1695   OS << "<MCAlignFragment ";
1696   this->MCFragment::dump();
1697   OS << "\n       ";
1698   OS << " Alignment:" << getAlignment()
1699      << " Value:" << getValue() << " ValueSize:" << getValueSize()
1700      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1701 }
1702
1703 void MCDataFragment::dump() {
1704   raw_ostream &OS = llvm::errs();
1705
1706   OS << "<MCDataFragment ";
1707   this->MCFragment::dump();
1708   OS << "\n       ";
1709   OS << " Contents:[";
1710   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1711     if (i) OS << ",";
1712     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1713   }
1714   OS << "] (" << getContents().size() << " bytes)";
1715
1716   if (!getFixups().empty()) {
1717     OS << ",\n       ";
1718     OS << " Fixups:[";
1719     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1720       if (it != fixup_begin()) OS << ",\n                ";
1721       OS << *it;
1722     }
1723     OS << "]";
1724   }
1725
1726   OS << ">";
1727 }
1728
1729 void MCFillFragment::dump() {
1730   raw_ostream &OS = llvm::errs();
1731
1732   OS << "<MCFillFragment ";
1733   this->MCFragment::dump();
1734   OS << "\n       ";
1735   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1736      << " Count:" << getCount() << ">";
1737 }
1738
1739 void MCOrgFragment::dump() {
1740   raw_ostream &OS = llvm::errs();
1741
1742   OS << "<MCOrgFragment ";
1743   this->MCFragment::dump();
1744   OS << "\n       ";
1745   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1746 }
1747
1748 void MCZeroFillFragment::dump() {
1749   raw_ostream &OS = llvm::errs();
1750
1751   OS << "<MCZeroFillFragment ";
1752   this->MCFragment::dump();
1753   OS << "\n       ";
1754   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1755 }
1756
1757 void MCSectionData::dump() {
1758   raw_ostream &OS = llvm::errs();
1759
1760   OS << "<MCSectionData";
1761   OS << " Alignment:" << getAlignment() << " Address:" << Address
1762      << " Size:" << Size << " FileSize:" << FileSize
1763      << " Fragments:[\n      ";
1764   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1765     if (it != begin()) OS << ",\n      ";
1766     it->dump();
1767   }
1768   OS << "]>";
1769 }
1770
1771 void MCSymbolData::dump() {
1772   raw_ostream &OS = llvm::errs();
1773
1774   OS << "<MCSymbolData Symbol:" << getSymbol()
1775      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1776      << " Flags:" << getFlags() << " Index:" << getIndex();
1777   if (isCommon())
1778     OS << " (common, size:" << getCommonSize()
1779        << " align: " << getCommonAlignment() << ")";
1780   if (isExternal())
1781     OS << " (external)";
1782   if (isPrivateExtern())
1783     OS << " (private extern)";
1784   OS << ">";
1785 }
1786
1787 void MCAssembler::dump() {
1788   raw_ostream &OS = llvm::errs();
1789
1790   OS << "<MCAssembler\n";
1791   OS << "  Sections:[\n    ";
1792   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1793     if (it != begin()) OS << ",\n    ";
1794     it->dump();
1795   }
1796   OS << "],\n";
1797   OS << "  Symbols:[";
1798
1799   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1800     if (it != symbol_begin()) OS << ",\n           ";
1801     it->dump();
1802   }
1803   OS << "]>\n";
1804 }