blob: cf02cc15c5a8b5096fb4a692c92361edc122f050 [file] [log] [blame]
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001//===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar0adcd352009-08-25 21:10:45 +000010#define DEBUG_TYPE "assembler"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000011#include "llvm/MC/MCAssembler.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000012#include "llvm/MC/MCExpr.h"
Chris Lattnerbea2c952009-08-22 19:19:12 +000013#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000014#include "llvm/MC/MCSymbol.h"
15#include "llvm/MC/MCValue.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000016#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000017#include "llvm/ADT/SmallString.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000018#include "llvm/ADT/Statistic.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000019#include "llvm/ADT/StringExtras.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000020#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000021#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000022#include "llvm/Support/ErrorHandling.h"
Chris Lattner45f8c092010-02-02 19:38:14 +000023#include "llvm/Support/MachO.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000024#include "llvm/Support/raw_ostream.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000025#include "llvm/Support/Debug.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000026
27// FIXME: Gross.
28#include "../Target/X86/X86FixupKinds.h"
29
Chris Lattner23132b12009-08-24 03:52:50 +000030#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000031using namespace llvm;
32
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000033class MachObjectWriter;
34
Daniel Dunbar0adcd352009-08-25 21:10:45 +000035STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000037// FIXME FIXME FIXME: There are number of places in this file where we convert
38// what is a 64-bit assembler value used for computation into a value in the
39// object file, which may truncate it. We should detect that truncation where
40// invalid and report errors back.
41
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000042static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
43 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000044
Kevin Enderby6e720482010-02-23 18:26:34 +000045static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
46
Daniel Dunbard5a8e982009-08-28 05:49:21 +000047/// isVirtualSection - Check if this is a section which does not actually exist
48/// in the object file.
49static bool isVirtualSection(const MCSection &Section) {
50 // FIXME: Lame.
51 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
52 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
53 return (Type == MCSectionMachO::S_ZEROFILL);
54}
55
Duncan Sands9a7795c2010-02-17 14:52:22 +000056static unsigned getFixupKindLog2Size(unsigned Kind) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000057 switch (Kind) {
58 default: llvm_unreachable("invalid fixup kind!");
Daniel Dunbarf6346762010-02-13 09:29:02 +000059 case X86::reloc_pcrel_1byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000060 case FK_Data_1: return 0;
61 case FK_Data_2: return 1;
Daniel Dunbarf6346762010-02-13 09:29:02 +000062 case X86::reloc_pcrel_4byte:
63 case X86::reloc_riprel_4byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000064 case FK_Data_4: return 2;
65 case FK_Data_8: return 3;
66 }
67}
68
Duncan Sands9a7795c2010-02-17 14:52:22 +000069static bool isFixupKindPCRel(unsigned Kind) {
Daniel Dunbar591047f2010-02-13 09:45:59 +000070 switch (Kind) {
71 default:
72 return false;
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 return true;
77 }
78}
79
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000080class MachObjectWriter {
81 // See <mach-o/loader.h>.
82 enum {
83 Header_Magic32 = 0xFEEDFACE,
84 Header_Magic64 = 0xFEEDFACF
85 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +000086
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000087 static const unsigned Header32Size = 28;
88 static const unsigned Header64Size = 32;
89 static const unsigned SegmentLoadCommand32Size = 56;
90 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000091 static const unsigned SymtabLoadCommandSize = 24;
92 static const unsigned DysymtabLoadCommandSize = 80;
93 static const unsigned Nlist32Size = 12;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000094 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000095
96 enum HeaderFileType {
97 HFT_Object = 0x1
98 };
99
Daniel Dunbar6009db42009-08-26 21:22:22 +0000100 enum HeaderFlags {
101 HF_SubsectionsViaSymbols = 0x2000
102 };
103
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000104 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000105 LCT_Segment = 0x1,
106 LCT_Symtab = 0x2,
107 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000108 };
109
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000110 // See <mach-o/nlist.h>.
111 enum SymbolTypeType {
112 STT_Undefined = 0x00,
113 STT_Absolute = 0x02,
114 STT_Section = 0x0e
115 };
116
117 enum SymbolTypeFlags {
118 // If any of these bits are set, then the entry is a stab entry number (see
119 // <mach-o/stab.h>. Otherwise the other masks apply.
120 STF_StabsEntryMask = 0xe0,
121
122 STF_TypeMask = 0x0e,
123 STF_External = 0x01,
124 STF_PrivateExtern = 0x10
125 };
126
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000127 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
128 /// symbol entry.
129 enum IndirectSymbolFlags {
130 ISF_Local = 0x80000000,
131 ISF_Absolute = 0x40000000
132 };
133
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000134 /// RelocationFlags - Special flags for addresses.
135 enum RelocationFlags {
136 RF_Scattered = 0x80000000
137 };
138
139 enum RelocationInfoType {
140 RIT_Vanilla = 0,
141 RIT_Pair = 1,
142 RIT_Difference = 2,
143 RIT_PreboundLazyPointer = 3,
144 RIT_LocalDifference = 4
145 };
146
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000147 /// MachSymbolData - Helper struct for containing some precomputed information
148 /// on symbols.
149 struct MachSymbolData {
150 MCSymbolData *SymbolData;
151 uint64_t StringIndex;
152 uint8_t SectionIndex;
153
154 // Support lexicographic sorting.
155 bool operator<(const MachSymbolData &RHS) const {
156 const std::string &Name = SymbolData->getSymbol().getName();
157 return Name < RHS.SymbolData->getSymbol().getName();
158 }
159 };
160
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000161 raw_ostream &OS;
162 bool IsLSB;
163
164public:
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000165 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000166 : OS(_OS), IsLSB(_IsLSB) {
167 }
168
169 /// @name Helper Methods
170 /// @{
171
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000172 void Write8(uint8_t Value) {
173 OS << char(Value);
174 }
175
176 void Write16(uint16_t Value) {
177 if (IsLSB) {
178 Write8(uint8_t(Value >> 0));
179 Write8(uint8_t(Value >> 8));
180 } else {
181 Write8(uint8_t(Value >> 8));
182 Write8(uint8_t(Value >> 0));
183 }
184 }
185
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000186 void Write32(uint32_t Value) {
187 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000188 Write16(uint16_t(Value >> 0));
189 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000190 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000191 Write16(uint16_t(Value >> 16));
192 Write16(uint16_t(Value >> 0));
193 }
194 }
195
196 void Write64(uint64_t Value) {
197 if (IsLSB) {
198 Write32(uint32_t(Value >> 0));
199 Write32(uint32_t(Value >> 32));
200 } else {
201 Write32(uint32_t(Value >> 32));
202 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000203 }
204 }
205
206 void WriteZeros(unsigned N) {
207 const char Zeros[16] = { 0 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000208
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000209 for (unsigned i = 0, e = N / 16; i != e; ++i)
210 OS << StringRef(Zeros, 16);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000211
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000212 OS << StringRef(Zeros, N % 16);
213 }
214
Daniel Dunbar2928c832009-11-06 10:58:06 +0000215 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000216 OS << Str;
217 if (ZeroFillSize)
218 WriteZeros(ZeroFillSize - Str.size());
219 }
220
221 /// @}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000222
Daniel Dunbar6009db42009-08-26 21:22:22 +0000223 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
224 bool SubsectionsViaSymbols) {
225 uint32_t Flags = 0;
226
227 if (SubsectionsViaSymbols)
228 Flags |= HF_SubsectionsViaSymbols;
229
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000230 // struct mach_header (28 bytes)
231
232 uint64_t Start = OS.tell();
233 (void) Start;
234
235 Write32(Header_Magic32);
236
237 // FIXME: Support cputype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000238 Write32(MachO::CPUTypeI386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000239 // FIXME: Support cpusubtype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000240 Write32(MachO::CPUSubType_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000241 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000242 Write32(NumLoadCommands); // Object files have a single load command, the
243 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000244 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000245 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000246
247 assert(OS.tell() - Start == Header32Size);
248 }
249
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000250 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
251 ///
252 /// \arg NumSections - The number of sections in this segment.
253 /// \arg SectionDataSize - The total size of the sections.
254 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000255 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000256 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000257 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000258 // struct segment_command (56 bytes)
259
260 uint64_t Start = OS.tell();
261 (void) Start;
262
263 Write32(LCT_Segment);
264 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
265
266 WriteString("", 16);
267 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000268 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000269 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000270 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000271 Write32(0x7); // maxprot
272 Write32(0x7); // initprot
273 Write32(NumSections);
274 Write32(0); // flags
275
276 assert(OS.tell() - Start == SegmentLoadCommand32Size);
277 }
278
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000279 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
280 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000281 // The offset is unused for virtual sections.
282 if (isVirtualSection(SD.getSection())) {
283 assert(SD.getFileSize() == 0 && "Invalid file size!");
284 FileOffset = 0;
285 }
286
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000287 // struct section (68 bytes)
288
289 uint64_t Start = OS.tell();
290 (void) Start;
291
292 // FIXME: cast<> support!
293 const MCSectionMachO &Section =
294 static_cast<const MCSectionMachO&>(SD.getSection());
295 WriteString(Section.getSectionName(), 16);
296 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000297 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000298 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000299 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000300
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000301 unsigned Flags = Section.getTypeAndAttributes();
302 if (SD.hasInstructions())
303 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
304
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000305 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
306 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000307 Write32(NumRelocations ? RelocationsStart : 0);
308 Write32(NumRelocations);
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000309 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000310 Write32(0); // reserved1
311 Write32(Section.getStubSize()); // reserved2
312
313 assert(OS.tell() - Start == Section32Size);
314 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000315
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000316 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
317 uint32_t StringTableOffset,
318 uint32_t StringTableSize) {
319 // struct symtab_command (24 bytes)
320
321 uint64_t Start = OS.tell();
322 (void) Start;
323
324 Write32(LCT_Symtab);
325 Write32(SymtabLoadCommandSize);
326 Write32(SymbolOffset);
327 Write32(NumSymbols);
328 Write32(StringTableOffset);
329 Write32(StringTableSize);
330
331 assert(OS.tell() - Start == SymtabLoadCommandSize);
332 }
333
334 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
335 uint32_t NumLocalSymbols,
336 uint32_t FirstExternalSymbol,
337 uint32_t NumExternalSymbols,
338 uint32_t FirstUndefinedSymbol,
339 uint32_t NumUndefinedSymbols,
340 uint32_t IndirectSymbolOffset,
341 uint32_t NumIndirectSymbols) {
342 // struct dysymtab_command (80 bytes)
343
344 uint64_t Start = OS.tell();
345 (void) Start;
346
347 Write32(LCT_Dysymtab);
348 Write32(DysymtabLoadCommandSize);
349 Write32(FirstLocalSymbol);
350 Write32(NumLocalSymbols);
351 Write32(FirstExternalSymbol);
352 Write32(NumExternalSymbols);
353 Write32(FirstUndefinedSymbol);
354 Write32(NumUndefinedSymbols);
355 Write32(0); // tocoff
356 Write32(0); // ntoc
357 Write32(0); // modtaboff
358 Write32(0); // nmodtab
359 Write32(0); // extrefsymoff
360 Write32(0); // nextrefsyms
361 Write32(IndirectSymbolOffset);
362 Write32(NumIndirectSymbols);
363 Write32(0); // extreloff
364 Write32(0); // nextrel
365 Write32(0); // locreloff
366 Write32(0); // nlocrel
367
368 assert(OS.tell() - Start == DysymtabLoadCommandSize);
369 }
370
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000371 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000372 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000373 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000374 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000375 uint16_t Flags = Data.getFlags();
376 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000377
378 // Set the N_TYPE bits. See <mach-o/nlist.h>.
379 //
380 // FIXME: Are the prebound or indirect fields possible here?
381 if (Symbol.isUndefined())
382 Type = STT_Undefined;
383 else if (Symbol.isAbsolute())
384 Type = STT_Absolute;
385 else
386 Type = STT_Section;
387
388 // FIXME: Set STAB bits.
389
Daniel Dunbar5e835962009-08-26 02:48:04 +0000390 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000391 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000392
393 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000394 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000395 Type |= STF_External;
396
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000397 // Compute the symbol address.
398 if (Symbol.isDefined()) {
399 if (Symbol.isAbsolute()) {
400 llvm_unreachable("FIXME: Not yet implemented!");
401 } else {
402 Address = Data.getFragment()->getAddress() + Data.getOffset();
403 }
404 } else if (Data.isCommon()) {
405 // Common symbols are encoded with the size in the address
406 // field, and their alignment in the flags.
407 Address = Data.getCommonSize();
408
409 // Common alignment is packed into the 'desc' bits.
410 if (unsigned Align = Data.getCommonAlignment()) {
411 unsigned Log2Size = Log2_32(Align);
412 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
413 if (Log2Size > 15)
414 llvm_report_error("invalid 'common' alignment '" +
415 Twine(Align) + "'");
416 // FIXME: Keep this mask with the SymbolFlags enumeration.
417 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
418 }
419 }
420
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000421 // struct nlist (12 bytes)
422
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000423 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000424 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000425 Write8(MSD.SectionIndex);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000426
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000427 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
428 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000429 Write16(Flags);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000430 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000431 }
432
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000433 struct MachRelocationEntry {
434 uint32_t Word0;
435 uint32_t Word1;
436 };
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000437 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000438 MCAsmFixup &Fixup,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000439 const MCValue &Target,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000440 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
441 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000442 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000443 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000444 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000445 unsigned Type = RIT_Vanilla;
446
447 // See <reloc.h>.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000448 const MCSymbol *A = Target.getSymA();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000449 MCSymbolData *SD = SymbolMap.lookup(A);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000450
451 if (!SD->getFragment())
452 llvm_report_error("symbol '" + A->getName() +
453 "' can not be undefined in a subtraction expression");
454
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000455 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
456 uint32_t Value2 = 0;
457
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000458 if (const MCSymbol *B = Target.getSymB()) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000459 MCSymbolData *SD = SymbolMap.lookup(B);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000460
461 if (!SD->getFragment())
462 llvm_report_error("symbol '" + B->getName() +
463 "' can not be undefined in a subtraction expression");
464
465 Type = RIT_LocalDifference;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000466 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
467 }
468
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000469 // The value which goes in the fixup is current value of the expression.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000470 Fixup.FixedValue = Value - Value2 + Target.getConstant();
Daniel Dunbare180fa92010-03-09 21:27:30 +0000471 if (IsPCRel)
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000472 Fixup.FixedValue -= Address;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000473
474 // If this fixup is a vanilla PC relative relocation for a local label, we
475 // don't need a relocation.
476 //
477 // FIXME: Implement proper atom support.
478 if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary() &&
479 !Target.getSymB())
480 return;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000481
482 MachRelocationEntry MRE;
483 MRE.Word0 = ((Address << 0) |
484 (Type << 24) |
485 (Log2Size << 28) |
486 (IsPCRel << 30) |
487 RF_Scattered);
488 MRE.Word1 = Value;
489 Relocs.push_back(MRE);
490
491 if (Type == RIT_LocalDifference) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000492 MachRelocationEntry MRE;
493 MRE.Word0 = ((0 << 0) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000494 (RIT_Pair << 24) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000495 (Log2Size << 28) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000496 (IsPCRel << 30) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000497 RF_Scattered);
498 MRE.Word1 = Value2;
499 Relocs.push_back(MRE);
500 }
501 }
502
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000503 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000504 MCAsmFixup &Fixup,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000505 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
506 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000507 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
508 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
509
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000510 MCValue Target;
511 if (!Fixup.Value->EvaluateAsRelocatable(Target))
512 llvm_report_error("expected relocatable expression");
513
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000514 // If this is a difference or a defined symbol plus an offset, then we need
515 // a scattered relocation entry.
516 uint32_t Offset = Target.getConstant();
517 if (IsPCRel)
518 Offset += 1 << Log2Size;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000519 if (Target.getSymB() ||
520 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000521 Offset))
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000522 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000523 SymbolMap, Relocs);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000524
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000525 // See <reloc.h>.
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000526 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000527 uint32_t Value = 0;
528 unsigned Index = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000529 unsigned IsExtern = 0;
530 unsigned Type = 0;
531
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000532 if (Target.isAbsolute()) { // constant
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000533 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000534 //
535 // FIXME: When is this generated?
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000536 Type = RIT_Vanilla;
537 Value = 0;
538 llvm_unreachable("FIXME: Not yet implemented!");
539 } else {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000540 const MCSymbol *Symbol = Target.getSymA();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000541 MCSymbolData *SD = SymbolMap.lookup(Symbol);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000542
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000543 if (Symbol->isUndefined()) {
544 IsExtern = 1;
545 Index = SD->getIndex();
546 Value = 0;
547 } else {
548 // The index is the section ordinal.
549 //
550 // FIXME: O(N)
551 Index = 1;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000552 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
553 for (; it != ie; ++it, ++Index)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000554 if (&*it == SD->getFragment()->getParent())
555 break;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000556 assert(it != ie && "Unable to find section index!");
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000557 Value = SD->getFragment()->getAddress() + SD->getOffset();
558 }
559
560 Type = RIT_Vanilla;
561 }
562
563 // The value which goes in the fixup is current value of the expression.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000564 Fixup.FixedValue = Value + Target.getConstant();
Daniel Dunbare180fa92010-03-09 21:27:30 +0000565 if (IsPCRel)
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000566 Fixup.FixedValue -= Address;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000567
568 // If this fixup is a vanilla PC relative relocation for a local label, we
569 // don't need a relocation.
570 //
571 // FIXME: Implement proper atom support.
572 if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary())
573 return;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000574
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000575 // struct relocation_info (8 bytes)
576 MachRelocationEntry MRE;
577 MRE.Word0 = Address;
578 MRE.Word1 = ((Index << 0) |
579 (IsPCRel << 24) |
580 (Log2Size << 25) |
581 (IsExtern << 27) |
582 (Type << 28));
583 Relocs.push_back(MRE);
584 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000585
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000586 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000587 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000588 // This is the point where 'as' creates actual symbols for indirect symbols
589 // (in the following two passes). It would be easier for us to do this
590 // sooner when we see the attribute, but that makes getting the order in the
591 // symbol table much more complicated than it is worth.
592 //
593 // FIXME: Revisit this when the dust settles.
594
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000595 // Bind non lazy symbol pointers first.
596 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
597 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
598 // FIXME: cast<> support!
599 const MCSectionMachO &Section =
600 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
601
602 unsigned Type =
603 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
604 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
605 continue;
606
607 MCSymbolData *&Entry = SymbolMap[it->Symbol];
608 if (!Entry)
609 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
610 }
611
612 // Then lazy symbol pointers and symbol stubs.
613 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
614 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
615 // FIXME: cast<> support!
616 const MCSectionMachO &Section =
617 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
618
619 unsigned Type =
620 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
621 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
622 Type != MCSectionMachO::S_SYMBOL_STUBS)
623 continue;
624
625 MCSymbolData *&Entry = SymbolMap[it->Symbol];
626 if (!Entry) {
627 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
628
629 // Set the symbol type to undefined lazy, but only on construction.
630 //
631 // FIXME: Do not hardcode.
632 Entry->setFlags(Entry->getFlags() | 0x0001);
633 }
634 }
635 }
636
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000637 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000638 ///
639 /// \param StringTable [out] - The string table data.
640 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
641 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000642 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
643 std::vector<MachSymbolData> &LocalSymbolData,
644 std::vector<MachSymbolData> &ExternalSymbolData,
645 std::vector<MachSymbolData> &UndefinedSymbolData) {
646 // Build section lookup table.
647 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
648 unsigned Index = 1;
649 for (MCAssembler::iterator it = Asm.begin(),
650 ie = Asm.end(); it != ie; ++it, ++Index)
651 SectionIndexMap[&it->getSection()] = Index;
652 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000653
654 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000655 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000656 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000657
658 // Build the symbol arrays and the string table, but only for non-local
659 // symbols.
660 //
661 // The particular order that we collect the symbols and create the string
662 // table, then sort the symbols is chosen to match 'as'. Even though it
663 // doesn't matter for correctness, this is important for letting us diff .o
664 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000665 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
666 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000667 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000668
Daniel Dunbar959fd882009-08-26 22:13:22 +0000669 // Ignore assembler temporaries.
670 if (it->getSymbol().isTemporary())
671 continue;
672
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000673 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000674 continue;
675
676 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000677 if (!Entry) {
678 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000679 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000680 StringTable += '\x00';
681 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000682
683 MachSymbolData MSD;
684 MSD.SymbolData = it;
685 MSD.StringIndex = Entry;
686
687 if (Symbol.isUndefined()) {
688 MSD.SectionIndex = 0;
689 UndefinedSymbolData.push_back(MSD);
690 } else if (Symbol.isAbsolute()) {
691 MSD.SectionIndex = 0;
692 ExternalSymbolData.push_back(MSD);
693 } else {
694 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
695 assert(MSD.SectionIndex && "Invalid section index!");
696 ExternalSymbolData.push_back(MSD);
697 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000698 }
699
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000700 // Now add the data for local symbols.
701 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
702 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000703 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000704
Daniel Dunbar959fd882009-08-26 22:13:22 +0000705 // Ignore assembler temporaries.
706 if (it->getSymbol().isTemporary())
707 continue;
708
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000709 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000710 continue;
711
712 uint64_t &Entry = StringIndexMap[Symbol.getName()];
713 if (!Entry) {
714 Entry = StringTable.size();
715 StringTable += Symbol.getName();
716 StringTable += '\x00';
717 }
718
719 MachSymbolData MSD;
720 MSD.SymbolData = it;
721 MSD.StringIndex = Entry;
722
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000723 if (Symbol.isAbsolute()) {
724 MSD.SectionIndex = 0;
725 LocalSymbolData.push_back(MSD);
726 } else {
727 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
728 assert(MSD.SectionIndex && "Invalid section index!");
729 LocalSymbolData.push_back(MSD);
730 }
731 }
732
733 // External and undefined symbols are required to be in lexicographic order.
734 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
735 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
736
Daniel Dunbarbe963552009-08-26 13:57:54 +0000737 // Set the symbol indices.
738 Index = 0;
739 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
740 LocalSymbolData[i].SymbolData->setIndex(Index++);
741 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
742 ExternalSymbolData[i].SymbolData->setIndex(Index++);
743 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
744 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
745
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000746 // The string table is padded to a multiple of 4.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000747 while (StringTable.size() % 4)
748 StringTable += '\x00';
749 }
750
751 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000752 unsigned NumSections = Asm.size();
753
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000754 // Compute the symbol -> symbol data map.
755 //
756 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000757 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000758 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
759 ie = Asm.symbol_end(); it != ie; ++it)
760 SymbolMap[&it->getSymbol()] = it;
761
762 // Create symbol data for any indirect symbols.
763 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000764
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000765 // Compute symbol table information.
766 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000767 std::vector<MachSymbolData> LocalSymbolData;
768 std::vector<MachSymbolData> ExternalSymbolData;
769 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000770 unsigned NumSymbols = Asm.symbol_size();
771
772 // No symbol table command is written if there are no symbols.
773 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000774 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
775 UndefinedSymbolData);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000776
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000777 // The section data starts after the header, the segment load command (and
778 // section headers) and the symbol table.
779 unsigned NumLoadCommands = 1;
780 uint64_t LoadCommandsSize =
781 SegmentLoadCommand32Size + NumSections * Section32Size;
782
783 // Add the symbol table load command sizes, if used.
784 if (NumSymbols) {
785 NumLoadCommands += 2;
786 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
787 }
788
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000789 // Compute the total size of the section data, as well as its file size and
790 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000791 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000792 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000793 uint64_t SectionDataFileSize = 0;
794 uint64_t VMSize = 0;
795 for (MCAssembler::iterator it = Asm.begin(),
796 ie = Asm.end(); it != ie; ++it) {
797 MCSectionData &SD = *it;
798
799 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
800
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000801 if (isVirtualSection(SD.getSection()))
802 continue;
803
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000804 SectionDataSize = std::max(SectionDataSize,
805 SD.getAddress() + SD.getSize());
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000806 SectionDataFileSize = std::max(SectionDataFileSize,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000807 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000808 }
809
Daniel Dunbar6b716532010-02-09 23:00:14 +0000810 // The section data is padded to 4 bytes.
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000811 //
812 // FIXME: Is this machine dependent?
813 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
814 SectionDataFileSize += SectionDataPadding;
815
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000816 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000817 WriteHeader32(NumLoadCommands, LoadCommandsSize,
818 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000819 WriteSegmentLoadCommand32(NumSections, VMSize,
820 SectionDataStart, SectionDataSize);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000821
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000822 // ... and then the section headers.
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000823 //
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000824 // We also compute the section relocations while we do this. Note that
Daniel Dunbar6b716532010-02-09 23:00:14 +0000825 // computing relocation info will also update the fixup to have the correct
826 // value; this will overwrite the appropriate data in the fragment when it
827 // is written.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000828 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000829 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000830 for (MCAssembler::iterator it = Asm.begin(),
831 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000832 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000833
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000834 // The assembler writes relocations in the reverse order they were seen.
835 //
836 // FIXME: It is probably more complicated than this.
837 unsigned NumRelocsStart = RelocInfos.size();
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000838 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
839 ie2 = SD.rend(); it2 != ie2; ++it2)
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000840 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
841 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
842 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
843 SymbolMap, RelocInfos);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000844
845 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
846 uint64_t SectionStart = SectionDataStart + SD.getAddress();
847 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
848 RelocTableEnd += NumRelocs * RelocationInfoSize;
849 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000850
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000851 // Write the symbol table load command, if used.
852 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000853 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000854 unsigned NumLocalSymbols = LocalSymbolData.size();
855 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
856 unsigned NumExternalSymbols = ExternalSymbolData.size();
857 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
858 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000859 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
860 unsigned NumSymTabSymbols =
861 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
862 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
863 uint64_t IndirectSymbolOffset = 0;
864
865 // If used, the indirect symbols are written after the section data.
866 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000867 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000868
869 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000870 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000871
872 // The string table is written after symbol table.
873 uint64_t StringTableOffset =
874 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
875 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
876 StringTableOffset, StringTable.size());
877
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000878 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
879 FirstExternalSymbol, NumExternalSymbols,
880 FirstUndefinedSymbol, NumUndefinedSymbols,
881 IndirectSymbolOffset, NumIndirectSymbols);
882 }
883
884 // Write the actual section data.
885 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
886 WriteFileData(OS, *it, *this);
887
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000888 // Write the extra padding.
889 WriteZeros(SectionDataPadding);
890
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000891 // Write the relocation entries.
892 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
893 Write32(RelocInfos[i].Word0);
894 Write32(RelocInfos[i].Word1);
895 }
896
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000897 // Write the symbol table data, if used.
898 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000899 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000900 for (MCAssembler::indirect_symbol_iterator
901 it = Asm.indirect_symbol_begin(),
902 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
903 // Indirect symbols in the non lazy symbol pointer section have some
904 // special handling.
905 const MCSectionMachO &Section =
906 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
907 unsigned Type =
908 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
909 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
910 // If this symbol is defined and internal, mark it as such.
911 if (it->Symbol->isDefined() &&
912 !SymbolMap.lookup(it->Symbol)->isExternal()) {
913 uint32_t Flags = ISF_Local;
914 if (it->Symbol->isAbsolute())
915 Flags |= ISF_Absolute;
916 Write32(Flags);
917 continue;
918 }
919 }
920
Daniel Dunbarbe963552009-08-26 13:57:54 +0000921 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000922 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000923
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000924 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000925
926 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000927 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
928 WriteNlist32(LocalSymbolData[i]);
929 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
930 WriteNlist32(ExternalSymbolData[i]);
931 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
932 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000933
934 // Write the string table.
935 OS << StringTable.str();
936 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000937 }
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000938
939 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000940 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
941
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000942 // FIXME: Endianness assumption.
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000943 assert(Fixup.Offset + Size <= DF.getContents().size() &&
944 "Invalid fixup offset!");
945 for (unsigned i = 0; i != Size; ++i)
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000946 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
947 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000948};
949
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000950/* *** */
951
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000952MCFragment::MCFragment() : Kind(FragmentType(~0)) {
953}
954
Daniel Dunbar5e835962009-08-26 02:48:04 +0000955MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000956 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000957 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000958 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000959{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000960 if (Parent)
961 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000962}
963
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000964MCFragment::~MCFragment() {
965}
966
Daniel Dunbar5e835962009-08-26 02:48:04 +0000967uint64_t MCFragment::getAddress() const {
968 assert(getParent() && "Missing Section!");
969 return getParent()->getAddress() + Offset;
970}
971
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000972/* *** */
973
Daniel Dunbar81e40002009-08-27 00:38:04 +0000974MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000975
976MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000977 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000978 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000979 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000980 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000981 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000982 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000983{
984 if (A)
985 A->getSectionList().push_back(this);
986}
987
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000988/* *** */
989
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000990MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000991
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000992MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000993 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000994 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000995 IsExternal(false), IsPrivateExtern(false),
996 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000997{
998 if (A)
999 A->getSymbolList().push_back(this);
1000}
1001
1002/* *** */
1003
Daniel Dunbara03a3682009-08-31 08:07:55 +00001004MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
1005 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +00001006{
1007}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001008
1009MCAssembler::~MCAssembler() {
1010}
1011
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001012void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001013 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001014
1015 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1016 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001017
Daniel Dunbar6742e342009-08-26 04:13:32 +00001018 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001019
1020 // Evaluate fragment size.
1021 switch (F.getKind()) {
1022 case MCFragment::FT_Align: {
1023 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001024
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001025 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +00001026 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001027 AF.setFileSize(0);
1028 else
Daniel Dunbar6742e342009-08-26 04:13:32 +00001029 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001030 break;
1031 }
1032
1033 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +00001034 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001035 F.setFileSize(F.getMaxFileSize());
1036 break;
1037
1038 case MCFragment::FT_Org: {
1039 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1040
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001041 MCValue Target;
1042 if (!OF.getOffset().EvaluateAsRelocatable(Target))
1043 llvm_report_error("expected relocatable expression");
1044
1045 if (!Target.isAbsolute())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001046 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001047 uint64_t OrgOffset = Target.getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +00001048 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001049
1050 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001051 if (OrgOffset < Offset)
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001052 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +00001053 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001054
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001055 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001056 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001057 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001058
1059 case MCFragment::FT_ZeroFill: {
1060 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1061
1062 // Align the fragment offset; it is safe to adjust the offset freely since
1063 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +00001064 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1065 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001066
1067 // FIXME: This is misnamed.
1068 F.setFileSize(ZFF.getSize());
1069 break;
1070 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001071 }
1072
Daniel Dunbar6742e342009-08-26 04:13:32 +00001073 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001074 }
1075
Daniel Dunbar6742e342009-08-26 04:13:32 +00001076 // Set the section sizes.
1077 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001078 if (isVirtualSection(SD.getSection()))
1079 SD.setFileSize(0);
1080 else
1081 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001082}
1083
Kevin Enderby6e720482010-02-23 18:26:34 +00001084/// WriteNopData - Write optimal nops to the output file for the \arg Count
1085/// bytes. This returns the number of bytes written. It may return 0 if
1086/// the \arg Count is more than the maximum optimal nops.
1087///
1088/// FIXME this is X86 32-bit specific and should move to a better place.
1089static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
Kevin Enderby76687082010-02-23 21:41:24 +00001090 static const uint8_t Nops[16][16] = {
1091 // nop
1092 {0x90},
1093 // xchg %ax,%ax
1094 {0x66, 0x90},
1095 // nopl (%[re]ax)
1096 {0x0f, 0x1f, 0x00},
1097 // nopl 0(%[re]ax)
1098 {0x0f, 0x1f, 0x40, 0x00},
1099 // nopl 0(%[re]ax,%[re]ax,1)
1100 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1101 // nopw 0(%[re]ax,%[re]ax,1)
1102 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1103 // nopl 0L(%[re]ax)
1104 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1105 // nopl 0L(%[re]ax,%[re]ax,1)
1106 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1107 // nopw 0L(%[re]ax,%[re]ax,1)
1108 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1109 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1110 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1111 // nopl 0(%[re]ax,%[re]ax,1)
1112 // nopw 0(%[re]ax,%[re]ax,1)
1113 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1114 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1115 // nopw 0(%[re]ax,%[re]ax,1)
1116 // nopw 0(%[re]ax,%[re]ax,1)
1117 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1118 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1119 // nopw 0(%[re]ax,%[re]ax,1)
1120 // nopl 0L(%[re]ax) */
1121 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1122 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1123 // nopl 0L(%[re]ax)
1124 // nopl 0L(%[re]ax)
1125 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1126 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1127 // nopl 0L(%[re]ax)
1128 // nopl 0L(%[re]ax,%[re]ax,1)
1129 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1130 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1131 };
1132
1133 if (Count > 15)
1134 return 0;
1135
Kevin Enderby6e720482010-02-23 18:26:34 +00001136 for (uint64_t i = 0; i < Count; i++)
Kevin Enderby76687082010-02-23 21:41:24 +00001137 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +00001138
1139 return Count;
1140}
1141
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001142/// WriteFileData - Write the \arg F data to the output file.
1143static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1144 MachObjectWriter &MOW) {
1145 uint64_t Start = OS.tell();
1146 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001147
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001148 ++EmittedFragments;
1149
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001150 // FIXME: Embed in fragments instead?
1151 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001152 case MCFragment::FT_Align: {
1153 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1154 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1155
1156 // FIXME: This error shouldn't actually occur (the front end should emit
1157 // multiple .align directives to enforce the semantics it wants), but is
1158 // severe enough that we want to report it. How to handle this?
1159 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001160 llvm_report_error("undefined .align directive, value size '" +
1161 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001162 "' is not a divisor of padding size '" +
1163 Twine(AF.getFileSize()) + "'");
1164
Kevin Enderby6e720482010-02-23 18:26:34 +00001165 // See if we are aligning with nops, and if so do that first to try to fill
1166 // the Count bytes. Then if that did not fill any bytes or there are any
1167 // bytes left to fill use the the Value and ValueSize to fill the rest.
1168 if (AF.getEmitNops()) {
1169 uint64_t NopByteCount = WriteNopData(Count, MOW);
1170 Count -= NopByteCount;
1171 }
1172
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001173 for (uint64_t i = 0; i != Count; ++i) {
1174 switch (AF.getValueSize()) {
1175 default:
1176 assert(0 && "Invalid size!");
1177 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1178 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1179 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1180 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1181 }
1182 }
1183 break;
1184 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001185
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001186 case MCFragment::FT_Data: {
1187 MCDataFragment &DF = cast<MCDataFragment>(F);
1188
1189 // Apply the fixups.
1190 //
1191 // FIXME: Move elsewhere.
1192 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1193 ie = DF.fixup_end(); it != ie; ++it)
1194 MOW.ApplyFixup(*it, DF);
1195
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001196 OS << cast<MCDataFragment>(F).getContents().str();
1197 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001198 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001199
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001200 case MCFragment::FT_Fill: {
1201 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001202 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1203 switch (FF.getValueSize()) {
1204 default:
1205 assert(0 && "Invalid size!");
Daniel Dunbara4766d72010-02-13 09:28:32 +00001206 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1207 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1208 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1209 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001210 }
1211 }
1212 break;
1213 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001214
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001215 case MCFragment::FT_Org: {
1216 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1217
1218 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1219 MOW.Write8(uint8_t(OF.getValue()));
1220
1221 break;
1222 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001223
1224 case MCFragment::FT_ZeroFill: {
1225 assert(0 && "Invalid zero fill fragment in concrete section!");
1226 break;
1227 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001228 }
1229
1230 assert(OS.tell() - Start == F.getFileSize());
1231}
1232
1233/// WriteFileData - Write the \arg SD data to the output file.
1234static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1235 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001236 // Ignore virtual sections.
1237 if (isVirtualSection(SD.getSection())) {
1238 assert(SD.getFileSize() == 0);
1239 return;
1240 }
1241
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001242 uint64_t Start = OS.tell();
1243 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001244
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001245 for (MCSectionData::const_iterator it = SD.begin(),
1246 ie = SD.end(); it != ie; ++it)
1247 WriteFileData(OS, *it, MOW);
1248
Daniel Dunbar6742e342009-08-26 04:13:32 +00001249 // Add section padding.
1250 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1251 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1252
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001253 assert(OS.tell() - Start == SD.getFileSize());
1254}
1255
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001256void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001257 DEBUG_WITH_TYPE("mc-dump", {
1258 llvm::errs() << "assembler backend - pre-layout\n--\n";
1259 dump(); });
1260
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001261 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001262 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001263 MCSectionData *Prev = 0;
1264 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001265 MCSectionData &SD = *it;
1266
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001267 // Skip virtual sections.
1268 if (isVirtualSection(SD.getSection()))
1269 continue;
1270
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001271 // Align this section if necessary by adding padding bytes to the previous
1272 // section.
1273 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1274 assert(Prev && "Missing prev section!");
1275 Prev->setFileSize(Prev->getFileSize() + Pad);
1276 Address += Pad;
1277 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001278
1279 // Layout the section fragments and its size.
1280 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001281 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001282 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001283
1284 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001285 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001286
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001287 // Layout the virtual sections.
1288 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1289 MCSectionData &SD = *it;
1290
1291 if (!isVirtualSection(SD.getSection()))
1292 continue;
1293
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001294 // Align this section if necessary by adding padding bytes to the previous
1295 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +00001296 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001297 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001298
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001299 SD.setAddress(Address);
1300 LayoutSection(SD);
1301 Address += SD.getSize();
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001302
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001303 }
1304
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001305 DEBUG_WITH_TYPE("mc-dump", {
1306 llvm::errs() << "assembler backend - post-layout\n--\n";
1307 dump(); });
1308
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001309 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001310 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001311 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001312
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001313 OS.flush();
1314}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001315
1316
1317// Debugging methods
1318
1319namespace llvm {
1320
1321raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001322 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1323 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001324 return OS;
1325}
1326
1327}
1328
1329void MCFragment::dump() {
1330 raw_ostream &OS = llvm::errs();
1331
1332 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1333 << " FileSize:" << FileSize;
1334
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001335 OS << ">";
1336}
1337
1338void MCAlignFragment::dump() {
1339 raw_ostream &OS = llvm::errs();
1340
1341 OS << "<MCAlignFragment ";
1342 this->MCFragment::dump();
1343 OS << "\n ";
1344 OS << " Alignment:" << getAlignment()
1345 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1346 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1347}
1348
1349void MCDataFragment::dump() {
1350 raw_ostream &OS = llvm::errs();
1351
1352 OS << "<MCDataFragment ";
1353 this->MCFragment::dump();
1354 OS << "\n ";
1355 OS << " Contents:[";
1356 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1357 if (i) OS << ",";
1358 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1359 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001360 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001361
1362 if (!getFixups().empty()) {
1363 OS << ",\n ";
1364 OS << " Fixups:[";
1365 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001366 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001367 OS << *it;
1368 }
1369 OS << "]";
1370 }
1371
1372 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001373}
1374
1375void MCFillFragment::dump() {
1376 raw_ostream &OS = llvm::errs();
1377
1378 OS << "<MCFillFragment ";
1379 this->MCFragment::dump();
1380 OS << "\n ";
1381 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1382 << " Count:" << getCount() << ">";
1383}
1384
1385void MCOrgFragment::dump() {
1386 raw_ostream &OS = llvm::errs();
1387
1388 OS << "<MCOrgFragment ";
1389 this->MCFragment::dump();
1390 OS << "\n ";
1391 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1392}
1393
1394void MCZeroFillFragment::dump() {
1395 raw_ostream &OS = llvm::errs();
1396
1397 OS << "<MCZeroFillFragment ";
1398 this->MCFragment::dump();
1399 OS << "\n ";
1400 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1401}
1402
1403void MCSectionData::dump() {
1404 raw_ostream &OS = llvm::errs();
1405
1406 OS << "<MCSectionData";
1407 OS << " Alignment:" << getAlignment() << " Address:" << Address
1408 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001409 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001410 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1411 if (it != begin()) OS << ",\n ";
1412 it->dump();
1413 }
1414 OS << "]>";
1415}
1416
1417void MCSymbolData::dump() {
1418 raw_ostream &OS = llvm::errs();
1419
1420 OS << "<MCSymbolData Symbol:" << getSymbol()
1421 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1422 << " Flags:" << getFlags() << " Index:" << getIndex();
1423 if (isCommon())
1424 OS << " (common, size:" << getCommonSize()
1425 << " align: " << getCommonAlignment() << ")";
1426 if (isExternal())
1427 OS << " (external)";
1428 if (isPrivateExtern())
1429 OS << " (private extern)";
1430 OS << ">";
1431}
1432
1433void MCAssembler::dump() {
1434 raw_ostream &OS = llvm::errs();
1435
1436 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001437 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001438 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1439 if (it != begin()) OS << ",\n ";
1440 it->dump();
1441 }
1442 OS << "],\n";
1443 OS << " Symbols:[";
1444
1445 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001446 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001447 it->dump();
1448 }
1449 OS << "]>\n";
1450}