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.
45 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
46 MachObjectWriter &MOW);
48 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
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) {
54 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
55 return (SMO.getType() == MCSectionMachO::S_ZEROFILL);
58 static unsigned getFixupKindLog2Size(unsigned 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;
71 static bool isFixupKindPCRel(unsigned Kind) {
75 case X86::reloc_pcrel_1byte:
76 case X86::reloc_pcrel_4byte:
77 case X86::reloc_riprel_4byte:
82 class MachObjectWriter {
83 // See <mach-o/loader.h>.
85 Header_Magic32 = 0xFEEDFACE,
86 Header_Magic64 = 0xFEEDFACF
92 SegmentLoadCommand32Size = 56,
93 SegmentLoadCommand64Size = 72,
96 SymtabLoadCommandSize = 24,
97 DysymtabLoadCommandSize = 80,
100 RelocationInfoSize = 8
103 enum HeaderFileType {
108 HF_SubsectionsViaSymbols = 0x2000
111 enum LoadCommandType {
118 // See <mach-o/nlist.h>.
119 enum SymbolTypeType {
120 STT_Undefined = 0x00,
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,
132 STF_PrivateExtern = 0x10
135 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
137 enum IndirectSymbolFlags {
138 ISF_Local = 0x80000000,
139 ISF_Absolute = 0x40000000
142 /// RelocationFlags - Special flags for addresses.
143 enum RelocationFlags {
144 RF_Scattered = 0x80000000
147 enum RelocationInfoType {
151 RIT_PreboundLazyPointer = 3,
152 RIT_LocalDifference = 4
155 /// MachSymbolData - Helper struct for containing some precomputed information
157 struct MachSymbolData {
158 MCSymbolData *SymbolData;
159 uint64_t StringIndex;
160 uint8_t SectionIndex;
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();
170 unsigned Is64Bit : 1;
173 /// @name Relocation Data
176 struct MachRelocationEntry {
181 llvm::DenseMap<const MCSectionData*,
182 std::vector<MachRelocationEntry> > Relocations;
185 /// @name Symbol Table Data
187 SmallString<256> StringTable;
188 std::vector<MachSymbolData> LocalSymbolData;
189 std::vector<MachSymbolData> ExternalSymbolData;
190 std::vector<MachSymbolData> UndefinedSymbolData;
195 MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLSB = true)
196 : OS(_OS), Is64Bit(_Is64Bit), IsLSB(_IsLSB) {
199 /// @name Helper Methods
202 void Write8(uint8_t Value) {
206 void Write16(uint16_t Value) {
208 Write8(uint8_t(Value >> 0));
209 Write8(uint8_t(Value >> 8));
211 Write8(uint8_t(Value >> 8));
212 Write8(uint8_t(Value >> 0));
216 void Write32(uint32_t Value) {
218 Write16(uint16_t(Value >> 0));
219 Write16(uint16_t(Value >> 16));
221 Write16(uint16_t(Value >> 16));
222 Write16(uint16_t(Value >> 0));
226 void Write64(uint64_t Value) {
228 Write32(uint32_t(Value >> 0));
229 Write32(uint32_t(Value >> 32));
231 Write32(uint32_t(Value >> 32));
232 Write32(uint32_t(Value >> 0));
236 void WriteZeros(unsigned N) {
237 const char Zeros[16] = { 0 };
239 for (unsigned i = 0, e = N / 16; i != e; ++i)
240 OS << StringRef(Zeros, 16);
242 OS << StringRef(Zeros, N % 16);
245 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
248 WriteZeros(ZeroFillSize - Str.size());
253 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
254 bool SubsectionsViaSymbols) {
257 if (SubsectionsViaSymbols)
258 Flags |= HF_SubsectionsViaSymbols;
260 // struct mach_header (28 bytes) or
261 // struct mach_header_64 (32 bytes)
263 uint64_t Start = OS.tell();
266 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
268 // FIXME: Support cputype.
269 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
270 // FIXME: Support cpusubtype.
271 Write32(MachO::CPUSubType_I386_ALL);
273 Write32(NumLoadCommands); // Object files have a single load command, the
275 Write32(LoadCommandsSize);
278 Write32(0); // reserved
280 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
283 /// WriteSegmentLoadCommand - Write a segment load command.
285 /// \arg NumSections - The number of sections in this segment.
286 /// \arg SectionDataSize - The total size of the sections.
287 void WriteSegmentLoadCommand(unsigned NumSections,
289 uint64_t SectionDataStartOffset,
290 uint64_t SectionDataSize) {
291 // struct segment_command (56 bytes) or
292 // struct segment_command_64 (72 bytes)
294 uint64_t Start = OS.tell();
297 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
298 SegmentLoadCommand32Size;
299 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
300 Write32(SegmentLoadCommandSize +
301 NumSections * (Is64Bit ? Section64Size : Section32Size));
305 Write64(0); // vmaddr
306 Write64(VMSize); // vmsize
307 Write64(SectionDataStartOffset); // file offset
308 Write64(SectionDataSize); // file size
310 Write32(0); // vmaddr
311 Write32(VMSize); // vmsize
312 Write32(SectionDataStartOffset); // file offset
313 Write32(SectionDataSize); // file size
315 Write32(0x7); // maxprot
316 Write32(0x7); // initprot
317 Write32(NumSections);
320 assert(OS.tell() - Start == SegmentLoadCommandSize);
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!");
331 // struct section (68 bytes) or
332 // struct section_64 (80 bytes)
334 uint64_t Start = OS.tell();
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);
343 Write64(SD.getAddress()); // address
344 Write64(SD.getSize()); // size
346 Write32(SD.getAddress()); // address
347 Write32(SD.getSize()); // size
351 unsigned Flags = Section.getTypeAndAttributes();
352 if (SD.hasInstructions())
353 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
355 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
356 Write32(Log2_32(SD.getAlignment()));
357 Write32(NumRelocations ? RelocationsStart : 0);
358 Write32(NumRelocations);
360 Write32(0); // reserved1
361 Write32(Section.getStubSize()); // reserved2
363 Write32(0); // reserved3
365 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
368 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
369 uint32_t StringTableOffset,
370 uint32_t StringTableSize) {
371 // struct symtab_command (24 bytes)
373 uint64_t Start = OS.tell();
377 Write32(SymtabLoadCommandSize);
378 Write32(SymbolOffset);
380 Write32(StringTableOffset);
381 Write32(StringTableSize);
383 assert(OS.tell() - Start == SymtabLoadCommandSize);
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)
396 uint64_t Start = OS.tell();
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
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
420 assert(OS.tell() - Start == DysymtabLoadCommandSize);
423 void WriteNlist(MachSymbolData &MSD) {
424 MCSymbolData &Data = *MSD.SymbolData;
425 const MCSymbol &Symbol = Data.getSymbol();
427 uint16_t Flags = Data.getFlags();
428 uint32_t Address = 0;
430 // Set the N_TYPE bits. See <mach-o/nlist.h>.
432 // FIXME: Are the prebound or indirect fields possible here?
433 if (Symbol.isUndefined())
434 Type = STT_Undefined;
435 else if (Symbol.isAbsolute())
440 // FIXME: Set STAB bits.
442 if (Data.isPrivateExtern())
443 Type |= STF_PrivateExtern;
446 if (Data.isExternal() || Symbol.isUndefined())
447 Type |= STF_External;
449 // Compute the symbol address.
450 if (Symbol.isDefined()) {
451 if (Symbol.isAbsolute()) {
452 llvm_unreachable("FIXME: Not yet implemented!");
454 Address = Data.getAddress();
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();
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!");
466 llvm_report_error("invalid 'common' alignment '" +
468 // FIXME: Keep this mask with the SymbolFlags enumeration.
469 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
473 // struct nlist (12 bytes)
475 Write32(MSD.StringIndex);
477 Write8(MSD.SectionIndex);
479 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
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;
497 const MCSymbol *A = &Target.getSymA()->getSymbol();
498 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
500 if (!A_SD->getFragment())
501 llvm_report_error("symbol '" + A->getName() +
502 "' can not be undefined in a subtraction expression");
504 uint32_t Value = A_SD->getAddress();
507 if (const MCSymbolRefExpr *B = Target.getSymB()) {
508 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
510 if (!B_SD->getFragment())
511 llvm_report_error("symbol '" + B->getSymbol().getName() +
512 "' can not be undefined in a subtraction expression");
514 // Select the appropriate difference relocation type.
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();
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) |
532 Relocations[Fragment.getParent()].push_back(MRE);
535 MachRelocationEntry MRE;
536 MRE.Word0 = ((Address << 0) |
542 Relocations[Fragment.getParent()].push_back(MRE);
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);
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();
555 Offset += 1 << Log2Size;
556 if (Target.getSymB() ||
557 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
559 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
564 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
567 unsigned IsExtern = 0;
570 if (Target.isAbsolute()) { // constant
571 // SymbolNum of 0 indicates the absolute section.
573 // FIXME: Currently, these are never generated (see code below). I cannot
574 // find a case where they are actually emitted.
578 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
579 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
581 if (Symbol->isUndefined()) {
583 Index = SD->getIndex();
586 // The index is the section ordinal.
590 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
591 for (; it != ie; ++it, ++Index)
592 if (&*it == SD->getFragment()->getParent())
594 assert(it != ie && "Unable to find section index!");
595 Value = SD->getAddress();
601 // struct relocation_info (8 bytes)
602 MachRelocationEntry MRE;
604 MRE.Word1 = ((Index << 0) |
609 Relocations[Fragment.getParent()].push_back(MRE);
612 void BindIndirectSymbols(MCAssembler &Asm) {
613 // This is the point where 'as' creates actual symbols for indirect symbols
614 // (in the following two passes). It would be easier for us to do this
615 // sooner when we see the attribute, but that makes getting the order in the
616 // symbol table much more complicated than it is worth.
618 // FIXME: Revisit this when the dust settles.
620 // Bind non lazy symbol pointers first.
621 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
622 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
623 // FIXME: cast<> support!
624 const MCSectionMachO &Section =
625 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
627 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
630 Asm.getOrCreateSymbolData(*it->Symbol);
633 // Then lazy symbol pointers and symbol stubs.
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());
640 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
641 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
644 // Set the symbol type to undefined lazy, but only on construction.
646 // FIXME: Do not hardcode.
648 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
650 Entry.setFlags(Entry.getFlags() | 0x0001);
654 /// ComputeSymbolTable - Compute the symbol table data
656 /// \param StringTable [out] - The string table data.
657 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
659 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
660 std::vector<MachSymbolData> &LocalSymbolData,
661 std::vector<MachSymbolData> &ExternalSymbolData,
662 std::vector<MachSymbolData> &UndefinedSymbolData) {
663 // Build section lookup table.
664 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
666 for (MCAssembler::iterator it = Asm.begin(),
667 ie = Asm.end(); it != ie; ++it, ++Index)
668 SectionIndexMap[&it->getSection()] = Index;
669 assert(Index <= 256 && "Too many sections!");
671 // Index 0 is always the empty string.
672 StringMap<uint64_t> StringIndexMap;
673 StringTable += '\x00';
675 // Build the symbol arrays and the string table, but only for non-local
678 // The particular order that we collect the symbols and create the string
679 // table, then sort the symbols is chosen to match 'as'. Even though it
680 // doesn't matter for correctness, this is important for letting us diff .o
682 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
683 ie = Asm.symbol_end(); it != ie; ++it) {
684 const MCSymbol &Symbol = it->getSymbol();
686 // Ignore non-linker visible symbols.
687 if (!Asm.isSymbolLinkerVisible(it))
690 if (!it->isExternal() && !Symbol.isUndefined())
693 uint64_t &Entry = StringIndexMap[Symbol.getName()];
695 Entry = StringTable.size();
696 StringTable += Symbol.getName();
697 StringTable += '\x00';
702 MSD.StringIndex = Entry;
704 if (Symbol.isUndefined()) {
705 MSD.SectionIndex = 0;
706 UndefinedSymbolData.push_back(MSD);
707 } else if (Symbol.isAbsolute()) {
708 MSD.SectionIndex = 0;
709 ExternalSymbolData.push_back(MSD);
711 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
712 assert(MSD.SectionIndex && "Invalid section index!");
713 ExternalSymbolData.push_back(MSD);
717 // Now add the data for local symbols.
718 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
719 ie = Asm.symbol_end(); it != ie; ++it) {
720 const MCSymbol &Symbol = it->getSymbol();
722 // Ignore non-linker visible symbols.
723 if (!Asm.isSymbolLinkerVisible(it))
726 if (it->isExternal() || Symbol.isUndefined())
729 uint64_t &Entry = StringIndexMap[Symbol.getName()];
731 Entry = StringTable.size();
732 StringTable += Symbol.getName();
733 StringTable += '\x00';
738 MSD.StringIndex = Entry;
740 if (Symbol.isAbsolute()) {
741 MSD.SectionIndex = 0;
742 LocalSymbolData.push_back(MSD);
744 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
745 assert(MSD.SectionIndex && "Invalid section index!");
746 LocalSymbolData.push_back(MSD);
750 // External and undefined symbols are required to be in lexicographic order.
751 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
752 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
754 // Set the symbol indices.
756 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
757 LocalSymbolData[i].SymbolData->setIndex(Index++);
758 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
759 ExternalSymbolData[i].SymbolData->setIndex(Index++);
760 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
761 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
763 // The string table is padded to a multiple of 4.
764 while (StringTable.size() % 4)
765 StringTable += '\x00';
768 void ExecutePostLayoutBinding(MCAssembler &Asm) {
769 // Create symbol data for any indirect symbols.
770 BindIndirectSymbols(Asm);
772 // Compute symbol table information and bind symbol indices.
773 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
774 UndefinedSymbolData);
777 void WriteObject(const MCAssembler &Asm) {
778 unsigned NumSections = Asm.size();
780 // The section data starts after the header, the segment load command (and
781 // section headers) and the symbol table.
782 unsigned NumLoadCommands = 1;
783 uint64_t LoadCommandsSize = Is64Bit ?
784 SegmentLoadCommand64Size + NumSections * Section64Size :
785 SegmentLoadCommand32Size + NumSections * Section32Size;
787 // Add the symbol table load command sizes, if used.
788 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
789 UndefinedSymbolData.size();
791 NumLoadCommands += 2;
792 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
795 // Compute the total size of the section data, as well as its file size and
797 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
799 uint64_t SectionDataSize = 0;
800 uint64_t SectionDataFileSize = 0;
802 for (MCAssembler::const_iterator it = Asm.begin(),
803 ie = Asm.end(); it != ie; ++it) {
804 const MCSectionData &SD = *it;
806 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
808 if (isVirtualSection(SD.getSection()))
811 SectionDataSize = std::max(SectionDataSize,
812 SD.getAddress() + SD.getSize());
813 SectionDataFileSize = std::max(SectionDataFileSize,
814 SD.getAddress() + SD.getFileSize());
817 // The section data is padded to 4 bytes.
819 // FIXME: Is this machine dependent?
820 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
821 SectionDataFileSize += SectionDataPadding;
823 // Write the prolog, starting with the header and load command...
824 WriteHeader(NumLoadCommands, LoadCommandsSize,
825 Asm.getSubsectionsViaSymbols());
826 WriteSegmentLoadCommand(NumSections, VMSize,
827 SectionDataStart, SectionDataSize);
829 // ... and then the section headers.
830 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
831 for (MCAssembler::const_iterator it = Asm.begin(),
832 ie = Asm.end(); it != ie; ++it) {
833 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
834 unsigned NumRelocs = Relocs.size();
835 uint64_t SectionStart = SectionDataStart + it->getAddress();
836 WriteSection(*it, SectionStart, RelocTableEnd, NumRelocs);
837 RelocTableEnd += NumRelocs * RelocationInfoSize;
840 // Write the symbol table load command, if used.
842 unsigned FirstLocalSymbol = 0;
843 unsigned NumLocalSymbols = LocalSymbolData.size();
844 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
845 unsigned NumExternalSymbols = ExternalSymbolData.size();
846 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
847 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
848 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
849 unsigned NumSymTabSymbols =
850 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
851 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
852 uint64_t IndirectSymbolOffset = 0;
854 // If used, the indirect symbols are written after the section data.
855 if (NumIndirectSymbols)
856 IndirectSymbolOffset = RelocTableEnd;
858 // The symbol table is written after the indirect symbol data.
859 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
861 // The string table is written after symbol table.
862 uint64_t StringTableOffset =
863 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
865 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
866 StringTableOffset, StringTable.size());
868 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
869 FirstExternalSymbol, NumExternalSymbols,
870 FirstUndefinedSymbol, NumUndefinedSymbols,
871 IndirectSymbolOffset, NumIndirectSymbols);
874 // Write the actual section data.
875 for (MCAssembler::const_iterator it = Asm.begin(),
876 ie = Asm.end(); it != ie; ++it)
877 WriteFileData(OS, *it, *this);
879 // Write the extra padding.
880 WriteZeros(SectionDataPadding);
882 // Write the relocation entries.
883 for (MCAssembler::const_iterator it = Asm.begin(),
884 ie = Asm.end(); it != ie; ++it) {
885 // Write the section relocation entries, in reverse order to match 'as'
886 // (approximately, the exact algorithm is more complicated than this).
887 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
888 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
889 Write32(Relocs[e - i - 1].Word0);
890 Write32(Relocs[e - i - 1].Word1);
894 // Write the symbol table data, if used.
896 // Write the indirect symbol entries.
897 for (MCAssembler::const_indirect_symbol_iterator
898 it = Asm.indirect_symbol_begin(),
899 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
900 // Indirect symbols in the non lazy symbol pointer section have some
902 const MCSectionMachO &Section =
903 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
904 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
905 // If this symbol is defined and internal, mark it as such.
906 if (it->Symbol->isDefined() &&
907 !Asm.getSymbolData(*it->Symbol).isExternal()) {
908 uint32_t Flags = ISF_Local;
909 if (it->Symbol->isAbsolute())
910 Flags |= ISF_Absolute;
916 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
919 // FIXME: Check that offsets match computed ones.
921 // Write the symbol table entries.
922 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
923 WriteNlist(LocalSymbolData[i]);
924 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
925 WriteNlist(ExternalSymbolData[i]);
926 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
927 WriteNlist(UndefinedSymbolData[i]);
929 // Write the string table.
930 OS << StringTable.str();
934 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF,
935 uint64_t FixedValue) {
936 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
938 // FIXME: Endianness assumption.
939 assert(Fixup.Offset + Size <= DF.getContents().size() &&
940 "Invalid fixup offset!");
941 for (unsigned i = 0; i != Size; ++i)
942 DF.getContents()[Fixup.Offset + i] = uint8_t(FixedValue >> (i * 8));
948 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
951 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
954 FileSize(~UINT64_C(0))
957 Parent->getFragmentList().push_back(this);
960 MCFragment::~MCFragment() {
963 uint64_t MCFragment::getAddress() const {
964 assert(getParent() && "Missing Section!");
965 return getParent()->getAddress() + Offset;
970 MCSectionData::MCSectionData() : Section(0) {}
972 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
973 : Section(&_Section),
975 Address(~UINT64_C(0)),
977 FileSize(~UINT64_C(0)),
978 HasInstructions(false)
981 A->getSectionList().push_back(this);
986 MCSymbolData::MCSymbolData() : Symbol(0) {}
988 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
989 uint64_t _Offset, MCAssembler *A)
990 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
991 IsExternal(false), IsPrivateExtern(false),
992 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
995 A->getSymbolList().push_back(this);
1000 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
1002 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
1006 MCAssembler::~MCAssembler() {
1009 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
1010 const MCAsmFixup &Fixup,
1011 const MCDataFragment *DF,
1012 const MCValue Target,
1013 const MCSection *BaseSection) {
1014 // The effective fixup address is
1015 // addr(atom(A)) + offset(A)
1016 // - addr(atom(B)) - offset(B)
1017 // - addr(<base symbol>) + <fixup offset from base symbol>
1018 // and the offsets are not relocatable, so the fixup is fully resolved when
1019 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
1021 // The simple (Darwin, except on x86_64) way of dealing with this was to
1022 // assume that any reference to a temporary symbol *must* be a temporary
1023 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
1024 // relocation to a temporary symbol (in the same section) is fully
1025 // resolved. This also works in conjunction with absolutized .set, which
1026 // requires the compiler to use .set to absolutize the differences between
1027 // symbols which the compiler knows to be assembly time constants, so we don't
1028 // need to worry about consider symbol differences fully resolved.
1030 // Non-relative fixups are only resolved if constant.
1032 return Target.isAbsolute();
1034 // Otherwise, relative fixups are only resolved if not a difference and the
1035 // target is a temporary in the same section.
1036 if (Target.isAbsolute() || Target.getSymB())
1039 const MCSymbol *A = &Target.getSymA()->getSymbol();
1040 if (!A->isTemporary() || !A->isInSection() ||
1041 &A->getSection() != BaseSection)
1047 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
1048 const MCAsmFixup &Fixup,
1049 const MCDataFragment *DF,
1050 const MCValue Target,
1051 const MCSymbolData *BaseSymbol) {
1052 // The effective fixup address is
1053 // addr(atom(A)) + offset(A)
1054 // - addr(atom(B)) - offset(B)
1055 // - addr(BaseSymbol) + <fixup offset from base symbol>
1056 // and the offsets are not relocatable, so the fixup is fully resolved when
1057 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
1059 // Note that "false" is almost always conservatively correct (it means we emit
1060 // a relocation which is unnecessary), except when it would force us to emit a
1061 // relocation which the target cannot encode.
1063 const MCSymbolData *A_Base = 0, *B_Base = 0;
1064 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1065 // Modified symbol references cannot be resolved.
1066 if (A->getKind() != MCSymbolRefExpr::VK_None)
1069 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1074 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1075 // Modified symbol references cannot be resolved.
1076 if (B->getKind() != MCSymbolRefExpr::VK_None)
1079 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1084 // If there is no base, A and B have to be the same atom for this fixup to be
1087 return A_Base == B_Base;
1089 // Otherwise, B must be missing and A must be the base.
1090 return !B_Base && BaseSymbol == A_Base;
1093 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
1094 // Non-temporary labels should always be visible to the linker.
1095 if (!SD->getSymbol().isTemporary())
1098 // Absolute temporary labels are never visible.
1099 if (!SD->getFragment())
1102 // Otherwise, check if the section requires symbols even for temporary labels.
1103 return getBackend().doesSectionRequireSymbols(
1104 SD->getFragment()->getParent()->getSection());
1107 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
1108 uint64_t Address) const {
1109 const MCSymbolData *Best = 0;
1110 for (MCAssembler::const_symbol_iterator it = symbol_begin(),
1111 ie = symbol_end(); it != ie; ++it) {
1112 // Ignore non-linker visible symbols.
1113 if (!isSymbolLinkerVisible(it))
1116 // Ignore symbols not in the same section.
1117 if (!it->getFragment() || it->getFragment()->getParent() != Section)
1120 // Otherwise, find the closest symbol preceding this address (ties are
1121 // resolved in favor of the last defined symbol).
1122 if (it->getAddress() <= Address &&
1123 (!Best || it->getAddress() >= Best->getAddress()))
1130 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
1131 // Linker visible symbols define atoms.
1132 if (isSymbolLinkerVisible(SD))
1135 // Absolute and undefined symbols have no defining atom.
1136 if (!SD->getFragment())
1139 // Otherwise, search by address.
1140 return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
1143 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1145 MCValue &Target, uint64_t &Value) const {
1146 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1147 llvm_report_error("expected relocatable expression");
1149 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1150 // doesn't support small relocations, but then under what criteria does the
1151 // assembler allow symbol differences?
1153 Value = Target.getConstant();
1155 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1156 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1157 if (A->getSymbol().isDefined())
1158 Value += getSymbolData(A->getSymbol()).getAddress();
1162 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1163 if (B->getSymbol().isDefined())
1164 Value -= getSymbolData(B->getSymbol()).getAddress();
1169 // If we are using scattered symbols, determine whether this value is actually
1170 // resolved; scattering may cause atoms to move.
1171 if (IsResolved && getBackend().hasScatteredSymbols()) {
1172 if (getBackend().hasReliableSymbolDifference()) {
1173 // If this is a PCrel relocation, find the base atom (identified by its
1174 // symbol) that the fixup value is relative to.
1175 const MCSymbolData *BaseSymbol = 0;
1177 BaseSymbol = getAtomForAddress(
1178 DF->getParent(), DF->getAddress() + Fixup.Offset);
1184 IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
1187 const MCSection *BaseSection = 0;
1189 BaseSection = &DF->getParent()->getSection();
1191 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
1197 Value -= DF->getAddress() + Fixup.Offset;
1202 void MCAssembler::LayoutSection(MCSectionData &SD) {
1203 MCAsmLayout Layout(*this);
1204 uint64_t Address = SD.getAddress();
1206 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1207 MCFragment &F = *it;
1209 F.setOffset(Address - SD.getAddress());
1211 // Evaluate fragment size.
1212 switch (F.getKind()) {
1213 case MCFragment::FT_Align: {
1214 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1216 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1217 if (Size > AF.getMaxBytesToEmit())
1220 AF.setFileSize(Size);
1224 case MCFragment::FT_Data:
1225 case MCFragment::FT_Fill:
1226 F.setFileSize(F.getMaxFileSize());
1229 case MCFragment::FT_Org: {
1230 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1232 int64_t TargetLocation;
1233 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1234 llvm_report_error("expected assembly-time absolute expression");
1236 // FIXME: We need a way to communicate this error.
1237 int64_t Offset = TargetLocation - F.getOffset();
1239 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1240 "' (at offset '" + Twine(F.getOffset()) + "'");
1242 F.setFileSize(Offset);
1246 case MCFragment::FT_ZeroFill: {
1247 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1249 // Align the fragment offset; it is safe to adjust the offset freely since
1250 // this is only in virtual sections.
1251 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1252 F.setOffset(Address - SD.getAddress());
1254 // FIXME: This is misnamed.
1255 F.setFileSize(ZFF.getSize());
1260 Address += F.getFileSize();
1263 // Set the section sizes.
1264 SD.setSize(Address - SD.getAddress());
1265 if (isVirtualSection(SD.getSection()))
1268 SD.setFileSize(Address - SD.getAddress());
1271 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1272 /// bytes. This returns the number of bytes written. It may return 0 if
1273 /// the \arg Count is more than the maximum optimal nops.
1275 /// FIXME this is X86 32-bit specific and should move to a better place.
1276 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1277 static const uint8_t Nops[16][16] = {
1285 {0x0f, 0x1f, 0x40, 0x00},
1286 // nopl 0(%[re]ax,%[re]ax,1)
1287 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1288 // nopw 0(%[re]ax,%[re]ax,1)
1289 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1291 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1292 // nopl 0L(%[re]ax,%[re]ax,1)
1293 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1294 // nopw 0L(%[re]ax,%[re]ax,1)
1295 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1296 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1297 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1298 // nopl 0(%[re]ax,%[re]ax,1)
1299 // nopw 0(%[re]ax,%[re]ax,1)
1300 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1301 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1302 // nopw 0(%[re]ax,%[re]ax,1)
1303 // nopw 0(%[re]ax,%[re]ax,1)
1304 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1305 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1306 // nopw 0(%[re]ax,%[re]ax,1)
1307 // nopl 0L(%[re]ax) */
1308 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1309 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1312 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1313 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1315 // nopl 0L(%[re]ax,%[re]ax,1)
1316 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1317 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1323 for (uint64_t i = 0; i < Count; i++)
1324 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1329 /// WriteFileData - Write the \arg F data to the output file.
1330 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1331 MachObjectWriter &MOW) {
1332 uint64_t Start = OS.tell();
1337 // FIXME: Embed in fragments instead?
1338 switch (F.getKind()) {
1339 case MCFragment::FT_Align: {
1340 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1341 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1343 // FIXME: This error shouldn't actually occur (the front end should emit
1344 // multiple .align directives to enforce the semantics it wants), but is
1345 // severe enough that we want to report it. How to handle this?
1346 if (Count * AF.getValueSize() != AF.getFileSize())
1347 llvm_report_error("undefined .align directive, value size '" +
1348 Twine(AF.getValueSize()) +
1349 "' is not a divisor of padding size '" +
1350 Twine(AF.getFileSize()) + "'");
1352 // See if we are aligning with nops, and if so do that first to try to fill
1353 // the Count bytes. Then if that did not fill any bytes or there are any
1354 // bytes left to fill use the the Value and ValueSize to fill the rest.
1355 if (AF.getEmitNops()) {
1356 uint64_t NopByteCount = WriteNopData(Count, MOW);
1357 Count -= NopByteCount;
1360 for (uint64_t i = 0; i != Count; ++i) {
1361 switch (AF.getValueSize()) {
1363 assert(0 && "Invalid size!");
1364 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1365 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1366 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1367 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1373 case MCFragment::FT_Data: {
1374 OS << cast<MCDataFragment>(F).getContents().str();
1378 case MCFragment::FT_Fill: {
1379 MCFillFragment &FF = cast<MCFillFragment>(F);
1380 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1381 switch (FF.getValueSize()) {
1383 assert(0 && "Invalid size!");
1384 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1385 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1386 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1387 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1393 case MCFragment::FT_Org: {
1394 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1396 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1397 MOW.Write8(uint8_t(OF.getValue()));
1402 case MCFragment::FT_ZeroFill: {
1403 assert(0 && "Invalid zero fill fragment in concrete section!");
1408 assert(OS.tell() - Start == F.getFileSize());
1411 /// WriteFileData - Write the \arg SD data to the output file.
1412 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1413 MachObjectWriter &MOW) {
1414 // Ignore virtual sections.
1415 if (isVirtualSection(SD.getSection())) {
1416 assert(SD.getFileSize() == 0);
1420 uint64_t Start = OS.tell();
1423 for (MCSectionData::const_iterator it = SD.begin(),
1424 ie = SD.end(); it != ie; ++it)
1425 WriteFileData(OS, *it, MOW);
1427 // Add section padding.
1428 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1429 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1431 assert(OS.tell() - Start == SD.getFileSize());
1434 void MCAssembler::Finish() {
1435 DEBUG_WITH_TYPE("mc-dump", {
1436 llvm::errs() << "assembler backend - pre-layout\n--\n";
1439 // Layout until everything fits.
1440 while (LayoutOnce())
1443 DEBUG_WITH_TYPE("mc-dump", {
1444 llvm::errs() << "assembler backend - post-layout\n--\n";
1447 // FIXME: Factor out MCObjectWriter.
1448 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1449 MachObjectWriter MOW(OS, Is64Bit);
1451 // Allow the object writer a chance to perform post-layout binding (for
1452 // example, to set the index fields in the symbol data).
1453 MOW.ExecutePostLayoutBinding(*this);
1455 // Evaluate and apply the fixups, generating relocation entries as necessary.
1456 MCAsmLayout Layout(*this);
1457 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
1458 for (MCSectionData::iterator it2 = it->begin(),
1459 ie2 = it->end(); it2 != ie2; ++it2) {
1460 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1464 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1465 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1466 MCAsmFixup &Fixup = *it3;
1468 // Evaluate the fixup.
1470 uint64_t FixedValue;
1471 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
1472 // The fixup was unresolved, we need a relocation. Inform the object
1473 // writer of the relocation, and give it an opportunity to adjust the
1474 // fixup value if need be.
1475 MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
1478 MOW.ApplyFixup(Fixup, *DF, FixedValue);
1483 // Write the object file.
1484 MOW.WriteObject(*this);
1489 bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1490 // FIXME: Share layout object.
1491 MCAsmLayout Layout(*this);
1493 // Currently we only need to relax X86::reloc_pcrel_1byte.
1494 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1497 // If we cannot resolve the fixup value, it requires relaxation.
1500 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1503 // Otherwise, relax if the value is too big for a (signed) i8.
1504 return int64_t(Value) != int64_t(int8_t(Value));
1507 bool MCAssembler::LayoutOnce() {
1508 // Layout the concrete sections and fragments.
1509 uint64_t Address = 0;
1510 MCSectionData *Prev = 0;
1511 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1512 MCSectionData &SD = *it;
1514 // Skip virtual sections.
1515 if (isVirtualSection(SD.getSection()))
1518 // Align this section if necessary by adding padding bytes to the previous
1520 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1521 assert(Prev && "Missing prev section!");
1522 Prev->setFileSize(Prev->getFileSize() + Pad);
1526 // Layout the section fragments and its size.
1527 SD.setAddress(Address);
1529 Address += SD.getFileSize();
1534 // Layout the virtual sections.
1535 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1536 MCSectionData &SD = *it;
1538 if (!isVirtualSection(SD.getSection()))
1541 // Align this section if necessary by adding padding bytes to the previous
1543 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1546 SD.setAddress(Address);
1548 Address += SD.getSize();
1551 // Scan the fixups in order and relax any that don't fit.
1552 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1553 MCSectionData &SD = *it;
1555 for (MCSectionData::iterator it2 = SD.begin(),
1556 ie2 = SD.end(); it2 != ie2; ++it2) {
1557 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1561 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1562 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1563 MCAsmFixup &Fixup = *it3;
1565 // Check whether we need to relax this fixup.
1566 if (!FixupNeedsRelaxation(Fixup, DF))
1569 // Relax the instruction.
1571 // FIXME: This is a huge temporary hack which just looks for x86
1572 // branches; the only thing we need to relax on x86 is
1573 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1574 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1575 // an individual MCInst.
1576 SmallVectorImpl<char> &C = DF->getContents();
1577 uint64_t PrevOffset = Fixup.Offset;
1581 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1582 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1583 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1584 C[Fixup.Offset-1] = char(0x0f);
1589 } else if (C[Fixup.Offset-1] == char(0xeb)) {
1590 C[Fixup.Offset-1] = char(0xe9);
1594 llvm_unreachable("unknown 1 byte pcrel instruction!");
1596 Fixup.Value = MCBinaryExpr::Create(
1597 MCBinaryExpr::Sub, Fixup.Value,
1598 MCConstantExpr::Create(3, getContext()),
1600 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1601 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1603 // Update the remaining fixups, which have slid.
1605 // FIXME: This is bad for performance, but will be eliminated by the
1606 // move to MCInst specific fragments.
1608 for (; it3 != ie3; ++it3)
1611 // Update all the symbols for this fragment, which may have slid.
1613 // FIXME: This is really really bad for performance, but will be
1614 // eliminated by the move to MCInst specific fragments.
1615 for (MCAssembler::symbol_iterator it = symbol_begin(),
1616 ie = symbol_end(); it != ie; ++it) {
1617 MCSymbolData &SD = *it;
1619 if (it->getFragment() != DF)
1622 if (SD.getOffset() > PrevOffset)
1623 SD.setOffset(SD.getOffset() + Amt);
1628 // FIXME: This is O(N^2), but will be eliminated once we have a smart
1629 // MCAsmLayout object.
1638 // Debugging methods
1642 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1643 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1644 << " Kind:" << AF.Kind << ">";
1650 void MCFragment::dump() {
1651 raw_ostream &OS = llvm::errs();
1653 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1654 << " FileSize:" << FileSize;
1659 void MCAlignFragment::dump() {
1660 raw_ostream &OS = llvm::errs();
1662 OS << "<MCAlignFragment ";
1663 this->MCFragment::dump();
1665 OS << " Alignment:" << getAlignment()
1666 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1667 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1670 void MCDataFragment::dump() {
1671 raw_ostream &OS = llvm::errs();
1673 OS << "<MCDataFragment ";
1674 this->MCFragment::dump();
1676 OS << " Contents:[";
1677 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1679 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1681 OS << "] (" << getContents().size() << " bytes)";
1683 if (!getFixups().empty()) {
1686 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1687 if (it != fixup_begin()) OS << ",\n ";
1696 void MCFillFragment::dump() {
1697 raw_ostream &OS = llvm::errs();
1699 OS << "<MCFillFragment ";
1700 this->MCFragment::dump();
1702 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1703 << " Count:" << getCount() << ">";
1706 void MCOrgFragment::dump() {
1707 raw_ostream &OS = llvm::errs();
1709 OS << "<MCOrgFragment ";
1710 this->MCFragment::dump();
1712 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1715 void MCZeroFillFragment::dump() {
1716 raw_ostream &OS = llvm::errs();
1718 OS << "<MCZeroFillFragment ";
1719 this->MCFragment::dump();
1721 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1724 void MCSectionData::dump() {
1725 raw_ostream &OS = llvm::errs();
1727 OS << "<MCSectionData";
1728 OS << " Alignment:" << getAlignment() << " Address:" << Address
1729 << " Size:" << Size << " FileSize:" << FileSize
1730 << " Fragments:[\n ";
1731 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1732 if (it != begin()) OS << ",\n ";
1738 void MCSymbolData::dump() {
1739 raw_ostream &OS = llvm::errs();
1741 OS << "<MCSymbolData Symbol:" << getSymbol()
1742 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1743 << " Flags:" << getFlags() << " Index:" << getIndex();
1745 OS << " (common, size:" << getCommonSize()
1746 << " align: " << getCommonAlignment() << ")";
1748 OS << " (external)";
1749 if (isPrivateExtern())
1750 OS << " (private extern)";
1754 void MCAssembler::dump() {
1755 raw_ostream &OS = llvm::errs();
1757 OS << "<MCAssembler\n";
1758 OS << " Sections:[\n ";
1759 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1760 if (it != begin()) OS << ",\n ";
1766 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1767 if (it != symbol_begin()) OS << ",\n ";