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/MCObjectWriter.h"
15 #include "llvm/MC/MCSectionMachO.h"
16 #include "llvm/MC/MCSymbol.h"
17 #include "llvm/MC/MCValue.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MachO.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetAsmBackend.h"
32 #include "../Target/X86/X86FixupKinds.h"
37 class MachObjectWriter;
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
41 // FIXME FIXME FIXME: There are number of places in this file where we convert
42 // what is a 64-bit assembler value used for computation into a value in the
43 // object file, which may truncate it. We should detect that truncation where
44 // invalid and report errors back.
46 static unsigned getFixupKindLog2Size(unsigned Kind) {
48 default: llvm_unreachable("invalid fixup kind!");
49 case X86::reloc_pcrel_1byte:
50 case FK_Data_1: return 0;
51 case FK_Data_2: return 1;
52 case X86::reloc_pcrel_4byte:
53 case X86::reloc_riprel_4byte:
54 case FK_Data_4: return 2;
55 case FK_Data_8: return 3;
59 static bool isFixupKindPCRel(unsigned Kind) {
63 case X86::reloc_pcrel_1byte:
64 case X86::reloc_pcrel_4byte:
65 case X86::reloc_riprel_4byte:
70 class MachObjectWriter : public MCObjectWriter {
71 // See <mach-o/loader.h>.
73 Header_Magic32 = 0xFEEDFACE,
74 Header_Magic64 = 0xFEEDFACF
80 SegmentLoadCommand32Size = 56,
81 SegmentLoadCommand64Size = 72,
84 SymtabLoadCommandSize = 24,
85 DysymtabLoadCommandSize = 80,
88 RelocationInfoSize = 8
96 HF_SubsectionsViaSymbols = 0x2000
99 enum LoadCommandType {
106 // See <mach-o/nlist.h>.
107 enum SymbolTypeType {
108 STT_Undefined = 0x00,
113 enum SymbolTypeFlags {
114 // If any of these bits are set, then the entry is a stab entry number (see
115 // <mach-o/stab.h>. Otherwise the other masks apply.
116 STF_StabsEntryMask = 0xe0,
120 STF_PrivateExtern = 0x10
123 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
125 enum IndirectSymbolFlags {
126 ISF_Local = 0x80000000,
127 ISF_Absolute = 0x40000000
130 /// RelocationFlags - Special flags for addresses.
131 enum RelocationFlags {
132 RF_Scattered = 0x80000000
135 enum RelocationInfoType {
139 RIT_PreboundLazyPointer = 3,
140 RIT_LocalDifference = 4
143 /// MachSymbolData - Helper struct for containing some precomputed information
145 struct MachSymbolData {
146 MCSymbolData *SymbolData;
147 uint64_t StringIndex;
148 uint8_t SectionIndex;
150 // Support lexicographic sorting.
151 bool operator<(const MachSymbolData &RHS) const {
152 const std::string &Name = SymbolData->getSymbol().getName();
153 return Name < RHS.SymbolData->getSymbol().getName();
157 unsigned Is64Bit : 1;
159 /// @name Relocation Data
162 struct MachRelocationEntry {
167 llvm::DenseMap<const MCSectionData*,
168 std::vector<MachRelocationEntry> > Relocations;
171 /// @name Symbol Table Data
173 SmallString<256> StringTable;
174 std::vector<MachSymbolData> LocalSymbolData;
175 std::vector<MachSymbolData> ExternalSymbolData;
176 std::vector<MachSymbolData> UndefinedSymbolData;
181 MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLittleEndian = true)
182 : MCObjectWriter(_OS, _IsLittleEndian), Is64Bit(_Is64Bit) {
185 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
186 bool SubsectionsViaSymbols) {
189 if (SubsectionsViaSymbols)
190 Flags |= HF_SubsectionsViaSymbols;
192 // struct mach_header (28 bytes) or
193 // struct mach_header_64 (32 bytes)
195 uint64_t Start = OS.tell();
198 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
200 // FIXME: Support cputype.
201 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
202 // FIXME: Support cpusubtype.
203 Write32(MachO::CPUSubType_I386_ALL);
205 Write32(NumLoadCommands); // Object files have a single load command, the
207 Write32(LoadCommandsSize);
210 Write32(0); // reserved
212 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
215 /// WriteSegmentLoadCommand - Write a segment load command.
217 /// \arg NumSections - The number of sections in this segment.
218 /// \arg SectionDataSize - The total size of the sections.
219 void WriteSegmentLoadCommand(unsigned NumSections,
221 uint64_t SectionDataStartOffset,
222 uint64_t SectionDataSize) {
223 // struct segment_command (56 bytes) or
224 // struct segment_command_64 (72 bytes)
226 uint64_t Start = OS.tell();
229 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
230 SegmentLoadCommand32Size;
231 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
232 Write32(SegmentLoadCommandSize +
233 NumSections * (Is64Bit ? Section64Size : Section32Size));
237 Write64(0); // vmaddr
238 Write64(VMSize); // vmsize
239 Write64(SectionDataStartOffset); // file offset
240 Write64(SectionDataSize); // file size
242 Write32(0); // vmaddr
243 Write32(VMSize); // vmsize
244 Write32(SectionDataStartOffset); // file offset
245 Write32(SectionDataSize); // file size
247 Write32(0x7); // maxprot
248 Write32(0x7); // initprot
249 Write32(NumSections);
252 assert(OS.tell() - Start == SegmentLoadCommandSize);
255 void WriteSection(const MCAssembler &Asm, const MCSectionData &SD,
256 uint64_t FileOffset, uint64_t RelocationsStart,
257 unsigned NumRelocations) {
258 // The offset is unused for virtual sections.
259 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
260 assert(SD.getFileSize() == 0 && "Invalid file size!");
264 // struct section (68 bytes) or
265 // struct section_64 (80 bytes)
267 uint64_t Start = OS.tell();
270 // FIXME: cast<> support!
271 const MCSectionMachO &Section =
272 static_cast<const MCSectionMachO&>(SD.getSection());
273 WriteBytes(Section.getSectionName(), 16);
274 WriteBytes(Section.getSegmentName(), 16);
276 Write64(SD.getAddress()); // address
277 Write64(SD.getSize()); // size
279 Write32(SD.getAddress()); // address
280 Write32(SD.getSize()); // size
284 unsigned Flags = Section.getTypeAndAttributes();
285 if (SD.hasInstructions())
286 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
288 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
289 Write32(Log2_32(SD.getAlignment()));
290 Write32(NumRelocations ? RelocationsStart : 0);
291 Write32(NumRelocations);
293 Write32(0); // reserved1
294 Write32(Section.getStubSize()); // reserved2
296 Write32(0); // reserved3
298 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
301 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
302 uint32_t StringTableOffset,
303 uint32_t StringTableSize) {
304 // struct symtab_command (24 bytes)
306 uint64_t Start = OS.tell();
310 Write32(SymtabLoadCommandSize);
311 Write32(SymbolOffset);
313 Write32(StringTableOffset);
314 Write32(StringTableSize);
316 assert(OS.tell() - Start == SymtabLoadCommandSize);
319 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
320 uint32_t NumLocalSymbols,
321 uint32_t FirstExternalSymbol,
322 uint32_t NumExternalSymbols,
323 uint32_t FirstUndefinedSymbol,
324 uint32_t NumUndefinedSymbols,
325 uint32_t IndirectSymbolOffset,
326 uint32_t NumIndirectSymbols) {
327 // struct dysymtab_command (80 bytes)
329 uint64_t Start = OS.tell();
332 Write32(LCT_Dysymtab);
333 Write32(DysymtabLoadCommandSize);
334 Write32(FirstLocalSymbol);
335 Write32(NumLocalSymbols);
336 Write32(FirstExternalSymbol);
337 Write32(NumExternalSymbols);
338 Write32(FirstUndefinedSymbol);
339 Write32(NumUndefinedSymbols);
340 Write32(0); // tocoff
342 Write32(0); // modtaboff
343 Write32(0); // nmodtab
344 Write32(0); // extrefsymoff
345 Write32(0); // nextrefsyms
346 Write32(IndirectSymbolOffset);
347 Write32(NumIndirectSymbols);
348 Write32(0); // extreloff
349 Write32(0); // nextrel
350 Write32(0); // locreloff
351 Write32(0); // nlocrel
353 assert(OS.tell() - Start == DysymtabLoadCommandSize);
356 void WriteNlist(MachSymbolData &MSD) {
357 MCSymbolData &Data = *MSD.SymbolData;
358 const MCSymbol &Symbol = Data.getSymbol();
360 uint16_t Flags = Data.getFlags();
361 uint32_t Address = 0;
363 // Set the N_TYPE bits. See <mach-o/nlist.h>.
365 // FIXME: Are the prebound or indirect fields possible here?
366 if (Symbol.isUndefined())
367 Type = STT_Undefined;
368 else if (Symbol.isAbsolute())
373 // FIXME: Set STAB bits.
375 if (Data.isPrivateExtern())
376 Type |= STF_PrivateExtern;
379 if (Data.isExternal() || Symbol.isUndefined())
380 Type |= STF_External;
382 // Compute the symbol address.
383 if (Symbol.isDefined()) {
384 if (Symbol.isAbsolute()) {
385 llvm_unreachable("FIXME: Not yet implemented!");
387 Address = Data.getAddress();
389 } else if (Data.isCommon()) {
390 // Common symbols are encoded with the size in the address
391 // field, and their alignment in the flags.
392 Address = Data.getCommonSize();
394 // Common alignment is packed into the 'desc' bits.
395 if (unsigned Align = Data.getCommonAlignment()) {
396 unsigned Log2Size = Log2_32(Align);
397 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
399 llvm_report_error("invalid 'common' alignment '" +
401 // FIXME: Keep this mask with the SymbolFlags enumeration.
402 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
406 // struct nlist (12 bytes)
408 Write32(MSD.StringIndex);
410 Write8(MSD.SectionIndex);
412 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
421 void RecordScatteredRelocation(const MCAssembler &Asm,
422 const MCFragment &Fragment,
423 const MCAsmFixup &Fixup, MCValue Target,
424 uint64_t &FixedValue) {
425 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
426 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
427 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
428 unsigned Type = RIT_Vanilla;
431 const MCSymbol *A = &Target.getSymA()->getSymbol();
432 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
434 if (!A_SD->getFragment())
435 llvm_report_error("symbol '" + A->getName() +
436 "' can not be undefined in a subtraction expression");
438 uint32_t Value = A_SD->getAddress();
441 if (const MCSymbolRefExpr *B = Target.getSymB()) {
442 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
444 if (!B_SD->getFragment())
445 llvm_report_error("symbol '" + B->getSymbol().getName() +
446 "' can not be undefined in a subtraction expression");
448 // Select the appropriate difference relocation type.
450 // Note that there is no longer any semantic difference between these two
451 // relocation types from the linkers point of view, this is done solely
452 // for pedantic compatibility with 'as'.
453 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
454 Value2 = B_SD->getAddress();
457 // Relocations are written out in reverse order, so the PAIR comes first.
458 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
459 MachRelocationEntry MRE;
460 MRE.Word0 = ((0 << 0) |
466 Relocations[Fragment.getParent()].push_back(MRE);
469 MachRelocationEntry MRE;
470 MRE.Word0 = ((Address << 0) |
476 Relocations[Fragment.getParent()].push_back(MRE);
479 virtual void RecordRelocation(const MCAssembler &Asm,
480 const MCDataFragment &Fragment,
481 const MCAsmFixup &Fixup, MCValue Target,
482 uint64_t &FixedValue) {
483 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
484 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
486 // If this is a difference or a defined symbol plus an offset, then we need
487 // a scattered relocation entry.
488 uint32_t Offset = Target.getConstant();
490 Offset += 1 << Log2Size;
491 if (Target.getSymB() ||
492 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
494 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
499 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
502 unsigned IsExtern = 0;
505 if (Target.isAbsolute()) { // constant
506 // SymbolNum of 0 indicates the absolute section.
508 // FIXME: Currently, these are never generated (see code below). I cannot
509 // find a case where they are actually emitted.
513 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
514 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
516 if (Symbol->isUndefined()) {
518 Index = SD->getIndex();
521 // The index is the section ordinal.
525 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
526 for (; it != ie; ++it, ++Index)
527 if (&*it == SD->getFragment()->getParent())
529 assert(it != ie && "Unable to find section index!");
530 Value = SD->getAddress();
536 // struct relocation_info (8 bytes)
537 MachRelocationEntry MRE;
539 MRE.Word1 = ((Index << 0) |
544 Relocations[Fragment.getParent()].push_back(MRE);
547 void BindIndirectSymbols(MCAssembler &Asm) {
548 // This is the point where 'as' creates actual symbols for indirect symbols
549 // (in the following two passes). It would be easier for us to do this
550 // sooner when we see the attribute, but that makes getting the order in the
551 // symbol table much more complicated than it is worth.
553 // FIXME: Revisit this when the dust settles.
555 // Bind non lazy symbol pointers first.
556 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
557 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
558 // FIXME: cast<> support!
559 const MCSectionMachO &Section =
560 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
562 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
565 Asm.getOrCreateSymbolData(*it->Symbol);
568 // Then lazy symbol pointers and symbol stubs.
569 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
570 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
571 // FIXME: cast<> support!
572 const MCSectionMachO &Section =
573 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
575 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
576 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
579 // Set the symbol type to undefined lazy, but only on construction.
581 // FIXME: Do not hardcode.
583 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
585 Entry.setFlags(Entry.getFlags() | 0x0001);
589 /// ComputeSymbolTable - Compute the symbol table data
591 /// \param StringTable [out] - The string table data.
592 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
594 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
595 std::vector<MachSymbolData> &LocalSymbolData,
596 std::vector<MachSymbolData> &ExternalSymbolData,
597 std::vector<MachSymbolData> &UndefinedSymbolData) {
598 // Build section lookup table.
599 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
601 for (MCAssembler::iterator it = Asm.begin(),
602 ie = Asm.end(); it != ie; ++it, ++Index)
603 SectionIndexMap[&it->getSection()] = Index;
604 assert(Index <= 256 && "Too many sections!");
606 // Index 0 is always the empty string.
607 StringMap<uint64_t> StringIndexMap;
608 StringTable += '\x00';
610 // Build the symbol arrays and the string table, but only for non-local
613 // The particular order that we collect the symbols and create the string
614 // table, then sort the symbols is chosen to match 'as'. Even though it
615 // doesn't matter for correctness, this is important for letting us diff .o
617 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
618 ie = Asm.symbol_end(); it != ie; ++it) {
619 const MCSymbol &Symbol = it->getSymbol();
621 // Ignore non-linker visible symbols.
622 if (!Asm.isSymbolLinkerVisible(it))
625 if (!it->isExternal() && !Symbol.isUndefined())
628 uint64_t &Entry = StringIndexMap[Symbol.getName()];
630 Entry = StringTable.size();
631 StringTable += Symbol.getName();
632 StringTable += '\x00';
637 MSD.StringIndex = Entry;
639 if (Symbol.isUndefined()) {
640 MSD.SectionIndex = 0;
641 UndefinedSymbolData.push_back(MSD);
642 } else if (Symbol.isAbsolute()) {
643 MSD.SectionIndex = 0;
644 ExternalSymbolData.push_back(MSD);
646 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
647 assert(MSD.SectionIndex && "Invalid section index!");
648 ExternalSymbolData.push_back(MSD);
652 // Now add the data for local symbols.
653 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
654 ie = Asm.symbol_end(); it != ie; ++it) {
655 const MCSymbol &Symbol = it->getSymbol();
657 // Ignore non-linker visible symbols.
658 if (!Asm.isSymbolLinkerVisible(it))
661 if (it->isExternal() || Symbol.isUndefined())
664 uint64_t &Entry = StringIndexMap[Symbol.getName()];
666 Entry = StringTable.size();
667 StringTable += Symbol.getName();
668 StringTable += '\x00';
673 MSD.StringIndex = Entry;
675 if (Symbol.isAbsolute()) {
676 MSD.SectionIndex = 0;
677 LocalSymbolData.push_back(MSD);
679 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
680 assert(MSD.SectionIndex && "Invalid section index!");
681 LocalSymbolData.push_back(MSD);
685 // External and undefined symbols are required to be in lexicographic order.
686 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
687 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
689 // Set the symbol indices.
691 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
692 LocalSymbolData[i].SymbolData->setIndex(Index++);
693 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
694 ExternalSymbolData[i].SymbolData->setIndex(Index++);
695 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
696 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
698 // The string table is padded to a multiple of 4.
699 while (StringTable.size() % 4)
700 StringTable += '\x00';
703 virtual void ExecutePostLayoutBinding(MCAssembler &Asm) {
704 // Create symbol data for any indirect symbols.
705 BindIndirectSymbols(Asm);
707 // Compute symbol table information and bind symbol indices.
708 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
709 UndefinedSymbolData);
712 virtual void WriteObject(const MCAssembler &Asm) {
713 unsigned NumSections = Asm.size();
715 // The section data starts after the header, the segment load command (and
716 // section headers) and the symbol table.
717 unsigned NumLoadCommands = 1;
718 uint64_t LoadCommandsSize = Is64Bit ?
719 SegmentLoadCommand64Size + NumSections * Section64Size :
720 SegmentLoadCommand32Size + NumSections * Section32Size;
722 // Add the symbol table load command sizes, if used.
723 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
724 UndefinedSymbolData.size();
726 NumLoadCommands += 2;
727 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
730 // Compute the total size of the section data, as well as its file size and
732 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
734 uint64_t SectionDataSize = 0;
735 uint64_t SectionDataFileSize = 0;
737 for (MCAssembler::const_iterator it = Asm.begin(),
738 ie = Asm.end(); it != ie; ++it) {
739 const MCSectionData &SD = *it;
741 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
743 if (Asm.getBackend().isVirtualSection(SD.getSection()))
746 SectionDataSize = std::max(SectionDataSize,
747 SD.getAddress() + SD.getSize());
748 SectionDataFileSize = std::max(SectionDataFileSize,
749 SD.getAddress() + SD.getFileSize());
752 // The section data is padded to 4 bytes.
754 // FIXME: Is this machine dependent?
755 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
756 SectionDataFileSize += SectionDataPadding;
758 // Write the prolog, starting with the header and load command...
759 WriteHeader(NumLoadCommands, LoadCommandsSize,
760 Asm.getSubsectionsViaSymbols());
761 WriteSegmentLoadCommand(NumSections, VMSize,
762 SectionDataStart, SectionDataSize);
764 // ... and then the section headers.
765 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
766 for (MCAssembler::const_iterator it = Asm.begin(),
767 ie = Asm.end(); it != ie; ++it) {
768 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
769 unsigned NumRelocs = Relocs.size();
770 uint64_t SectionStart = SectionDataStart + it->getAddress();
771 WriteSection(Asm, *it, SectionStart, RelocTableEnd, NumRelocs);
772 RelocTableEnd += NumRelocs * RelocationInfoSize;
775 // Write the symbol table load command, if used.
777 unsigned FirstLocalSymbol = 0;
778 unsigned NumLocalSymbols = LocalSymbolData.size();
779 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
780 unsigned NumExternalSymbols = ExternalSymbolData.size();
781 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
782 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
783 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
784 unsigned NumSymTabSymbols =
785 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
786 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
787 uint64_t IndirectSymbolOffset = 0;
789 // If used, the indirect symbols are written after the section data.
790 if (NumIndirectSymbols)
791 IndirectSymbolOffset = RelocTableEnd;
793 // The symbol table is written after the indirect symbol data.
794 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
796 // The string table is written after symbol table.
797 uint64_t StringTableOffset =
798 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
800 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
801 StringTableOffset, StringTable.size());
803 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
804 FirstExternalSymbol, NumExternalSymbols,
805 FirstUndefinedSymbol, NumUndefinedSymbols,
806 IndirectSymbolOffset, NumIndirectSymbols);
809 // Write the actual section data.
810 for (MCAssembler::const_iterator it = Asm.begin(),
811 ie = Asm.end(); it != ie; ++it)
812 Asm.WriteSectionData(it, this);
814 // Write the extra padding.
815 WriteZeros(SectionDataPadding);
817 // Write the relocation entries.
818 for (MCAssembler::const_iterator it = Asm.begin(),
819 ie = Asm.end(); it != ie; ++it) {
820 // Write the section relocation entries, in reverse order to match 'as'
821 // (approximately, the exact algorithm is more complicated than this).
822 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
823 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
824 Write32(Relocs[e - i - 1].Word0);
825 Write32(Relocs[e - i - 1].Word1);
829 // Write the symbol table data, if used.
831 // Write the indirect symbol entries.
832 for (MCAssembler::const_indirect_symbol_iterator
833 it = Asm.indirect_symbol_begin(),
834 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
835 // Indirect symbols in the non lazy symbol pointer section have some
837 const MCSectionMachO &Section =
838 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
839 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
840 // If this symbol is defined and internal, mark it as such.
841 if (it->Symbol->isDefined() &&
842 !Asm.getSymbolData(*it->Symbol).isExternal()) {
843 uint32_t Flags = ISF_Local;
844 if (it->Symbol->isAbsolute())
845 Flags |= ISF_Absolute;
851 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
854 // FIXME: Check that offsets match computed ones.
856 // Write the symbol table entries.
857 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
858 WriteNlist(LocalSymbolData[i]);
859 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
860 WriteNlist(ExternalSymbolData[i]);
861 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
862 WriteNlist(UndefinedSymbolData[i]);
864 // Write the string table.
865 OS << StringTable.str();
872 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
875 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
878 FileSize(~UINT64_C(0))
881 Parent->getFragmentList().push_back(this);
884 MCFragment::~MCFragment() {
887 uint64_t MCFragment::getAddress() const {
888 assert(getParent() && "Missing Section!");
889 return getParent()->getAddress() + Offset;
894 MCSectionData::MCSectionData() : Section(0) {}
896 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
897 : Section(&_Section),
899 Address(~UINT64_C(0)),
901 FileSize(~UINT64_C(0)),
902 HasInstructions(false)
905 A->getSectionList().push_back(this);
910 MCSymbolData::MCSymbolData() : Symbol(0) {}
912 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
913 uint64_t _Offset, MCAssembler *A)
914 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
915 IsExternal(false), IsPrivateExtern(false),
916 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
919 A->getSymbolList().push_back(this);
924 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
926 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
930 MCAssembler::~MCAssembler() {
933 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
934 const MCAsmFixup &Fixup,
935 const MCDataFragment *DF,
936 const MCValue Target,
937 const MCSection *BaseSection) {
938 // The effective fixup address is
939 // addr(atom(A)) + offset(A)
940 // - addr(atom(B)) - offset(B)
941 // - addr(<base symbol>) + <fixup offset from base symbol>
942 // and the offsets are not relocatable, so the fixup is fully resolved when
943 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
945 // The simple (Darwin, except on x86_64) way of dealing with this was to
946 // assume that any reference to a temporary symbol *must* be a temporary
947 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
948 // relocation to a temporary symbol (in the same section) is fully
949 // resolved. This also works in conjunction with absolutized .set, which
950 // requires the compiler to use .set to absolutize the differences between
951 // symbols which the compiler knows to be assembly time constants, so we don't
952 // need to worry about consider symbol differences fully resolved.
954 // Non-relative fixups are only resolved if constant.
956 return Target.isAbsolute();
958 // Otherwise, relative fixups are only resolved if not a difference and the
959 // target is a temporary in the same section.
960 if (Target.isAbsolute() || Target.getSymB())
963 const MCSymbol *A = &Target.getSymA()->getSymbol();
964 if (!A->isTemporary() || !A->isInSection() ||
965 &A->getSection() != BaseSection)
971 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
972 const MCAsmFixup &Fixup,
973 const MCDataFragment *DF,
974 const MCValue Target,
975 const MCSymbolData *BaseSymbol) {
976 // The effective fixup address is
977 // addr(atom(A)) + offset(A)
978 // - addr(atom(B)) - offset(B)
979 // - addr(BaseSymbol) + <fixup offset from base symbol>
980 // and the offsets are not relocatable, so the fixup is fully resolved when
981 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
983 // Note that "false" is almost always conservatively correct (it means we emit
984 // a relocation which is unnecessary), except when it would force us to emit a
985 // relocation which the target cannot encode.
987 const MCSymbolData *A_Base = 0, *B_Base = 0;
988 if (const MCSymbolRefExpr *A = Target.getSymA()) {
989 // Modified symbol references cannot be resolved.
990 if (A->getKind() != MCSymbolRefExpr::VK_None)
993 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
998 if (const MCSymbolRefExpr *B = Target.getSymB()) {
999 // Modified symbol references cannot be resolved.
1000 if (B->getKind() != MCSymbolRefExpr::VK_None)
1003 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1008 // If there is no base, A and B have to be the same atom for this fixup to be
1011 return A_Base == B_Base;
1013 // Otherwise, B must be missing and A must be the base.
1014 return !B_Base && BaseSymbol == A_Base;
1017 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
1018 // Non-temporary labels should always be visible to the linker.
1019 if (!SD->getSymbol().isTemporary())
1022 // Absolute temporary labels are never visible.
1023 if (!SD->getFragment())
1026 // Otherwise, check if the section requires symbols even for temporary labels.
1027 return getBackend().doesSectionRequireSymbols(
1028 SD->getFragment()->getParent()->getSection());
1031 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
1032 uint64_t Address) const {
1033 const MCSymbolData *Best = 0;
1034 for (MCAssembler::const_symbol_iterator it = symbol_begin(),
1035 ie = symbol_end(); it != ie; ++it) {
1036 // Ignore non-linker visible symbols.
1037 if (!isSymbolLinkerVisible(it))
1040 // Ignore symbols not in the same section.
1041 if (!it->getFragment() || it->getFragment()->getParent() != Section)
1044 // Otherwise, find the closest symbol preceding this address (ties are
1045 // resolved in favor of the last defined symbol).
1046 if (it->getAddress() <= Address &&
1047 (!Best || it->getAddress() >= Best->getAddress()))
1054 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
1055 // Linker visible symbols define atoms.
1056 if (isSymbolLinkerVisible(SD))
1059 // Absolute and undefined symbols have no defining atom.
1060 if (!SD->getFragment())
1063 // Otherwise, search by address.
1064 return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
1067 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1069 MCValue &Target, uint64_t &Value) const {
1070 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1071 llvm_report_error("expected relocatable expression");
1073 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1074 // doesn't support small relocations, but then under what criteria does the
1075 // assembler allow symbol differences?
1077 Value = Target.getConstant();
1079 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1080 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1081 if (A->getSymbol().isDefined())
1082 Value += getSymbolData(A->getSymbol()).getAddress();
1086 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1087 if (B->getSymbol().isDefined())
1088 Value -= getSymbolData(B->getSymbol()).getAddress();
1093 // If we are using scattered symbols, determine whether this value is actually
1094 // resolved; scattering may cause atoms to move.
1095 if (IsResolved && getBackend().hasScatteredSymbols()) {
1096 if (getBackend().hasReliableSymbolDifference()) {
1097 // If this is a PCrel relocation, find the base atom (identified by its
1098 // symbol) that the fixup value is relative to.
1099 const MCSymbolData *BaseSymbol = 0;
1101 BaseSymbol = getAtomForAddress(
1102 DF->getParent(), DF->getAddress() + Fixup.Offset);
1108 IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
1111 const MCSection *BaseSection = 0;
1113 BaseSection = &DF->getParent()->getSection();
1115 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
1121 Value -= DF->getAddress() + Fixup.Offset;
1126 void MCAssembler::LayoutSection(MCSectionData &SD) {
1127 MCAsmLayout Layout(*this);
1128 uint64_t Address = SD.getAddress();
1130 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1131 MCFragment &F = *it;
1133 F.setOffset(Address - SD.getAddress());
1135 // Evaluate fragment size.
1136 switch (F.getKind()) {
1137 case MCFragment::FT_Align: {
1138 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1140 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1141 if (Size > AF.getMaxBytesToEmit())
1144 AF.setFileSize(Size);
1148 case MCFragment::FT_Data:
1149 case MCFragment::FT_Fill:
1150 F.setFileSize(F.getMaxFileSize());
1153 case MCFragment::FT_Org: {
1154 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1156 int64_t TargetLocation;
1157 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1158 llvm_report_error("expected assembly-time absolute expression");
1160 // FIXME: We need a way to communicate this error.
1161 int64_t Offset = TargetLocation - F.getOffset();
1163 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1164 "' (at offset '" + Twine(F.getOffset()) + "'");
1166 F.setFileSize(Offset);
1170 case MCFragment::FT_ZeroFill: {
1171 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1173 // Align the fragment offset; it is safe to adjust the offset freely since
1174 // this is only in virtual sections.
1175 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1176 F.setOffset(Address - SD.getAddress());
1178 // FIXME: This is misnamed.
1179 F.setFileSize(ZFF.getSize());
1184 Address += F.getFileSize();
1187 // Set the section sizes.
1188 SD.setSize(Address - SD.getAddress());
1189 if (getBackend().isVirtualSection(SD.getSection()))
1192 SD.setFileSize(Address - SD.getAddress());
1195 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1196 /// bytes. This returns the number of bytes written. It may return 0 if
1197 /// the \arg Count is more than the maximum optimal nops.
1199 /// FIXME this is X86 32-bit specific and should move to a better place.
1200 static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
1201 static const uint8_t Nops[16][16] = {
1209 {0x0f, 0x1f, 0x40, 0x00},
1210 // nopl 0(%[re]ax,%[re]ax,1)
1211 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1212 // nopw 0(%[re]ax,%[re]ax,1)
1213 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1215 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1216 // nopl 0L(%[re]ax,%[re]ax,1)
1217 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1218 // nopw 0L(%[re]ax,%[re]ax,1)
1219 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1220 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1221 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1222 // nopl 0(%[re]ax,%[re]ax,1)
1223 // nopw 0(%[re]ax,%[re]ax,1)
1224 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1225 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1226 // nopw 0(%[re]ax,%[re]ax,1)
1227 // nopw 0(%[re]ax,%[re]ax,1)
1228 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1229 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1230 // nopw 0(%[re]ax,%[re]ax,1)
1231 // nopl 0L(%[re]ax) */
1232 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1233 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1236 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1237 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1239 // nopl 0L(%[re]ax,%[re]ax,1)
1240 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1241 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1247 for (uint64_t i = 0; i < Count; i++)
1248 OW->Write8(uint8_t(Nops[Count - 1][i]));
1253 /// WriteFragmentData - Write the \arg F data to the output file.
1254 static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
1255 uint64_t Start = OW->getStream().tell();
1260 // FIXME: Embed in fragments instead?
1261 switch (F.getKind()) {
1262 case MCFragment::FT_Align: {
1263 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1264 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1266 // FIXME: This error shouldn't actually occur (the front end should emit
1267 // multiple .align directives to enforce the semantics it wants), but is
1268 // severe enough that we want to report it. How to handle this?
1269 if (Count * AF.getValueSize() != AF.getFileSize())
1270 llvm_report_error("undefined .align directive, value size '" +
1271 Twine(AF.getValueSize()) +
1272 "' is not a divisor of padding size '" +
1273 Twine(AF.getFileSize()) + "'");
1275 // See if we are aligning with nops, and if so do that first to try to fill
1276 // the Count bytes. Then if that did not fill any bytes or there are any
1277 // bytes left to fill use the the Value and ValueSize to fill the rest.
1278 if (AF.getEmitNops()) {
1279 uint64_t NopByteCount = WriteNopData(Count, OW);
1280 Count -= NopByteCount;
1283 for (uint64_t i = 0; i != Count; ++i) {
1284 switch (AF.getValueSize()) {
1286 assert(0 && "Invalid size!");
1287 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
1288 case 2: OW->Write16(uint16_t(AF.getValue())); break;
1289 case 4: OW->Write32(uint32_t(AF.getValue())); break;
1290 case 8: OW->Write64(uint64_t(AF.getValue())); break;
1296 case MCFragment::FT_Data: {
1297 OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1301 case MCFragment::FT_Fill: {
1302 MCFillFragment &FF = cast<MCFillFragment>(F);
1303 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1304 switch (FF.getValueSize()) {
1306 assert(0 && "Invalid size!");
1307 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
1308 case 2: OW->Write16(uint16_t(FF.getValue())); break;
1309 case 4: OW->Write32(uint32_t(FF.getValue())); break;
1310 case 8: OW->Write64(uint64_t(FF.getValue())); break;
1316 case MCFragment::FT_Org: {
1317 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1319 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1320 OW->Write8(uint8_t(OF.getValue()));
1325 case MCFragment::FT_ZeroFill: {
1326 assert(0 && "Invalid zero fill fragment in concrete section!");
1331 assert(OW->getStream().tell() - Start == F.getFileSize());
1334 void MCAssembler::WriteSectionData(const MCSectionData *SD,
1335 MCObjectWriter *OW) const {
1336 // Ignore virtual sections.
1337 if (getBackend().isVirtualSection(SD->getSection())) {
1338 assert(SD->getFileSize() == 0);
1342 uint64_t Start = OW->getStream().tell();
1345 for (MCSectionData::const_iterator it = SD->begin(),
1346 ie = SD->end(); it != ie; ++it)
1347 WriteFragmentData(*it, OW);
1349 // Add section padding.
1350 assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
1351 OW->WriteZeros(SD->getFileSize() - SD->getSize());
1353 assert(OW->getStream().tell() - Start == SD->getFileSize());
1356 void MCAssembler::Finish() {
1357 DEBUG_WITH_TYPE("mc-dump", {
1358 llvm::errs() << "assembler backend - pre-layout\n--\n";
1361 // Layout until everything fits.
1362 while (LayoutOnce())
1365 DEBUG_WITH_TYPE("mc-dump", {
1366 llvm::errs() << "assembler backend - post-layout\n--\n";
1369 // FIXME: Factor out MCObjectWriter.
1370 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1371 MachObjectWriter MOW(OS, Is64Bit);
1373 // Allow the object writer a chance to perform post-layout binding (for
1374 // example, to set the index fields in the symbol data).
1375 MOW.ExecutePostLayoutBinding(*this);
1377 // Evaluate and apply the fixups, generating relocation entries as necessary.
1379 // FIXME: Share layout object.
1380 MCAsmLayout Layout(*this);
1381 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
1382 for (MCSectionData::iterator it2 = it->begin(),
1383 ie2 = it->end(); it2 != ie2; ++it2) {
1384 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1388 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1389 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1390 MCAsmFixup &Fixup = *it3;
1392 // Evaluate the fixup.
1394 uint64_t FixedValue;
1395 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
1396 // The fixup was unresolved, we need a relocation. Inform the object
1397 // writer of the relocation, and give it an opportunity to adjust the
1398 // fixup value if need be.
1399 MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
1402 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
1407 // Write the object file.
1408 MOW.WriteObject(*this);
1413 bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1414 // FIXME: Share layout object.
1415 MCAsmLayout Layout(*this);
1417 // Currently we only need to relax X86::reloc_pcrel_1byte.
1418 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1421 // If we cannot resolve the fixup value, it requires relaxation.
1424 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1427 // Otherwise, relax if the value is too big for a (signed) i8.
1428 return int64_t(Value) != int64_t(int8_t(Value));
1431 bool MCAssembler::LayoutOnce() {
1432 // Layout the concrete sections and fragments.
1433 uint64_t Address = 0;
1434 MCSectionData *Prev = 0;
1435 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1436 MCSectionData &SD = *it;
1438 // Skip virtual sections.
1439 if (getBackend().isVirtualSection(SD.getSection()))
1442 // Align this section if necessary by adding padding bytes to the previous
1444 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1445 assert(Prev && "Missing prev section!");
1446 Prev->setFileSize(Prev->getFileSize() + Pad);
1450 // Layout the section fragments and its size.
1451 SD.setAddress(Address);
1453 Address += SD.getFileSize();
1458 // Layout the virtual sections.
1459 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1460 MCSectionData &SD = *it;
1462 if (!getBackend().isVirtualSection(SD.getSection()))
1465 // Align this section if necessary by adding padding bytes to the previous
1467 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1470 SD.setAddress(Address);
1472 Address += SD.getSize();
1475 // Scan the fixups in order and relax any that don't fit.
1476 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1477 MCSectionData &SD = *it;
1479 for (MCSectionData::iterator it2 = SD.begin(),
1480 ie2 = SD.end(); it2 != ie2; ++it2) {
1481 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1485 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1486 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1487 MCAsmFixup &Fixup = *it3;
1489 // Check whether we need to relax this fixup.
1490 if (!FixupNeedsRelaxation(Fixup, DF))
1493 // Relax the instruction.
1495 // FIXME: This is a huge temporary hack which just looks for x86
1496 // branches; the only thing we need to relax on x86 is
1497 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1498 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1499 // an individual MCInst.
1500 SmallVectorImpl<char> &C = DF->getContents();
1501 uint64_t PrevOffset = Fixup.Offset;
1505 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1506 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1507 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1508 C[Fixup.Offset-1] = char(0x0f);
1513 } else if (C[Fixup.Offset-1] == char(0xeb)) {
1514 C[Fixup.Offset-1] = char(0xe9);
1518 llvm_unreachable("unknown 1 byte pcrel instruction!");
1520 Fixup.Value = MCBinaryExpr::Create(
1521 MCBinaryExpr::Sub, Fixup.Value,
1522 MCConstantExpr::Create(3, getContext()),
1524 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1525 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1527 // Update the remaining fixups, which have slid.
1529 // FIXME: This is bad for performance, but will be eliminated by the
1530 // move to MCInst specific fragments.
1532 for (; it3 != ie3; ++it3)
1535 // Update all the symbols for this fragment, which may have slid.
1537 // FIXME: This is really really bad for performance, but will be
1538 // eliminated by the move to MCInst specific fragments.
1539 for (MCAssembler::symbol_iterator it = symbol_begin(),
1540 ie = symbol_end(); it != ie; ++it) {
1541 MCSymbolData &SD = *it;
1543 if (it->getFragment() != DF)
1546 if (SD.getOffset() > PrevOffset)
1547 SD.setOffset(SD.getOffset() + Amt);
1552 // FIXME: This is O(N^2), but will be eliminated once we have a smart
1553 // MCAsmLayout object.
1562 // Debugging methods
1566 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1567 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1568 << " Kind:" << AF.Kind << ">";
1574 void MCFragment::dump() {
1575 raw_ostream &OS = llvm::errs();
1577 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1578 << " FileSize:" << FileSize;
1583 void MCAlignFragment::dump() {
1584 raw_ostream &OS = llvm::errs();
1586 OS << "<MCAlignFragment ";
1587 this->MCFragment::dump();
1589 OS << " Alignment:" << getAlignment()
1590 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1591 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1594 void MCDataFragment::dump() {
1595 raw_ostream &OS = llvm::errs();
1597 OS << "<MCDataFragment ";
1598 this->MCFragment::dump();
1600 OS << " Contents:[";
1601 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1603 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1605 OS << "] (" << getContents().size() << " bytes)";
1607 if (!getFixups().empty()) {
1610 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1611 if (it != fixup_begin()) OS << ",\n ";
1620 void MCFillFragment::dump() {
1621 raw_ostream &OS = llvm::errs();
1623 OS << "<MCFillFragment ";
1624 this->MCFragment::dump();
1626 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1627 << " Count:" << getCount() << ">";
1630 void MCOrgFragment::dump() {
1631 raw_ostream &OS = llvm::errs();
1633 OS << "<MCOrgFragment ";
1634 this->MCFragment::dump();
1636 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1639 void MCZeroFillFragment::dump() {
1640 raw_ostream &OS = llvm::errs();
1642 OS << "<MCZeroFillFragment ";
1643 this->MCFragment::dump();
1645 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1648 void MCSectionData::dump() {
1649 raw_ostream &OS = llvm::errs();
1651 OS << "<MCSectionData";
1652 OS << " Alignment:" << getAlignment() << " Address:" << Address
1653 << " Size:" << Size << " FileSize:" << FileSize
1654 << " Fragments:[\n ";
1655 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1656 if (it != begin()) OS << ",\n ";
1662 void MCSymbolData::dump() {
1663 raw_ostream &OS = llvm::errs();
1665 OS << "<MCSymbolData Symbol:" << getSymbol()
1666 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1667 << " Flags:" << getFlags() << " Index:" << getIndex();
1669 OS << " (common, size:" << getCommonSize()
1670 << " align: " << getCommonAlignment() << ")";
1672 OS << " (external)";
1673 if (isPrivateExtern())
1674 OS << " (private extern)";
1678 void MCAssembler::dump() {
1679 raw_ostream &OS = llvm::errs();
1681 OS << "<MCAssembler\n";
1682 OS << " Sections:[\n ";
1683 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1684 if (it != begin()) OS << ",\n ";
1690 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1691 if (it != symbol_begin()) OS << ",\n ";