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