pass machinemoduleinfo down into getSymbolForDwarfGlobalReference,
[llvm/avr.git] / lib / MC / MCAssembler.cpp
blob0afdf98cbe797a6b80470e8c7b12694080b508cd
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCSectionMachO.h"
13 #include "llvm/Target/TargetMachOWriterInfo.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <vector>
22 using namespace llvm;
24 class MachObjectWriter;
26 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
28 // FIXME FIXME FIXME: There are number of places in this file where we convert
29 // what is a 64-bit assembler value used for computation into a value in the
30 // object file, which may truncate it. We should detect that truncation where
31 // invalid and report errors back.
33 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
34 MachObjectWriter &MOW);
36 /// isVirtualSection - Check if this is a section which does not actually exist
37 /// in the object file.
38 static bool isVirtualSection(const MCSection &Section) {
39 // FIXME: Lame.
40 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
41 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
42 return (Type == MCSectionMachO::S_ZEROFILL);
45 class MachObjectWriter {
46 // See <mach-o/loader.h>.
47 enum {
48 Header_Magic32 = 0xFEEDFACE,
49 Header_Magic64 = 0xFEEDFACF
52 static const unsigned Header32Size = 28;
53 static const unsigned Header64Size = 32;
54 static const unsigned SegmentLoadCommand32Size = 56;
55 static const unsigned Section32Size = 68;
56 static const unsigned SymtabLoadCommandSize = 24;
57 static const unsigned DysymtabLoadCommandSize = 80;
58 static const unsigned Nlist32Size = 12;
59 static const unsigned RelocationInfoSize = 8;
61 enum HeaderFileType {
62 HFT_Object = 0x1
65 enum HeaderFlags {
66 HF_SubsectionsViaSymbols = 0x2000
69 enum LoadCommandType {
70 LCT_Segment = 0x1,
71 LCT_Symtab = 0x2,
72 LCT_Dysymtab = 0xb
75 // See <mach-o/nlist.h>.
76 enum SymbolTypeType {
77 STT_Undefined = 0x00,
78 STT_Absolute = 0x02,
79 STT_Section = 0x0e
82 enum SymbolTypeFlags {
83 // If any of these bits are set, then the entry is a stab entry number (see
84 // <mach-o/stab.h>. Otherwise the other masks apply.
85 STF_StabsEntryMask = 0xe0,
87 STF_TypeMask = 0x0e,
88 STF_External = 0x01,
89 STF_PrivateExtern = 0x10
92 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
93 /// symbol entry.
94 enum IndirectSymbolFlags {
95 ISF_Local = 0x80000000,
96 ISF_Absolute = 0x40000000
99 /// RelocationFlags - Special flags for addresses.
100 enum RelocationFlags {
101 RF_Scattered = 0x80000000
104 enum RelocationInfoType {
105 RIT_Vanilla = 0,
106 RIT_Pair = 1,
107 RIT_Difference = 2,
108 RIT_PreboundLazyPointer = 3,
109 RIT_LocalDifference = 4
112 /// MachSymbolData - Helper struct for containing some precomputed information
113 /// on symbols.
114 struct MachSymbolData {
115 MCSymbolData *SymbolData;
116 uint64_t StringIndex;
117 uint8_t SectionIndex;
119 // Support lexicographic sorting.
120 bool operator<(const MachSymbolData &RHS) const {
121 const std::string &Name = SymbolData->getSymbol().getName();
122 return Name < RHS.SymbolData->getSymbol().getName();
126 raw_ostream &OS;
127 bool IsLSB;
129 public:
130 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
131 : OS(_OS), IsLSB(_IsLSB) {
134 /// @name Helper Methods
135 /// @{
137 void Write8(uint8_t Value) {
138 OS << char(Value);
141 void Write16(uint16_t Value) {
142 if (IsLSB) {
143 Write8(uint8_t(Value >> 0));
144 Write8(uint8_t(Value >> 8));
145 } else {
146 Write8(uint8_t(Value >> 8));
147 Write8(uint8_t(Value >> 0));
151 void Write32(uint32_t Value) {
152 if (IsLSB) {
153 Write16(uint16_t(Value >> 0));
154 Write16(uint16_t(Value >> 16));
155 } else {
156 Write16(uint16_t(Value >> 16));
157 Write16(uint16_t(Value >> 0));
161 void Write64(uint64_t Value) {
162 if (IsLSB) {
163 Write32(uint32_t(Value >> 0));
164 Write32(uint32_t(Value >> 32));
165 } else {
166 Write32(uint32_t(Value >> 32));
167 Write32(uint32_t(Value >> 0));
171 void WriteZeros(unsigned N) {
172 const char Zeros[16] = { 0 };
174 for (unsigned i = 0, e = N / 16; i != e; ++i)
175 OS << StringRef(Zeros, 16);
177 OS << StringRef(Zeros, N % 16);
180 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
181 OS << Str;
182 if (ZeroFillSize)
183 WriteZeros(ZeroFillSize - Str.size());
186 /// @}
188 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
189 bool SubsectionsViaSymbols) {
190 uint32_t Flags = 0;
192 if (SubsectionsViaSymbols)
193 Flags |= HF_SubsectionsViaSymbols;
195 // struct mach_header (28 bytes)
197 uint64_t Start = OS.tell();
198 (void) Start;
200 Write32(Header_Magic32);
202 // FIXME: Support cputype.
203 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
204 // FIXME: Support cpusubtype.
205 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
206 Write32(HFT_Object);
207 Write32(NumLoadCommands); // Object files have a single load command, the
208 // segment.
209 Write32(LoadCommandsSize);
210 Write32(Flags);
212 assert(OS.tell() - Start == Header32Size);
215 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
217 /// \arg NumSections - The number of sections in this segment.
218 /// \arg SectionDataSize - The total size of the sections.
219 void WriteSegmentLoadCommand32(unsigned NumSections,
220 uint64_t VMSize,
221 uint64_t SectionDataStartOffset,
222 uint64_t SectionDataSize) {
223 // struct segment_command (56 bytes)
225 uint64_t Start = OS.tell();
226 (void) Start;
228 Write32(LCT_Segment);
229 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
231 WriteString("", 16);
232 Write32(0); // vmaddr
233 Write32(VMSize); // vmsize
234 Write32(SectionDataStartOffset); // file offset
235 Write32(SectionDataSize); // file size
236 Write32(0x7); // maxprot
237 Write32(0x7); // initprot
238 Write32(NumSections);
239 Write32(0); // flags
241 assert(OS.tell() - Start == SegmentLoadCommand32Size);
244 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
245 uint64_t RelocationsStart, unsigned NumRelocations) {
246 // The offset is unused for virtual sections.
247 if (isVirtualSection(SD.getSection())) {
248 assert(SD.getFileSize() == 0 && "Invalid file size!");
249 FileOffset = 0;
252 // struct section (68 bytes)
254 uint64_t Start = OS.tell();
255 (void) Start;
257 // FIXME: cast<> support!
258 const MCSectionMachO &Section =
259 static_cast<const MCSectionMachO&>(SD.getSection());
260 WriteString(Section.getSectionName(), 16);
261 WriteString(Section.getSegmentName(), 16);
262 Write32(SD.getAddress()); // address
263 Write32(SD.getSize()); // size
264 Write32(FileOffset);
266 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
267 Write32(Log2_32(SD.getAlignment()));
268 Write32(NumRelocations ? RelocationsStart : 0);
269 Write32(NumRelocations);
270 Write32(Section.getTypeAndAttributes());
271 Write32(0); // reserved1
272 Write32(Section.getStubSize()); // reserved2
274 assert(OS.tell() - Start == Section32Size);
277 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
278 uint32_t StringTableOffset,
279 uint32_t StringTableSize) {
280 // struct symtab_command (24 bytes)
282 uint64_t Start = OS.tell();
283 (void) Start;
285 Write32(LCT_Symtab);
286 Write32(SymtabLoadCommandSize);
287 Write32(SymbolOffset);
288 Write32(NumSymbols);
289 Write32(StringTableOffset);
290 Write32(StringTableSize);
292 assert(OS.tell() - Start == SymtabLoadCommandSize);
295 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
296 uint32_t NumLocalSymbols,
297 uint32_t FirstExternalSymbol,
298 uint32_t NumExternalSymbols,
299 uint32_t FirstUndefinedSymbol,
300 uint32_t NumUndefinedSymbols,
301 uint32_t IndirectSymbolOffset,
302 uint32_t NumIndirectSymbols) {
303 // struct dysymtab_command (80 bytes)
305 uint64_t Start = OS.tell();
306 (void) Start;
308 Write32(LCT_Dysymtab);
309 Write32(DysymtabLoadCommandSize);
310 Write32(FirstLocalSymbol);
311 Write32(NumLocalSymbols);
312 Write32(FirstExternalSymbol);
313 Write32(NumExternalSymbols);
314 Write32(FirstUndefinedSymbol);
315 Write32(NumUndefinedSymbols);
316 Write32(0); // tocoff
317 Write32(0); // ntoc
318 Write32(0); // modtaboff
319 Write32(0); // nmodtab
320 Write32(0); // extrefsymoff
321 Write32(0); // nextrefsyms
322 Write32(IndirectSymbolOffset);
323 Write32(NumIndirectSymbols);
324 Write32(0); // extreloff
325 Write32(0); // nextrel
326 Write32(0); // locreloff
327 Write32(0); // nlocrel
329 assert(OS.tell() - Start == DysymtabLoadCommandSize);
332 void WriteNlist32(MachSymbolData &MSD) {
333 MCSymbolData &Data = *MSD.SymbolData;
334 const MCSymbol &Symbol = Data.getSymbol();
335 uint8_t Type = 0;
336 uint16_t Flags = Data.getFlags();
337 uint32_t Address = 0;
339 // Set the N_TYPE bits. See <mach-o/nlist.h>.
341 // FIXME: Are the prebound or indirect fields possible here?
342 if (Symbol.isUndefined())
343 Type = STT_Undefined;
344 else if (Symbol.isAbsolute())
345 Type = STT_Absolute;
346 else
347 Type = STT_Section;
349 // FIXME: Set STAB bits.
351 if (Data.isPrivateExtern())
352 Type |= STF_PrivateExtern;
354 // Set external bit.
355 if (Data.isExternal() || Symbol.isUndefined())
356 Type |= STF_External;
358 // Compute the symbol address.
359 if (Symbol.isDefined()) {
360 if (Symbol.isAbsolute()) {
361 llvm_unreachable("FIXME: Not yet implemented!");
362 } else {
363 Address = Data.getFragment()->getAddress() + Data.getOffset();
365 } else if (Data.isCommon()) {
366 // Common symbols are encoded with the size in the address
367 // field, and their alignment in the flags.
368 Address = Data.getCommonSize();
370 // Common alignment is packed into the 'desc' bits.
371 if (unsigned Align = Data.getCommonAlignment()) {
372 unsigned Log2Size = Log2_32(Align);
373 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
374 if (Log2Size > 15)
375 llvm_report_error("invalid 'common' alignment '" +
376 Twine(Align) + "'");
377 // FIXME: Keep this mask with the SymbolFlags enumeration.
378 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
382 // struct nlist (12 bytes)
384 Write32(MSD.StringIndex);
385 Write8(Type);
386 Write8(MSD.SectionIndex);
388 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
389 // value.
390 Write16(Flags);
391 Write32(Address);
394 struct MachRelocationEntry {
395 uint32_t Word0;
396 uint32_t Word1;
398 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
399 MCSectionData::Fixup &Fixup,
400 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
401 std::vector<MachRelocationEntry> &Relocs) {
402 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
403 unsigned IsPCRel = 0;
404 unsigned Type = RIT_Vanilla;
406 // See <reloc.h>.
408 const MCSymbol *A = Fixup.Value.getSymA();
409 MCSymbolData *SD = SymbolMap.lookup(A);
410 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
411 uint32_t Value2 = 0;
413 if (const MCSymbol *B = Fixup.Value.getSymB()) {
414 Type = RIT_LocalDifference;
416 MCSymbolData *SD = SymbolMap.lookup(B);
417 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
420 unsigned Log2Size = Log2_32(Fixup.Size);
421 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
423 // The value which goes in the fixup is current value of the expression.
424 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
426 MachRelocationEntry MRE;
427 MRE.Word0 = ((Address << 0) |
428 (Type << 24) |
429 (Log2Size << 28) |
430 (IsPCRel << 30) |
431 RF_Scattered);
432 MRE.Word1 = Value;
433 Relocs.push_back(MRE);
435 if (Type == RIT_LocalDifference) {
436 Type = RIT_Pair;
438 MachRelocationEntry MRE;
439 MRE.Word0 = ((0 << 0) |
440 (Type << 24) |
441 (Log2Size << 28) |
442 (0 << 30) |
443 RF_Scattered);
444 MRE.Word1 = Value2;
445 Relocs.push_back(MRE);
449 void ComputeRelocationInfo(MCAssembler &Asm,
450 MCSectionData::Fixup &Fixup,
451 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
452 std::vector<MachRelocationEntry> &Relocs) {
453 // If this is a local symbol plus an offset or a difference, then we need a
454 // scattered relocation entry.
455 if (Fixup.Value.getSymB()) // a - b
456 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
457 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
458 if (!Fixup.Value.getSymA()->isUndefined())
459 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
461 // See <reloc.h>.
462 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
463 uint32_t Value = 0;
464 unsigned Index = 0;
465 unsigned IsPCRel = 0;
466 unsigned IsExtern = 0;
467 unsigned Type = 0;
469 if (Fixup.Value.isAbsolute()) { // constant
470 // SymbolNum of 0 indicates the absolute section.
471 Type = RIT_Vanilla;
472 Value = 0;
473 llvm_unreachable("FIXME: Not yet implemented!");
474 } else {
475 const MCSymbol *Symbol = Fixup.Value.getSymA();
476 MCSymbolData *SD = SymbolMap.lookup(Symbol);
478 if (Symbol->isUndefined()) {
479 IsExtern = 1;
480 Index = SD->getIndex();
481 Value = 0;
482 } else {
483 // The index is the section ordinal.
485 // FIXME: O(N)
486 Index = 1;
487 for (MCAssembler::iterator it = Asm.begin(),
488 ie = Asm.end(); it != ie; ++it, ++Index)
489 if (&*it == SD->getFragment()->getParent())
490 break;
491 Value = SD->getFragment()->getAddress() + SD->getOffset();
494 Type = RIT_Vanilla;
497 // The value which goes in the fixup is current value of the expression.
498 Fixup.FixedValue = Value + Fixup.Value.getConstant();
500 unsigned Log2Size = Log2_32(Fixup.Size);
501 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
503 // struct relocation_info (8 bytes)
504 MachRelocationEntry MRE;
505 MRE.Word0 = Address;
506 MRE.Word1 = ((Index << 0) |
507 (IsPCRel << 24) |
508 (Log2Size << 25) |
509 (IsExtern << 27) |
510 (Type << 28));
511 Relocs.push_back(MRE);
514 void BindIndirectSymbols(MCAssembler &Asm,
515 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
516 // This is the point where 'as' creates actual symbols for indirect symbols
517 // (in the following two passes). It would be easier for us to do this
518 // sooner when we see the attribute, but that makes getting the order in the
519 // symbol table much more complicated than it is worth.
521 // FIXME: Revisit this when the dust settles.
523 // Bind non lazy symbol pointers first.
524 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
525 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
526 // FIXME: cast<> support!
527 const MCSectionMachO &Section =
528 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
530 unsigned Type =
531 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
532 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
533 continue;
535 MCSymbolData *&Entry = SymbolMap[it->Symbol];
536 if (!Entry)
537 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
540 // Then lazy symbol pointers and symbol stubs.
541 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
542 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
543 // FIXME: cast<> support!
544 const MCSectionMachO &Section =
545 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
547 unsigned Type =
548 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
549 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
550 Type != MCSectionMachO::S_SYMBOL_STUBS)
551 continue;
553 MCSymbolData *&Entry = SymbolMap[it->Symbol];
554 if (!Entry) {
555 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
557 // Set the symbol type to undefined lazy, but only on construction.
559 // FIXME: Do not hardcode.
560 Entry->setFlags(Entry->getFlags() | 0x0001);
565 /// ComputeSymbolTable - Compute the symbol table data
567 /// \param StringTable [out] - The string table data.
568 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
569 /// string table.
570 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
571 std::vector<MachSymbolData> &LocalSymbolData,
572 std::vector<MachSymbolData> &ExternalSymbolData,
573 std::vector<MachSymbolData> &UndefinedSymbolData) {
574 // Build section lookup table.
575 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
576 unsigned Index = 1;
577 for (MCAssembler::iterator it = Asm.begin(),
578 ie = Asm.end(); it != ie; ++it, ++Index)
579 SectionIndexMap[&it->getSection()] = Index;
580 assert(Index <= 256 && "Too many sections!");
582 // Index 0 is always the empty string.
583 StringMap<uint64_t> StringIndexMap;
584 StringTable += '\x00';
586 // Build the symbol arrays and the string table, but only for non-local
587 // symbols.
589 // The particular order that we collect the symbols and create the string
590 // table, then sort the symbols is chosen to match 'as'. Even though it
591 // doesn't matter for correctness, this is important for letting us diff .o
592 // files.
593 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
594 ie = Asm.symbol_end(); it != ie; ++it) {
595 const MCSymbol &Symbol = it->getSymbol();
597 // Ignore assembler temporaries.
598 if (it->getSymbol().isTemporary())
599 continue;
601 if (!it->isExternal() && !Symbol.isUndefined())
602 continue;
604 uint64_t &Entry = StringIndexMap[Symbol.getName()];
605 if (!Entry) {
606 Entry = StringTable.size();
607 StringTable += Symbol.getName();
608 StringTable += '\x00';
611 MachSymbolData MSD;
612 MSD.SymbolData = it;
613 MSD.StringIndex = Entry;
615 if (Symbol.isUndefined()) {
616 MSD.SectionIndex = 0;
617 UndefinedSymbolData.push_back(MSD);
618 } else if (Symbol.isAbsolute()) {
619 MSD.SectionIndex = 0;
620 ExternalSymbolData.push_back(MSD);
621 } else {
622 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
623 assert(MSD.SectionIndex && "Invalid section index!");
624 ExternalSymbolData.push_back(MSD);
628 // Now add the data for local symbols.
629 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
630 ie = Asm.symbol_end(); it != ie; ++it) {
631 const MCSymbol &Symbol = it->getSymbol();
633 // Ignore assembler temporaries.
634 if (it->getSymbol().isTemporary())
635 continue;
637 if (it->isExternal() || Symbol.isUndefined())
638 continue;
640 uint64_t &Entry = StringIndexMap[Symbol.getName()];
641 if (!Entry) {
642 Entry = StringTable.size();
643 StringTable += Symbol.getName();
644 StringTable += '\x00';
647 MachSymbolData MSD;
648 MSD.SymbolData = it;
649 MSD.StringIndex = Entry;
651 if (Symbol.isAbsolute()) {
652 MSD.SectionIndex = 0;
653 LocalSymbolData.push_back(MSD);
654 } else {
655 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
656 assert(MSD.SectionIndex && "Invalid section index!");
657 LocalSymbolData.push_back(MSD);
661 // External and undefined symbols are required to be in lexicographic order.
662 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
663 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
665 // Set the symbol indices.
666 Index = 0;
667 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
668 LocalSymbolData[i].SymbolData->setIndex(Index++);
669 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
670 ExternalSymbolData[i].SymbolData->setIndex(Index++);
671 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
672 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
674 // The string table is padded to a multiple of 4.
676 // FIXME: Check to see if this varies per arch.
677 while (StringTable.size() % 4)
678 StringTable += '\x00';
681 void WriteObject(MCAssembler &Asm) {
682 unsigned NumSections = Asm.size();
684 // Compute the symbol -> symbol data map.
686 // FIXME: This should not be here.
687 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
688 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
689 ie = Asm.symbol_end(); it != ie; ++it)
690 SymbolMap[&it->getSymbol()] = it;
692 // Create symbol data for any indirect symbols.
693 BindIndirectSymbols(Asm, SymbolMap);
695 // Compute symbol table information.
696 SmallString<256> StringTable;
697 std::vector<MachSymbolData> LocalSymbolData;
698 std::vector<MachSymbolData> ExternalSymbolData;
699 std::vector<MachSymbolData> UndefinedSymbolData;
700 unsigned NumSymbols = Asm.symbol_size();
702 // No symbol table command is written if there are no symbols.
703 if (NumSymbols)
704 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
705 UndefinedSymbolData);
707 // The section data starts after the header, the segment load command (and
708 // section headers) and the symbol table.
709 unsigned NumLoadCommands = 1;
710 uint64_t LoadCommandsSize =
711 SegmentLoadCommand32Size + NumSections * Section32Size;
713 // Add the symbol table load command sizes, if used.
714 if (NumSymbols) {
715 NumLoadCommands += 2;
716 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
719 // Compute the total size of the section data, as well as its file size and
720 // vm size.
721 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
722 uint64_t SectionDataSize = 0;
723 uint64_t SectionDataFileSize = 0;
724 uint64_t VMSize = 0;
725 for (MCAssembler::iterator it = Asm.begin(),
726 ie = Asm.end(); it != ie; ++it) {
727 MCSectionData &SD = *it;
729 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
731 if (isVirtualSection(SD.getSection()))
732 continue;
734 SectionDataSize = std::max(SectionDataSize,
735 SD.getAddress() + SD.getSize());
736 SectionDataFileSize = std::max(SectionDataFileSize,
737 SD.getAddress() + SD.getFileSize());
740 // The section data is passed to 4 bytes.
742 // FIXME: Is this machine dependent?
743 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
744 SectionDataFileSize += SectionDataPadding;
746 // Write the prolog, starting with the header and load command...
747 WriteHeader32(NumLoadCommands, LoadCommandsSize,
748 Asm.getSubsectionsViaSymbols());
749 WriteSegmentLoadCommand32(NumSections, VMSize,
750 SectionDataStart, SectionDataSize);
752 // ... and then the section headers.
754 // We also compute the section relocations while we do this. Note that
755 // compute relocation info will also update the fixup to have the correct
756 // value; this will be overwrite the appropriate data in the fragment when
757 // it is written.
758 std::vector<MachRelocationEntry> RelocInfos;
759 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
760 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
761 ++it) {
762 MCSectionData &SD = *it;
764 // The assembler writes relocations in the reverse order they were seen.
766 // FIXME: It is probably more complicated than this.
767 unsigned NumRelocsStart = RelocInfos.size();
768 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
769 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
770 RelocInfos);
772 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
773 uint64_t SectionStart = SectionDataStart + SD.getAddress();
774 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
775 RelocTableEnd += NumRelocs * RelocationInfoSize;
778 // Write the symbol table load command, if used.
779 if (NumSymbols) {
780 unsigned FirstLocalSymbol = 0;
781 unsigned NumLocalSymbols = LocalSymbolData.size();
782 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
783 unsigned NumExternalSymbols = ExternalSymbolData.size();
784 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
785 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
786 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
787 unsigned NumSymTabSymbols =
788 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
789 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
790 uint64_t IndirectSymbolOffset = 0;
792 // If used, the indirect symbols are written after the section data.
793 if (NumIndirectSymbols)
794 IndirectSymbolOffset = RelocTableEnd;
796 // The symbol table is written after the indirect symbol data.
797 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
799 // The string table is written after symbol table.
800 uint64_t StringTableOffset =
801 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
802 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
803 StringTableOffset, StringTable.size());
805 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
806 FirstExternalSymbol, NumExternalSymbols,
807 FirstUndefinedSymbol, NumUndefinedSymbols,
808 IndirectSymbolOffset, NumIndirectSymbols);
811 // Write the actual section data.
812 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
813 WriteFileData(OS, *it, *this);
815 // Write the extra padding.
816 WriteZeros(SectionDataPadding);
818 // Write the relocation entries.
819 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
820 Write32(RelocInfos[i].Word0);
821 Write32(RelocInfos[i].Word1);
824 // Write the symbol table data, if used.
825 if (NumSymbols) {
826 // Write the indirect symbol entries.
827 for (MCAssembler::indirect_symbol_iterator
828 it = Asm.indirect_symbol_begin(),
829 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
830 // Indirect symbols in the non lazy symbol pointer section have some
831 // special handling.
832 const MCSectionMachO &Section =
833 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
834 unsigned Type =
835 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
836 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
837 // If this symbol is defined and internal, mark it as such.
838 if (it->Symbol->isDefined() &&
839 !SymbolMap.lookup(it->Symbol)->isExternal()) {
840 uint32_t Flags = ISF_Local;
841 if (it->Symbol->isAbsolute())
842 Flags |= ISF_Absolute;
843 Write32(Flags);
844 continue;
848 Write32(SymbolMap[it->Symbol]->getIndex());
851 // FIXME: Check that offsets match computed ones.
853 // Write the symbol table entries.
854 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
855 WriteNlist32(LocalSymbolData[i]);
856 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
857 WriteNlist32(ExternalSymbolData[i]);
858 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
859 WriteNlist32(UndefinedSymbolData[i]);
861 // Write the string table.
862 OS << StringTable.str();
867 /* *** */
869 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
872 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
873 : Kind(_Kind),
874 Parent(_Parent),
875 FileSize(~UINT64_C(0))
877 if (Parent)
878 Parent->getFragmentList().push_back(this);
881 MCFragment::~MCFragment() {
884 uint64_t MCFragment::getAddress() const {
885 assert(getParent() && "Missing Section!");
886 return getParent()->getAddress() + Offset;
889 /* *** */
891 MCSectionData::MCSectionData() : Section(0) {}
893 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
894 : Section(&_Section),
895 Alignment(1),
896 Address(~UINT64_C(0)),
897 Size(~UINT64_C(0)),
898 FileSize(~UINT64_C(0)),
899 LastFixupLookup(~0)
901 if (A)
902 A->getSectionList().push_back(this);
905 const MCSectionData::Fixup *
906 MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
907 // Use a one level cache to turn the common case of accessing the fixups in
908 // order into O(1) instead of O(N).
909 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
910 if (i >= End)
911 i = 0;
912 while (Count--) {
913 const Fixup &F = Fixups[i];
914 if (F.Fragment == Fragment && F.Offset == Offset) {
915 LastFixupLookup = i;
916 return &F;
919 ++i;
920 if (i == End)
921 i = 0;
924 return 0;
927 /* *** */
929 MCSymbolData::MCSymbolData() : Symbol(0) {}
931 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
932 uint64_t _Offset, MCAssembler *A)
933 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
934 IsExternal(false), IsPrivateExtern(false),
935 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
937 if (A)
938 A->getSymbolList().push_back(this);
941 /* *** */
943 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
944 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
948 MCAssembler::~MCAssembler() {
951 void MCAssembler::LayoutSection(MCSectionData &SD) {
952 uint64_t Address = SD.getAddress();
954 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
955 MCFragment &F = *it;
957 F.setOffset(Address - SD.getAddress());
959 // Evaluate fragment size.
960 switch (F.getKind()) {
961 case MCFragment::FT_Align: {
962 MCAlignFragment &AF = cast<MCAlignFragment>(F);
964 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
965 if (Size > AF.getMaxBytesToEmit())
966 AF.setFileSize(0);
967 else
968 AF.setFileSize(Size);
969 break;
972 case MCFragment::FT_Data:
973 F.setFileSize(F.getMaxFileSize());
974 break;
976 case MCFragment::FT_Fill: {
977 MCFillFragment &FF = cast<MCFillFragment>(F);
979 F.setFileSize(F.getMaxFileSize());
981 // If the fill value is constant, thats it.
982 if (FF.getValue().isAbsolute())
983 break;
985 // Otherwise, add fixups for the values.
986 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
987 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
988 FF.getValue(),FF.getValueSize());
989 SD.getFixups().push_back(Fix);
991 break;
994 case MCFragment::FT_Org: {
995 MCOrgFragment &OF = cast<MCOrgFragment>(F);
997 if (!OF.getOffset().isAbsolute())
998 llvm_unreachable("FIXME: Not yet implemented!");
999 uint64_t OrgOffset = OF.getOffset().getConstant();
1000 uint64_t Offset = Address - SD.getAddress();
1002 // FIXME: We need a way to communicate this error.
1003 if (OrgOffset < Offset)
1004 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1005 "' (at offset '" + Twine(Offset) + "'");
1007 F.setFileSize(OrgOffset - Offset);
1008 break;
1011 case MCFragment::FT_ZeroFill: {
1012 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1014 // Align the fragment offset; it is safe to adjust the offset freely since
1015 // this is only in virtual sections.
1016 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1017 F.setOffset(Aligned - SD.getAddress());
1019 // FIXME: This is misnamed.
1020 F.setFileSize(ZFF.getSize());
1021 break;
1025 Address += F.getFileSize();
1028 // Set the section sizes.
1029 SD.setSize(Address - SD.getAddress());
1030 if (isVirtualSection(SD.getSection()))
1031 SD.setFileSize(0);
1032 else
1033 SD.setFileSize(Address - SD.getAddress());
1036 /// WriteFileData - Write the \arg F data to the output file.
1037 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1038 MachObjectWriter &MOW) {
1039 uint64_t Start = OS.tell();
1040 (void) Start;
1042 ++EmittedFragments;
1044 // FIXME: Embed in fragments instead?
1045 switch (F.getKind()) {
1046 case MCFragment::FT_Align: {
1047 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1048 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1050 // FIXME: This error shouldn't actually occur (the front end should emit
1051 // multiple .align directives to enforce the semantics it wants), but is
1052 // severe enough that we want to report it. How to handle this?
1053 if (Count * AF.getValueSize() != AF.getFileSize())
1054 llvm_report_error("undefined .align directive, value size '" +
1055 Twine(AF.getValueSize()) +
1056 "' is not a divisor of padding size '" +
1057 Twine(AF.getFileSize()) + "'");
1059 for (uint64_t i = 0; i != Count; ++i) {
1060 switch (AF.getValueSize()) {
1061 default:
1062 assert(0 && "Invalid size!");
1063 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1064 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1065 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1066 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1069 break;
1072 case MCFragment::FT_Data:
1073 OS << cast<MCDataFragment>(F).getContents().str();
1074 break;
1076 case MCFragment::FT_Fill: {
1077 MCFillFragment &FF = cast<MCFillFragment>(F);
1079 int64_t Value = 0;
1080 if (FF.getValue().isAbsolute())
1081 Value = FF.getValue().getConstant();
1082 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1083 if (!FF.getValue().isAbsolute()) {
1084 // Find the fixup.
1086 // FIXME: Find a better way to write in the fixes.
1087 const MCSectionData::Fixup *Fixup =
1088 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1089 assert(Fixup && "Missing fixup for fill value!");
1090 Value = Fixup->FixedValue;
1093 switch (FF.getValueSize()) {
1094 default:
1095 assert(0 && "Invalid size!");
1096 case 1: MOW.Write8 (uint8_t (Value)); break;
1097 case 2: MOW.Write16(uint16_t(Value)); break;
1098 case 4: MOW.Write32(uint32_t(Value)); break;
1099 case 8: MOW.Write64(uint64_t(Value)); break;
1102 break;
1105 case MCFragment::FT_Org: {
1106 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1108 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1109 MOW.Write8(uint8_t(OF.getValue()));
1111 break;
1114 case MCFragment::FT_ZeroFill: {
1115 assert(0 && "Invalid zero fill fragment in concrete section!");
1116 break;
1120 assert(OS.tell() - Start == F.getFileSize());
1123 /// WriteFileData - Write the \arg SD data to the output file.
1124 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1125 MachObjectWriter &MOW) {
1126 // Ignore virtual sections.
1127 if (isVirtualSection(SD.getSection())) {
1128 assert(SD.getFileSize() == 0);
1129 return;
1132 uint64_t Start = OS.tell();
1133 (void) Start;
1135 for (MCSectionData::const_iterator it = SD.begin(),
1136 ie = SD.end(); it != ie; ++it)
1137 WriteFileData(OS, *it, MOW);
1139 // Add section padding.
1140 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1141 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1143 assert(OS.tell() - Start == SD.getFileSize());
1146 void MCAssembler::Finish() {
1147 // Layout the concrete sections and fragments.
1148 uint64_t Address = 0;
1149 MCSectionData *Prev = 0;
1150 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1151 MCSectionData &SD = *it;
1153 // Skip virtual sections.
1154 if (isVirtualSection(SD.getSection()))
1155 continue;
1157 // Align this section if necessary by adding padding bytes to the previous
1158 // section.
1159 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1160 assert(Prev && "Missing prev section!");
1161 Prev->setFileSize(Prev->getFileSize() + Pad);
1162 Address += Pad;
1165 // Layout the section fragments and its size.
1166 SD.setAddress(Address);
1167 LayoutSection(SD);
1168 Address += SD.getFileSize();
1170 Prev = &SD;
1173 // Layout the virtual sections.
1174 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1175 MCSectionData &SD = *it;
1177 if (!isVirtualSection(SD.getSection()))
1178 continue;
1180 SD.setAddress(Address);
1181 LayoutSection(SD);
1182 Address += SD.getSize();
1185 // Write the object file.
1186 MachObjectWriter MOW(OS);
1187 MOW.WriteObject(*this);
1189 OS.flush();