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