1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
31 #include "../Target/X86/X86FixupKinds.h"
36 class MachObjectWriter;
38 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
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.
46 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
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) {
53 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
54 return (SMO.getType() == MCSectionMachO::S_ZEROFILL);
57 static unsigned getFixupKindLog2Size(unsigned Kind) {
59 default: llvm_unreachable("invalid fixup kind!");
60 case X86::reloc_pcrel_1byte:
61 case FK_Data_1: return 0;
62 case FK_Data_2: return 1;
63 case X86::reloc_pcrel_4byte:
64 case X86::reloc_riprel_4byte:
65 case FK_Data_4: return 2;
66 case FK_Data_8: return 3;
70 static bool isFixupKindPCRel(unsigned Kind) {
74 case X86::reloc_pcrel_1byte:
75 case X86::reloc_pcrel_4byte:
76 case X86::reloc_riprel_4byte:
81 class MCObjectWriter {
82 MCObjectWriter(const MCObjectWriter &); // DO NOT IMPLEMENT
83 void operator=(const MCObjectWriter &); // DO NOT IMPLEMENT
88 unsigned IsLittleEndian : 1;
90 protected: // Can only create subclasses.
91 MCObjectWriter(raw_ostream &_OS, bool _IsLittleEndian)
92 : OS(_OS), IsLittleEndian(_IsLittleEndian) {}
93 virtual ~MCObjectWriter();
97 bool isLittleEndian() { return IsLittleEndian; }
99 raw_ostream &getStream() { return OS; }
101 /// @name Binary Output Methods
104 void Write8(uint8_t Value) {
108 void WriteLE16(uint16_t Value) {
109 Write8(uint8_t(Value >> 0));
110 Write8(uint8_t(Value >> 8));
113 void WriteLE32(uint32_t Value) {
114 WriteLE16(uint16_t(Value >> 0));
115 WriteLE16(uint16_t(Value >> 16));
118 void WriteLE64(uint64_t Value) {
119 WriteLE32(uint32_t(Value >> 0));
120 WriteLE32(uint32_t(Value >> 32));
123 void WriteBE16(uint16_t Value) {
124 Write8(uint8_t(Value >> 8));
125 Write8(uint8_t(Value >> 0));
128 void WriteBE32(uint32_t Value) {
129 WriteBE16(uint16_t(Value >> 16));
130 WriteBE16(uint16_t(Value >> 0));
133 void WriteBE64(uint64_t Value) {
134 WriteBE32(uint32_t(Value >> 32));
135 WriteBE32(uint32_t(Value >> 0));
138 void Write16(uint16_t Value) {
145 void Write32(uint32_t Value) {
152 void Write64(uint64_t Value) {
159 void WriteZeros(unsigned N) {
160 const char Zeros[16] = { 0 };
162 for (unsigned i = 0, e = N / 16; i != e; ++i)
163 OS << StringRef(Zeros, 16);
165 OS << StringRef(Zeros, N % 16);
168 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
171 WriteZeros(ZeroFillSize - Str.size());
177 MCObjectWriter::~MCObjectWriter() {
180 class MachObjectWriter : public MCObjectWriter {
181 // See <mach-o/loader.h>.
183 Header_Magic32 = 0xFEEDFACE,
184 Header_Magic64 = 0xFEEDFACF
190 SegmentLoadCommand32Size = 56,
191 SegmentLoadCommand64Size = 72,
194 SymtabLoadCommandSize = 24,
195 DysymtabLoadCommandSize = 80,
198 RelocationInfoSize = 8
201 enum HeaderFileType {
206 HF_SubsectionsViaSymbols = 0x2000
209 enum LoadCommandType {
216 // See <mach-o/nlist.h>.
217 enum SymbolTypeType {
218 STT_Undefined = 0x00,
223 enum SymbolTypeFlags {
224 // If any of these bits are set, then the entry is a stab entry number (see
225 // <mach-o/stab.h>. Otherwise the other masks apply.
226 STF_StabsEntryMask = 0xe0,
230 STF_PrivateExtern = 0x10
233 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
235 enum IndirectSymbolFlags {
236 ISF_Local = 0x80000000,
237 ISF_Absolute = 0x40000000
240 /// RelocationFlags - Special flags for addresses.
241 enum RelocationFlags {
242 RF_Scattered = 0x80000000
245 enum RelocationInfoType {
249 RIT_PreboundLazyPointer = 3,
250 RIT_LocalDifference = 4
253 /// MachSymbolData - Helper struct for containing some precomputed information
255 struct MachSymbolData {
256 MCSymbolData *SymbolData;
257 uint64_t StringIndex;
258 uint8_t SectionIndex;
260 // Support lexicographic sorting.
261 bool operator<(const MachSymbolData &RHS) const {
262 const std::string &Name = SymbolData->getSymbol().getName();
263 return Name < RHS.SymbolData->getSymbol().getName();
267 unsigned Is64Bit : 1;
269 /// @name Relocation Data
272 struct MachRelocationEntry {
277 llvm::DenseMap<const MCSectionData*,
278 std::vector<MachRelocationEntry> > Relocations;
281 /// @name Symbol Table Data
283 SmallString<256> StringTable;
284 std::vector<MachSymbolData> LocalSymbolData;
285 std::vector<MachSymbolData> ExternalSymbolData;
286 std::vector<MachSymbolData> UndefinedSymbolData;
291 MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLittleEndian = true)
292 : MCObjectWriter(_OS, _IsLittleEndian), Is64Bit(_Is64Bit) {
295 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
296 bool SubsectionsViaSymbols) {
299 if (SubsectionsViaSymbols)
300 Flags |= HF_SubsectionsViaSymbols;
302 // struct mach_header (28 bytes) or
303 // struct mach_header_64 (32 bytes)
305 uint64_t Start = OS.tell();
308 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
310 // FIXME: Support cputype.
311 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
312 // FIXME: Support cpusubtype.
313 Write32(MachO::CPUSubType_I386_ALL);
315 Write32(NumLoadCommands); // Object files have a single load command, the
317 Write32(LoadCommandsSize);
320 Write32(0); // reserved
322 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
325 /// WriteSegmentLoadCommand - Write a segment load command.
327 /// \arg NumSections - The number of sections in this segment.
328 /// \arg SectionDataSize - The total size of the sections.
329 void WriteSegmentLoadCommand(unsigned NumSections,
331 uint64_t SectionDataStartOffset,
332 uint64_t SectionDataSize) {
333 // struct segment_command (56 bytes) or
334 // struct segment_command_64 (72 bytes)
336 uint64_t Start = OS.tell();
339 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
340 SegmentLoadCommand32Size;
341 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
342 Write32(SegmentLoadCommandSize +
343 NumSections * (Is64Bit ? Section64Size : Section32Size));
347 Write64(0); // vmaddr
348 Write64(VMSize); // vmsize
349 Write64(SectionDataStartOffset); // file offset
350 Write64(SectionDataSize); // file size
352 Write32(0); // vmaddr
353 Write32(VMSize); // vmsize
354 Write32(SectionDataStartOffset); // file offset
355 Write32(SectionDataSize); // file size
357 Write32(0x7); // maxprot
358 Write32(0x7); // initprot
359 Write32(NumSections);
362 assert(OS.tell() - Start == SegmentLoadCommandSize);
365 void WriteSection(const MCSectionData &SD, uint64_t FileOffset,
366 uint64_t RelocationsStart, unsigned NumRelocations) {
367 // The offset is unused for virtual sections.
368 if (isVirtualSection(SD.getSection())) {
369 assert(SD.getFileSize() == 0 && "Invalid file size!");
373 // struct section (68 bytes) or
374 // struct section_64 (80 bytes)
376 uint64_t Start = OS.tell();
379 // FIXME: cast<> support!
380 const MCSectionMachO &Section =
381 static_cast<const MCSectionMachO&>(SD.getSection());
382 WriteBytes(Section.getSectionName(), 16);
383 WriteBytes(Section.getSegmentName(), 16);
385 Write64(SD.getAddress()); // address
386 Write64(SD.getSize()); // size
388 Write32(SD.getAddress()); // address
389 Write32(SD.getSize()); // size
393 unsigned Flags = Section.getTypeAndAttributes();
394 if (SD.hasInstructions())
395 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
397 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
398 Write32(Log2_32(SD.getAlignment()));
399 Write32(NumRelocations ? RelocationsStart : 0);
400 Write32(NumRelocations);
402 Write32(0); // reserved1
403 Write32(Section.getStubSize()); // reserved2
405 Write32(0); // reserved3
407 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
410 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
411 uint32_t StringTableOffset,
412 uint32_t StringTableSize) {
413 // struct symtab_command (24 bytes)
415 uint64_t Start = OS.tell();
419 Write32(SymtabLoadCommandSize);
420 Write32(SymbolOffset);
422 Write32(StringTableOffset);
423 Write32(StringTableSize);
425 assert(OS.tell() - Start == SymtabLoadCommandSize);
428 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
429 uint32_t NumLocalSymbols,
430 uint32_t FirstExternalSymbol,
431 uint32_t NumExternalSymbols,
432 uint32_t FirstUndefinedSymbol,
433 uint32_t NumUndefinedSymbols,
434 uint32_t IndirectSymbolOffset,
435 uint32_t NumIndirectSymbols) {
436 // struct dysymtab_command (80 bytes)
438 uint64_t Start = OS.tell();
441 Write32(LCT_Dysymtab);
442 Write32(DysymtabLoadCommandSize);
443 Write32(FirstLocalSymbol);
444 Write32(NumLocalSymbols);
445 Write32(FirstExternalSymbol);
446 Write32(NumExternalSymbols);
447 Write32(FirstUndefinedSymbol);
448 Write32(NumUndefinedSymbols);
449 Write32(0); // tocoff
451 Write32(0); // modtaboff
452 Write32(0); // nmodtab
453 Write32(0); // extrefsymoff
454 Write32(0); // nextrefsyms
455 Write32(IndirectSymbolOffset);
456 Write32(NumIndirectSymbols);
457 Write32(0); // extreloff
458 Write32(0); // nextrel
459 Write32(0); // locreloff
460 Write32(0); // nlocrel
462 assert(OS.tell() - Start == DysymtabLoadCommandSize);
465 void WriteNlist(MachSymbolData &MSD) {
466 MCSymbolData &Data = *MSD.SymbolData;
467 const MCSymbol &Symbol = Data.getSymbol();
469 uint16_t Flags = Data.getFlags();
470 uint32_t Address = 0;
472 // Set the N_TYPE bits. See <mach-o/nlist.h>.
474 // FIXME: Are the prebound or indirect fields possible here?
475 if (Symbol.isUndefined())
476 Type = STT_Undefined;
477 else if (Symbol.isAbsolute())
482 // FIXME: Set STAB bits.
484 if (Data.isPrivateExtern())
485 Type |= STF_PrivateExtern;
488 if (Data.isExternal() || Symbol.isUndefined())
489 Type |= STF_External;
491 // Compute the symbol address.
492 if (Symbol.isDefined()) {
493 if (Symbol.isAbsolute()) {
494 llvm_unreachable("FIXME: Not yet implemented!");
496 Address = Data.getAddress();
498 } else if (Data.isCommon()) {
499 // Common symbols are encoded with the size in the address
500 // field, and their alignment in the flags.
501 Address = Data.getCommonSize();
503 // Common alignment is packed into the 'desc' bits.
504 if (unsigned Align = Data.getCommonAlignment()) {
505 unsigned Log2Size = Log2_32(Align);
506 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
508 llvm_report_error("invalid 'common' alignment '" +
510 // FIXME: Keep this mask with the SymbolFlags enumeration.
511 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
515 // struct nlist (12 bytes)
517 Write32(MSD.StringIndex);
519 Write8(MSD.SectionIndex);
521 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
530 void RecordScatteredRelocation(MCAssembler &Asm, MCFragment &Fragment,
531 const MCAsmFixup &Fixup, MCValue Target,
532 uint64_t &FixedValue) {
533 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
534 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
535 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
536 unsigned Type = RIT_Vanilla;
539 const MCSymbol *A = &Target.getSymA()->getSymbol();
540 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
542 if (!A_SD->getFragment())
543 llvm_report_error("symbol '" + A->getName() +
544 "' can not be undefined in a subtraction expression");
546 uint32_t Value = A_SD->getAddress();
549 if (const MCSymbolRefExpr *B = Target.getSymB()) {
550 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
552 if (!B_SD->getFragment())
553 llvm_report_error("symbol '" + B->getSymbol().getName() +
554 "' can not be undefined in a subtraction expression");
556 // Select the appropriate difference relocation type.
558 // Note that there is no longer any semantic difference between these two
559 // relocation types from the linkers point of view, this is done solely
560 // for pedantic compatibility with 'as'.
561 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
562 Value2 = B_SD->getAddress();
565 // Relocations are written out in reverse order, so the PAIR comes first.
566 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
567 MachRelocationEntry MRE;
568 MRE.Word0 = ((0 << 0) |
574 Relocations[Fragment.getParent()].push_back(MRE);
577 MachRelocationEntry MRE;
578 MRE.Word0 = ((Address << 0) |
584 Relocations[Fragment.getParent()].push_back(MRE);
587 void RecordRelocation(MCAssembler &Asm, MCDataFragment &Fragment,
588 const MCAsmFixup &Fixup, MCValue Target,
589 uint64_t &FixedValue) {
590 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
591 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
593 // If this is a difference or a defined symbol plus an offset, then we need
594 // a scattered relocation entry.
595 uint32_t Offset = Target.getConstant();
597 Offset += 1 << Log2Size;
598 if (Target.getSymB() ||
599 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
601 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
606 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
609 unsigned IsExtern = 0;
612 if (Target.isAbsolute()) { // constant
613 // SymbolNum of 0 indicates the absolute section.
615 // FIXME: Currently, these are never generated (see code below). I cannot
616 // find a case where they are actually emitted.
620 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
621 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
623 if (Symbol->isUndefined()) {
625 Index = SD->getIndex();
628 // The index is the section ordinal.
632 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
633 for (; it != ie; ++it, ++Index)
634 if (&*it == SD->getFragment()->getParent())
636 assert(it != ie && "Unable to find section index!");
637 Value = SD->getAddress();
643 // struct relocation_info (8 bytes)
644 MachRelocationEntry MRE;
646 MRE.Word1 = ((Index << 0) |
651 Relocations[Fragment.getParent()].push_back(MRE);
654 void BindIndirectSymbols(MCAssembler &Asm) {
655 // This is the point where 'as' creates actual symbols for indirect symbols
656 // (in the following two passes). It would be easier for us to do this
657 // sooner when we see the attribute, but that makes getting the order in the
658 // symbol table much more complicated than it is worth.
660 // FIXME: Revisit this when the dust settles.
662 // Bind non lazy symbol pointers first.
663 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
664 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
665 // FIXME: cast<> support!
666 const MCSectionMachO &Section =
667 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
669 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
672 Asm.getOrCreateSymbolData(*it->Symbol);
675 // Then lazy symbol pointers and symbol stubs.
676 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
677 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
678 // FIXME: cast<> support!
679 const MCSectionMachO &Section =
680 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
682 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
683 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
686 // Set the symbol type to undefined lazy, but only on construction.
688 // FIXME: Do not hardcode.
690 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
692 Entry.setFlags(Entry.getFlags() | 0x0001);
696 /// ComputeSymbolTable - Compute the symbol table data
698 /// \param StringTable [out] - The string table data.
699 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
701 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
702 std::vector<MachSymbolData> &LocalSymbolData,
703 std::vector<MachSymbolData> &ExternalSymbolData,
704 std::vector<MachSymbolData> &UndefinedSymbolData) {
705 // Build section lookup table.
706 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
708 for (MCAssembler::iterator it = Asm.begin(),
709 ie = Asm.end(); it != ie; ++it, ++Index)
710 SectionIndexMap[&it->getSection()] = Index;
711 assert(Index <= 256 && "Too many sections!");
713 // Index 0 is always the empty string.
714 StringMap<uint64_t> StringIndexMap;
715 StringTable += '\x00';
717 // Build the symbol arrays and the string table, but only for non-local
720 // The particular order that we collect the symbols and create the string
721 // table, then sort the symbols is chosen to match 'as'. Even though it
722 // doesn't matter for correctness, this is important for letting us diff .o
724 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
725 ie = Asm.symbol_end(); it != ie; ++it) {
726 const MCSymbol &Symbol = it->getSymbol();
728 // Ignore non-linker visible symbols.
729 if (!Asm.isSymbolLinkerVisible(it))
732 if (!it->isExternal() && !Symbol.isUndefined())
735 uint64_t &Entry = StringIndexMap[Symbol.getName()];
737 Entry = StringTable.size();
738 StringTable += Symbol.getName();
739 StringTable += '\x00';
744 MSD.StringIndex = Entry;
746 if (Symbol.isUndefined()) {
747 MSD.SectionIndex = 0;
748 UndefinedSymbolData.push_back(MSD);
749 } else if (Symbol.isAbsolute()) {
750 MSD.SectionIndex = 0;
751 ExternalSymbolData.push_back(MSD);
753 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
754 assert(MSD.SectionIndex && "Invalid section index!");
755 ExternalSymbolData.push_back(MSD);
759 // Now add the data for local symbols.
760 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
761 ie = Asm.symbol_end(); it != ie; ++it) {
762 const MCSymbol &Symbol = it->getSymbol();
764 // Ignore non-linker visible symbols.
765 if (!Asm.isSymbolLinkerVisible(it))
768 if (it->isExternal() || Symbol.isUndefined())
771 uint64_t &Entry = StringIndexMap[Symbol.getName()];
773 Entry = StringTable.size();
774 StringTable += Symbol.getName();
775 StringTable += '\x00';
780 MSD.StringIndex = Entry;
782 if (Symbol.isAbsolute()) {
783 MSD.SectionIndex = 0;
784 LocalSymbolData.push_back(MSD);
786 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
787 assert(MSD.SectionIndex && "Invalid section index!");
788 LocalSymbolData.push_back(MSD);
792 // External and undefined symbols are required to be in lexicographic order.
793 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
794 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
796 // Set the symbol indices.
798 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
799 LocalSymbolData[i].SymbolData->setIndex(Index++);
800 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
801 ExternalSymbolData[i].SymbolData->setIndex(Index++);
802 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
803 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
805 // The string table is padded to a multiple of 4.
806 while (StringTable.size() % 4)
807 StringTable += '\x00';
810 void ExecutePostLayoutBinding(MCAssembler &Asm) {
811 // Create symbol data for any indirect symbols.
812 BindIndirectSymbols(Asm);
814 // Compute symbol table information and bind symbol indices.
815 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
816 UndefinedSymbolData);
819 void WriteObject(const MCAssembler &Asm) {
820 unsigned NumSections = Asm.size();
822 // The section data starts after the header, the segment load command (and
823 // section headers) and the symbol table.
824 unsigned NumLoadCommands = 1;
825 uint64_t LoadCommandsSize = Is64Bit ?
826 SegmentLoadCommand64Size + NumSections * Section64Size :
827 SegmentLoadCommand32Size + NumSections * Section32Size;
829 // Add the symbol table load command sizes, if used.
830 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
831 UndefinedSymbolData.size();
833 NumLoadCommands += 2;
834 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
837 // Compute the total size of the section data, as well as its file size and
839 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
841 uint64_t SectionDataSize = 0;
842 uint64_t SectionDataFileSize = 0;
844 for (MCAssembler::const_iterator it = Asm.begin(),
845 ie = Asm.end(); it != ie; ++it) {
846 const MCSectionData &SD = *it;
848 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
850 if (isVirtualSection(SD.getSection()))
853 SectionDataSize = std::max(SectionDataSize,
854 SD.getAddress() + SD.getSize());
855 SectionDataFileSize = std::max(SectionDataFileSize,
856 SD.getAddress() + SD.getFileSize());
859 // The section data is padded to 4 bytes.
861 // FIXME: Is this machine dependent?
862 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
863 SectionDataFileSize += SectionDataPadding;
865 // Write the prolog, starting with the header and load command...
866 WriteHeader(NumLoadCommands, LoadCommandsSize,
867 Asm.getSubsectionsViaSymbols());
868 WriteSegmentLoadCommand(NumSections, VMSize,
869 SectionDataStart, SectionDataSize);
871 // ... and then the section headers.
872 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
873 for (MCAssembler::const_iterator it = Asm.begin(),
874 ie = Asm.end(); it != ie; ++it) {
875 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
876 unsigned NumRelocs = Relocs.size();
877 uint64_t SectionStart = SectionDataStart + it->getAddress();
878 WriteSection(*it, SectionStart, RelocTableEnd, NumRelocs);
879 RelocTableEnd += NumRelocs * RelocationInfoSize;
882 // Write the symbol table load command, if used.
884 unsigned FirstLocalSymbol = 0;
885 unsigned NumLocalSymbols = LocalSymbolData.size();
886 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
887 unsigned NumExternalSymbols = ExternalSymbolData.size();
888 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
889 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
890 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
891 unsigned NumSymTabSymbols =
892 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
893 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
894 uint64_t IndirectSymbolOffset = 0;
896 // If used, the indirect symbols are written after the section data.
897 if (NumIndirectSymbols)
898 IndirectSymbolOffset = RelocTableEnd;
900 // The symbol table is written after the indirect symbol data.
901 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
903 // The string table is written after symbol table.
904 uint64_t StringTableOffset =
905 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
907 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
908 StringTableOffset, StringTable.size());
910 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
911 FirstExternalSymbol, NumExternalSymbols,
912 FirstUndefinedSymbol, NumUndefinedSymbols,
913 IndirectSymbolOffset, NumIndirectSymbols);
916 // Write the actual section data.
917 for (MCAssembler::const_iterator it = Asm.begin(),
918 ie = Asm.end(); it != ie; ++it)
919 WriteFileData(OS, *it, this);
921 // Write the extra padding.
922 WriteZeros(SectionDataPadding);
924 // Write the relocation entries.
925 for (MCAssembler::const_iterator it = Asm.begin(),
926 ie = Asm.end(); it != ie; ++it) {
927 // Write the section relocation entries, in reverse order to match 'as'
928 // (approximately, the exact algorithm is more complicated than this).
929 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
930 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
931 Write32(Relocs[e - i - 1].Word0);
932 Write32(Relocs[e - i - 1].Word1);
936 // Write the symbol table data, if used.
938 // Write the indirect symbol entries.
939 for (MCAssembler::const_indirect_symbol_iterator
940 it = Asm.indirect_symbol_begin(),
941 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
942 // Indirect symbols in the non lazy symbol pointer section have some
944 const MCSectionMachO &Section =
945 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
946 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
947 // If this symbol is defined and internal, mark it as such.
948 if (it->Symbol->isDefined() &&
949 !Asm.getSymbolData(*it->Symbol).isExternal()) {
950 uint32_t Flags = ISF_Local;
951 if (it->Symbol->isAbsolute())
952 Flags |= ISF_Absolute;
958 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
961 // FIXME: Check that offsets match computed ones.
963 // Write the symbol table entries.
964 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
965 WriteNlist(LocalSymbolData[i]);
966 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
967 WriteNlist(ExternalSymbolData[i]);
968 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
969 WriteNlist(UndefinedSymbolData[i]);
971 // Write the string table.
972 OS << StringTable.str();
979 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
982 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
985 FileSize(~UINT64_C(0))
988 Parent->getFragmentList().push_back(this);
991 MCFragment::~MCFragment() {
994 uint64_t MCFragment::getAddress() const {
995 assert(getParent() && "Missing Section!");
996 return getParent()->getAddress() + Offset;
1001 MCSectionData::MCSectionData() : Section(0) {}
1003 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
1004 : Section(&_Section),
1006 Address(~UINT64_C(0)),
1008 FileSize(~UINT64_C(0)),
1009 HasInstructions(false)
1012 A->getSectionList().push_back(this);
1017 MCSymbolData::MCSymbolData() : Symbol(0) {}
1019 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
1020 uint64_t _Offset, MCAssembler *A)
1021 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
1022 IsExternal(false), IsPrivateExtern(false),
1023 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
1026 A->getSymbolList().push_back(this);
1031 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
1033 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
1037 MCAssembler::~MCAssembler() {
1040 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
1041 const MCAsmFixup &Fixup,
1042 const MCDataFragment *DF,
1043 const MCValue Target,
1044 const MCSection *BaseSection) {
1045 // The effective fixup address is
1046 // addr(atom(A)) + offset(A)
1047 // - addr(atom(B)) - offset(B)
1048 // - addr(<base symbol>) + <fixup offset from base symbol>
1049 // and the offsets are not relocatable, so the fixup is fully resolved when
1050 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
1052 // The simple (Darwin, except on x86_64) way of dealing with this was to
1053 // assume that any reference to a temporary symbol *must* be a temporary
1054 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
1055 // relocation to a temporary symbol (in the same section) is fully
1056 // resolved. This also works in conjunction with absolutized .set, which
1057 // requires the compiler to use .set to absolutize the differences between
1058 // symbols which the compiler knows to be assembly time constants, so we don't
1059 // need to worry about consider symbol differences fully resolved.
1061 // Non-relative fixups are only resolved if constant.
1063 return Target.isAbsolute();
1065 // Otherwise, relative fixups are only resolved if not a difference and the
1066 // target is a temporary in the same section.
1067 if (Target.isAbsolute() || Target.getSymB())
1070 const MCSymbol *A = &Target.getSymA()->getSymbol();
1071 if (!A->isTemporary() || !A->isInSection() ||
1072 &A->getSection() != BaseSection)
1078 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
1079 const MCAsmFixup &Fixup,
1080 const MCDataFragment *DF,
1081 const MCValue Target,
1082 const MCSymbolData *BaseSymbol) {
1083 // The effective fixup address is
1084 // addr(atom(A)) + offset(A)
1085 // - addr(atom(B)) - offset(B)
1086 // - addr(BaseSymbol) + <fixup offset from base symbol>
1087 // and the offsets are not relocatable, so the fixup is fully resolved when
1088 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
1090 // Note that "false" is almost always conservatively correct (it means we emit
1091 // a relocation which is unnecessary), except when it would force us to emit a
1092 // relocation which the target cannot encode.
1094 const MCSymbolData *A_Base = 0, *B_Base = 0;
1095 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1096 // Modified symbol references cannot be resolved.
1097 if (A->getKind() != MCSymbolRefExpr::VK_None)
1100 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1105 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1106 // Modified symbol references cannot be resolved.
1107 if (B->getKind() != MCSymbolRefExpr::VK_None)
1110 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1115 // If there is no base, A and B have to be the same atom for this fixup to be
1118 return A_Base == B_Base;
1120 // Otherwise, B must be missing and A must be the base.
1121 return !B_Base && BaseSymbol == A_Base;
1124 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
1125 // Non-temporary labels should always be visible to the linker.
1126 if (!SD->getSymbol().isTemporary())
1129 // Absolute temporary labels are never visible.
1130 if (!SD->getFragment())
1133 // Otherwise, check if the section requires symbols even for temporary labels.
1134 return getBackend().doesSectionRequireSymbols(
1135 SD->getFragment()->getParent()->getSection());
1138 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
1139 uint64_t Address) const {
1140 const MCSymbolData *Best = 0;
1141 for (MCAssembler::const_symbol_iterator it = symbol_begin(),
1142 ie = symbol_end(); it != ie; ++it) {
1143 // Ignore non-linker visible symbols.
1144 if (!isSymbolLinkerVisible(it))
1147 // Ignore symbols not in the same section.
1148 if (!it->getFragment() || it->getFragment()->getParent() != Section)
1151 // Otherwise, find the closest symbol preceding this address (ties are
1152 // resolved in favor of the last defined symbol).
1153 if (it->getAddress() <= Address &&
1154 (!Best || it->getAddress() >= Best->getAddress()))
1161 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
1162 // Linker visible symbols define atoms.
1163 if (isSymbolLinkerVisible(SD))
1166 // Absolute and undefined symbols have no defining atom.
1167 if (!SD->getFragment())
1170 // Otherwise, search by address.
1171 return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
1174 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1176 MCValue &Target, uint64_t &Value) const {
1177 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1178 llvm_report_error("expected relocatable expression");
1180 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1181 // doesn't support small relocations, but then under what criteria does the
1182 // assembler allow symbol differences?
1184 Value = Target.getConstant();
1186 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1187 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1188 if (A->getSymbol().isDefined())
1189 Value += getSymbolData(A->getSymbol()).getAddress();
1193 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1194 if (B->getSymbol().isDefined())
1195 Value -= getSymbolData(B->getSymbol()).getAddress();
1200 // If we are using scattered symbols, determine whether this value is actually
1201 // resolved; scattering may cause atoms to move.
1202 if (IsResolved && getBackend().hasScatteredSymbols()) {
1203 if (getBackend().hasReliableSymbolDifference()) {
1204 // If this is a PCrel relocation, find the base atom (identified by its
1205 // symbol) that the fixup value is relative to.
1206 const MCSymbolData *BaseSymbol = 0;
1208 BaseSymbol = getAtomForAddress(
1209 DF->getParent(), DF->getAddress() + Fixup.Offset);
1215 IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
1218 const MCSection *BaseSection = 0;
1220 BaseSection = &DF->getParent()->getSection();
1222 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
1228 Value -= DF->getAddress() + Fixup.Offset;
1233 void MCAssembler::LayoutSection(MCSectionData &SD) {
1234 MCAsmLayout Layout(*this);
1235 uint64_t Address = SD.getAddress();
1237 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1238 MCFragment &F = *it;
1240 F.setOffset(Address - SD.getAddress());
1242 // Evaluate fragment size.
1243 switch (F.getKind()) {
1244 case MCFragment::FT_Align: {
1245 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1247 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1248 if (Size > AF.getMaxBytesToEmit())
1251 AF.setFileSize(Size);
1255 case MCFragment::FT_Data:
1256 case MCFragment::FT_Fill:
1257 F.setFileSize(F.getMaxFileSize());
1260 case MCFragment::FT_Org: {
1261 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1263 int64_t TargetLocation;
1264 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1265 llvm_report_error("expected assembly-time absolute expression");
1267 // FIXME: We need a way to communicate this error.
1268 int64_t Offset = TargetLocation - F.getOffset();
1270 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1271 "' (at offset '" + Twine(F.getOffset()) + "'");
1273 F.setFileSize(Offset);
1277 case MCFragment::FT_ZeroFill: {
1278 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1280 // Align the fragment offset; it is safe to adjust the offset freely since
1281 // this is only in virtual sections.
1282 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1283 F.setOffset(Address - SD.getAddress());
1285 // FIXME: This is misnamed.
1286 F.setFileSize(ZFF.getSize());
1291 Address += F.getFileSize();
1294 // Set the section sizes.
1295 SD.setSize(Address - SD.getAddress());
1296 if (isVirtualSection(SD.getSection()))
1299 SD.setFileSize(Address - SD.getAddress());
1302 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1303 /// bytes. This returns the number of bytes written. It may return 0 if
1304 /// the \arg Count is more than the maximum optimal nops.
1306 /// FIXME this is X86 32-bit specific and should move to a better place.
1307 static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
1308 static const uint8_t Nops[16][16] = {
1316 {0x0f, 0x1f, 0x40, 0x00},
1317 // nopl 0(%[re]ax,%[re]ax,1)
1318 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1319 // nopw 0(%[re]ax,%[re]ax,1)
1320 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1322 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1323 // nopl 0L(%[re]ax,%[re]ax,1)
1324 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1325 // nopw 0L(%[re]ax,%[re]ax,1)
1326 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1327 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1328 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1329 // nopl 0(%[re]ax,%[re]ax,1)
1330 // nopw 0(%[re]ax,%[re]ax,1)
1331 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1332 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1333 // nopw 0(%[re]ax,%[re]ax,1)
1334 // nopw 0(%[re]ax,%[re]ax,1)
1335 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1336 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1337 // nopw 0(%[re]ax,%[re]ax,1)
1338 // nopl 0L(%[re]ax) */
1339 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1340 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1343 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1344 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1346 // nopl 0L(%[re]ax,%[re]ax,1)
1347 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1348 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1354 for (uint64_t i = 0; i < Count; i++)
1355 OW->Write8(uint8_t(Nops[Count - 1][i]));
1360 /// WriteFileData - Write the \arg F data to the output file.
1361 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1362 MCObjectWriter *OW) {
1363 uint64_t Start = OS.tell();
1368 // FIXME: Embed in fragments instead?
1369 switch (F.getKind()) {
1370 case MCFragment::FT_Align: {
1371 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1372 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1374 // FIXME: This error shouldn't actually occur (the front end should emit
1375 // multiple .align directives to enforce the semantics it wants), but is
1376 // severe enough that we want to report it. How to handle this?
1377 if (Count * AF.getValueSize() != AF.getFileSize())
1378 llvm_report_error("undefined .align directive, value size '" +
1379 Twine(AF.getValueSize()) +
1380 "' is not a divisor of padding size '" +
1381 Twine(AF.getFileSize()) + "'");
1383 // See if we are aligning with nops, and if so do that first to try to fill
1384 // the Count bytes. Then if that did not fill any bytes or there are any
1385 // bytes left to fill use the the Value and ValueSize to fill the rest.
1386 if (AF.getEmitNops()) {
1387 uint64_t NopByteCount = WriteNopData(Count, OW);
1388 Count -= NopByteCount;
1391 for (uint64_t i = 0; i != Count; ++i) {
1392 switch (AF.getValueSize()) {
1394 assert(0 && "Invalid size!");
1395 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
1396 case 2: OW->Write16(uint16_t(AF.getValue())); break;
1397 case 4: OW->Write32(uint32_t(AF.getValue())); break;
1398 case 8: OW->Write64(uint64_t(AF.getValue())); break;
1404 case MCFragment::FT_Data: {
1405 OS << cast<MCDataFragment>(F).getContents().str();
1409 case MCFragment::FT_Fill: {
1410 MCFillFragment &FF = cast<MCFillFragment>(F);
1411 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1412 switch (FF.getValueSize()) {
1414 assert(0 && "Invalid size!");
1415 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
1416 case 2: OW->Write16(uint16_t(FF.getValue())); break;
1417 case 4: OW->Write32(uint32_t(FF.getValue())); break;
1418 case 8: OW->Write64(uint64_t(FF.getValue())); break;
1424 case MCFragment::FT_Org: {
1425 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1427 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1428 OW->Write8(uint8_t(OF.getValue()));
1433 case MCFragment::FT_ZeroFill: {
1434 assert(0 && "Invalid zero fill fragment in concrete section!");
1439 assert(OS.tell() - Start == F.getFileSize());
1442 /// WriteFileData - Write the \arg SD data to the output file.
1443 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1444 MCObjectWriter *OW) {
1445 // Ignore virtual sections.
1446 if (isVirtualSection(SD.getSection())) {
1447 assert(SD.getFileSize() == 0);
1451 uint64_t Start = OS.tell();
1454 for (MCSectionData::const_iterator it = SD.begin(),
1455 ie = SD.end(); it != ie; ++it)
1456 WriteFileData(OS, *it, OW);
1458 // Add section padding.
1459 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1460 OW->WriteZeros(SD.getFileSize() - SD.getSize());
1462 assert(OS.tell() - Start == SD.getFileSize());
1465 void MCAssembler::Finish() {
1466 DEBUG_WITH_TYPE("mc-dump", {
1467 llvm::errs() << "assembler backend - pre-layout\n--\n";
1470 // Layout until everything fits.
1471 while (LayoutOnce())
1474 DEBUG_WITH_TYPE("mc-dump", {
1475 llvm::errs() << "assembler backend - post-layout\n--\n";
1478 // FIXME: Factor out MCObjectWriter.
1479 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1480 MachObjectWriter MOW(OS, Is64Bit);
1482 // Allow the object writer a chance to perform post-layout binding (for
1483 // example, to set the index fields in the symbol data).
1484 MOW.ExecutePostLayoutBinding(*this);
1486 // Evaluate and apply the fixups, generating relocation entries as necessary.
1488 // FIXME: Share layout object.
1489 MCAsmLayout Layout(*this);
1490 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
1491 for (MCSectionData::iterator it2 = it->begin(),
1492 ie2 = it->end(); it2 != ie2; ++it2) {
1493 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1497 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1498 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1499 MCAsmFixup &Fixup = *it3;
1501 // Evaluate the fixup.
1503 uint64_t FixedValue;
1504 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
1505 // The fixup was unresolved, we need a relocation. Inform the object
1506 // writer of the relocation, and give it an opportunity to adjust the
1507 // fixup value if need be.
1508 MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
1511 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
1516 // Write the object file.
1517 MOW.WriteObject(*this);
1522 bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1523 // FIXME: Share layout object.
1524 MCAsmLayout Layout(*this);
1526 // Currently we only need to relax X86::reloc_pcrel_1byte.
1527 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1530 // If we cannot resolve the fixup value, it requires relaxation.
1533 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1536 // Otherwise, relax if the value is too big for a (signed) i8.
1537 return int64_t(Value) != int64_t(int8_t(Value));
1540 bool MCAssembler::LayoutOnce() {
1541 // Layout the concrete sections and fragments.
1542 uint64_t Address = 0;
1543 MCSectionData *Prev = 0;
1544 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1545 MCSectionData &SD = *it;
1547 // Skip virtual sections.
1548 if (isVirtualSection(SD.getSection()))
1551 // Align this section if necessary by adding padding bytes to the previous
1553 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1554 assert(Prev && "Missing prev section!");
1555 Prev->setFileSize(Prev->getFileSize() + Pad);
1559 // Layout the section fragments and its size.
1560 SD.setAddress(Address);
1562 Address += SD.getFileSize();
1567 // Layout the virtual sections.
1568 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1569 MCSectionData &SD = *it;
1571 if (!isVirtualSection(SD.getSection()))
1574 // Align this section if necessary by adding padding bytes to the previous
1576 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1579 SD.setAddress(Address);
1581 Address += SD.getSize();
1584 // Scan the fixups in order and relax any that don't fit.
1585 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1586 MCSectionData &SD = *it;
1588 for (MCSectionData::iterator it2 = SD.begin(),
1589 ie2 = SD.end(); it2 != ie2; ++it2) {
1590 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1594 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1595 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1596 MCAsmFixup &Fixup = *it3;
1598 // Check whether we need to relax this fixup.
1599 if (!FixupNeedsRelaxation(Fixup, DF))
1602 // Relax the instruction.
1604 // FIXME: This is a huge temporary hack which just looks for x86
1605 // branches; the only thing we need to relax on x86 is
1606 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1607 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1608 // an individual MCInst.
1609 SmallVectorImpl<char> &C = DF->getContents();
1610 uint64_t PrevOffset = Fixup.Offset;
1614 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1615 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1616 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1617 C[Fixup.Offset-1] = char(0x0f);
1622 } else if (C[Fixup.Offset-1] == char(0xeb)) {
1623 C[Fixup.Offset-1] = char(0xe9);
1627 llvm_unreachable("unknown 1 byte pcrel instruction!");
1629 Fixup.Value = MCBinaryExpr::Create(
1630 MCBinaryExpr::Sub, Fixup.Value,
1631 MCConstantExpr::Create(3, getContext()),
1633 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1634 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1636 // Update the remaining fixups, which have slid.
1638 // FIXME: This is bad for performance, but will be eliminated by the
1639 // move to MCInst specific fragments.
1641 for (; it3 != ie3; ++it3)
1644 // Update all the symbols for this fragment, which may have slid.
1646 // FIXME: This is really really bad for performance, but will be
1647 // eliminated by the move to MCInst specific fragments.
1648 for (MCAssembler::symbol_iterator it = symbol_begin(),
1649 ie = symbol_end(); it != ie; ++it) {
1650 MCSymbolData &SD = *it;
1652 if (it->getFragment() != DF)
1655 if (SD.getOffset() > PrevOffset)
1656 SD.setOffset(SD.getOffset() + Amt);
1661 // FIXME: This is O(N^2), but will be eliminated once we have a smart
1662 // MCAsmLayout object.
1671 // Debugging methods
1675 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1676 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1677 << " Kind:" << AF.Kind << ">";
1683 void MCFragment::dump() {
1684 raw_ostream &OS = llvm::errs();
1686 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1687 << " FileSize:" << FileSize;
1692 void MCAlignFragment::dump() {
1693 raw_ostream &OS = llvm::errs();
1695 OS << "<MCAlignFragment ";
1696 this->MCFragment::dump();
1698 OS << " Alignment:" << getAlignment()
1699 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1700 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1703 void MCDataFragment::dump() {
1704 raw_ostream &OS = llvm::errs();
1706 OS << "<MCDataFragment ";
1707 this->MCFragment::dump();
1709 OS << " Contents:[";
1710 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1712 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1714 OS << "] (" << getContents().size() << " bytes)";
1716 if (!getFixups().empty()) {
1719 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1720 if (it != fixup_begin()) OS << ",\n ";
1729 void MCFillFragment::dump() {
1730 raw_ostream &OS = llvm::errs();
1732 OS << "<MCFillFragment ";
1733 this->MCFragment::dump();
1735 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1736 << " Count:" << getCount() << ">";
1739 void MCOrgFragment::dump() {
1740 raw_ostream &OS = llvm::errs();
1742 OS << "<MCOrgFragment ";
1743 this->MCFragment::dump();
1745 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1748 void MCZeroFillFragment::dump() {
1749 raw_ostream &OS = llvm::errs();
1751 OS << "<MCZeroFillFragment ";
1752 this->MCFragment::dump();
1754 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1757 void MCSectionData::dump() {
1758 raw_ostream &OS = llvm::errs();
1760 OS << "<MCSectionData";
1761 OS << " Alignment:" << getAlignment() << " Address:" << Address
1762 << " Size:" << Size << " FileSize:" << FileSize
1763 << " Fragments:[\n ";
1764 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1765 if (it != begin()) OS << ",\n ";
1771 void MCSymbolData::dump() {
1772 raw_ostream &OS = llvm::errs();
1774 OS << "<MCSymbolData Symbol:" << getSymbol()
1775 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1776 << " Flags:" << getFlags() << " Index:" << getIndex();
1778 OS << " (common, size:" << getCommonSize()
1779 << " align: " << getCommonAlignment() << ")";
1781 OS << " (external)";
1782 if (isPrivateExtern())
1783 OS << " (private extern)";
1787 void MCAssembler::dump() {
1788 raw_ostream &OS = llvm::errs();
1790 OS << "<MCAssembler\n";
1791 OS << " Sections:[\n ";
1792 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1793 if (it != begin()) OS << ",\n ";
1799 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1800 if (it != symbol_begin()) OS << ",\n ";