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