blob: a207d9952b02c3a76bf9b03c4504d361e656077f [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 Dunbar18ff2cc2010-03-11 05:53:33 +000012#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000013#include "llvm/MC/MCExpr.h"
Chris Lattnerbea2c952009-08-22 19:19:12 +000014#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000015#include "llvm/MC/MCSymbol.h"
16#include "llvm/MC/MCValue.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000017#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000018#include "llvm/ADT/SmallString.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000019#include "llvm/ADT/Statistic.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000020#include "llvm/ADT/StringExtras.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000021#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000022#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000023#include "llvm/Support/ErrorHandling.h"
Chris Lattner45f8c092010-02-02 19:38:14 +000024#include "llvm/Support/MachO.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000025#include "llvm/Support/raw_ostream.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000026#include "llvm/Support/Debug.h"
Daniel Dunbaree0d8922010-03-13 22:10:17 +000027#include "llvm/Target/TargetRegistry.h"
Daniel Dunbardf3c8f22010-03-12 21:00:49 +000028#include "llvm/Target/TargetAsmBackend.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000029
30// FIXME: Gross.
31#include "../Target/X86/X86FixupKinds.h"
32
Chris Lattner23132b12009-08-24 03:52:50 +000033#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000034using namespace llvm;
35
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000036class MachObjectWriter;
37
Daniel Dunbar0adcd352009-08-25 21:10:45 +000038STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
39
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000040// FIXME FIXME FIXME: There are number of places in this file where we convert
41// what is a 64-bit assembler value used for computation into a value in the
42// object file, which may truncate it. We should detect that truncation where
43// invalid and report errors back.
44
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000045static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
46 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000047
Kevin Enderby6e720482010-02-23 18:26:34 +000048static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
49
Daniel Dunbard5a8e982009-08-28 05:49:21 +000050/// isVirtualSection - Check if this is a section which does not actually exist
51/// in the object file.
52static bool isVirtualSection(const MCSection &Section) {
53 // FIXME: Lame.
54 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
55 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
56 return (Type == MCSectionMachO::S_ZEROFILL);
57}
58
Duncan Sands9a7795c2010-02-17 14:52:22 +000059static unsigned getFixupKindLog2Size(unsigned Kind) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000060 switch (Kind) {
61 default: llvm_unreachable("invalid fixup kind!");
Daniel Dunbarf6346762010-02-13 09:29:02 +000062 case X86::reloc_pcrel_1byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000063 case FK_Data_1: return 0;
64 case FK_Data_2: return 1;
Daniel Dunbarf6346762010-02-13 09:29:02 +000065 case X86::reloc_pcrel_4byte:
66 case X86::reloc_riprel_4byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000067 case FK_Data_4: return 2;
68 case FK_Data_8: return 3;
69 }
70}
71
Duncan Sands9a7795c2010-02-17 14:52:22 +000072static bool isFixupKindPCRel(unsigned Kind) {
Daniel Dunbar591047f2010-02-13 09:45:59 +000073 switch (Kind) {
74 default:
75 return false;
76 case X86::reloc_pcrel_1byte:
77 case X86::reloc_pcrel_4byte:
78 case X86::reloc_riprel_4byte:
79 return true;
80 }
81}
82
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000083class MachObjectWriter {
84 // See <mach-o/loader.h>.
85 enum {
86 Header_Magic32 = 0xFEEDFACE,
87 Header_Magic64 = 0xFEEDFACF
88 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +000089
Daniel Dunbaree0d8922010-03-13 22:10:17 +000090 enum {
91 Header32Size = 28,
92 Header64Size = 32,
93 SegmentLoadCommand32Size = 56,
94 SegmentLoadCommand64Size = 72,
95 Section32Size = 68,
96 Section64Size = 80,
97 SymtabLoadCommandSize = 24,
98 DysymtabLoadCommandSize = 80,
99 Nlist32Size = 12,
100 Nlist64Size = 16,
101 RelocationInfoSize = 8
102 };
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000103
104 enum HeaderFileType {
105 HFT_Object = 0x1
106 };
107
Daniel Dunbar6009db42009-08-26 21:22:22 +0000108 enum HeaderFlags {
109 HF_SubsectionsViaSymbols = 0x2000
110 };
111
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000112 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000113 LCT_Segment = 0x1,
114 LCT_Symtab = 0x2,
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000115 LCT_Dysymtab = 0xb,
116 LCT_Segment64 = 0x19
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000117 };
118
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000119 // See <mach-o/nlist.h>.
120 enum SymbolTypeType {
121 STT_Undefined = 0x00,
122 STT_Absolute = 0x02,
123 STT_Section = 0x0e
124 };
125
126 enum SymbolTypeFlags {
127 // If any of these bits are set, then the entry is a stab entry number (see
128 // <mach-o/stab.h>. Otherwise the other masks apply.
129 STF_StabsEntryMask = 0xe0,
130
131 STF_TypeMask = 0x0e,
132 STF_External = 0x01,
133 STF_PrivateExtern = 0x10
134 };
135
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000136 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
137 /// symbol entry.
138 enum IndirectSymbolFlags {
139 ISF_Local = 0x80000000,
140 ISF_Absolute = 0x40000000
141 };
142
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000143 /// RelocationFlags - Special flags for addresses.
144 enum RelocationFlags {
145 RF_Scattered = 0x80000000
146 };
147
148 enum RelocationInfoType {
149 RIT_Vanilla = 0,
150 RIT_Pair = 1,
151 RIT_Difference = 2,
152 RIT_PreboundLazyPointer = 3,
153 RIT_LocalDifference = 4
154 };
155
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000156 /// MachSymbolData - Helper struct for containing some precomputed information
157 /// on symbols.
158 struct MachSymbolData {
159 MCSymbolData *SymbolData;
160 uint64_t StringIndex;
161 uint8_t SectionIndex;
162
163 // Support lexicographic sorting.
164 bool operator<(const MachSymbolData &RHS) const {
165 const std::string &Name = SymbolData->getSymbol().getName();
166 return Name < RHS.SymbolData->getSymbol().getName();
167 }
168 };
169
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000170 raw_ostream &OS;
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000171 unsigned Is64Bit : 1;
172 unsigned IsLSB : 1;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000173
174public:
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000175 MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLSB = true)
176 : OS(_OS), Is64Bit(_Is64Bit), IsLSB(_IsLSB) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000177 }
178
179 /// @name Helper Methods
180 /// @{
181
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000182 void Write8(uint8_t Value) {
183 OS << char(Value);
184 }
185
186 void Write16(uint16_t Value) {
187 if (IsLSB) {
188 Write8(uint8_t(Value >> 0));
189 Write8(uint8_t(Value >> 8));
190 } else {
191 Write8(uint8_t(Value >> 8));
192 Write8(uint8_t(Value >> 0));
193 }
194 }
195
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000196 void Write32(uint32_t Value) {
197 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000198 Write16(uint16_t(Value >> 0));
199 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000200 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000201 Write16(uint16_t(Value >> 16));
202 Write16(uint16_t(Value >> 0));
203 }
204 }
205
206 void Write64(uint64_t Value) {
207 if (IsLSB) {
208 Write32(uint32_t(Value >> 0));
209 Write32(uint32_t(Value >> 32));
210 } else {
211 Write32(uint32_t(Value >> 32));
212 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000213 }
214 }
215
216 void WriteZeros(unsigned N) {
217 const char Zeros[16] = { 0 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000218
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000219 for (unsigned i = 0, e = N / 16; i != e; ++i)
220 OS << StringRef(Zeros, 16);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000221
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000222 OS << StringRef(Zeros, N % 16);
223 }
224
Daniel Dunbar2928c832009-11-06 10:58:06 +0000225 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000226 OS << Str;
227 if (ZeroFillSize)
228 WriteZeros(ZeroFillSize - Str.size());
229 }
230
231 /// @}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000232
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000233 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
234 bool SubsectionsViaSymbols) {
Daniel Dunbar6009db42009-08-26 21:22:22 +0000235 uint32_t Flags = 0;
236
237 if (SubsectionsViaSymbols)
238 Flags |= HF_SubsectionsViaSymbols;
239
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000240 // struct mach_header (28 bytes) or
241 // struct mach_header_64 (32 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000242
243 uint64_t Start = OS.tell();
244 (void) Start;
245
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000246 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000247
248 // FIXME: Support cputype.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000249 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000250 // FIXME: Support cpusubtype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000251 Write32(MachO::CPUSubType_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000252 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000253 Write32(NumLoadCommands); // Object files have a single load command, the
254 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000255 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000256 Write32(Flags);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000257 if (Is64Bit)
258 Write32(0); // reserved
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000259
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000260 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000261 }
262
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000263 /// WriteSegmentLoadCommand - Write a segment load command.
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000264 ///
265 /// \arg NumSections - The number of sections in this segment.
266 /// \arg SectionDataSize - The total size of the sections.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000267 void WriteSegmentLoadCommand(unsigned NumSections,
268 uint64_t VMSize,
269 uint64_t SectionDataStartOffset,
270 uint64_t SectionDataSize) {
271 // struct segment_command (56 bytes) or
272 // struct segment_command_64 (72 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000273
274 uint64_t Start = OS.tell();
275 (void) Start;
276
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000277 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
278 SegmentLoadCommand32Size;
279 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
280 Write32(SegmentLoadCommandSize +
281 NumSections * (Is64Bit ? Section64Size : Section32Size));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000282
283 WriteString("", 16);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000284 if (Is64Bit) {
285 Write64(0); // vmaddr
286 Write64(VMSize); // vmsize
287 Write64(SectionDataStartOffset); // file offset
288 Write64(SectionDataSize); // file size
289 } else {
290 Write32(0); // vmaddr
291 Write32(VMSize); // vmsize
292 Write32(SectionDataStartOffset); // file offset
293 Write32(SectionDataSize); // file size
294 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000295 Write32(0x7); // maxprot
296 Write32(0x7); // initprot
297 Write32(NumSections);
298 Write32(0); // flags
299
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000300 assert(OS.tell() - Start == SegmentLoadCommandSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000301 }
302
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000303 void WriteSection(const MCSectionData &SD, uint64_t FileOffset,
304 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000305 // The offset is unused for virtual sections.
306 if (isVirtualSection(SD.getSection())) {
307 assert(SD.getFileSize() == 0 && "Invalid file size!");
308 FileOffset = 0;
309 }
310
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000311 // struct section (68 bytes) or
312 // struct section_64 (80 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000313
314 uint64_t Start = OS.tell();
315 (void) Start;
316
317 // FIXME: cast<> support!
318 const MCSectionMachO &Section =
319 static_cast<const MCSectionMachO&>(SD.getSection());
320 WriteString(Section.getSectionName(), 16);
321 WriteString(Section.getSegmentName(), 16);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000322 if (Is64Bit) {
323 Write64(SD.getAddress()); // address
324 Write64(SD.getSize()); // size
325 } else {
326 Write32(SD.getAddress()); // address
327 Write32(SD.getSize()); // size
328 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000329 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000330
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000331 unsigned Flags = Section.getTypeAndAttributes();
332 if (SD.hasInstructions())
333 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
334
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000335 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
336 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000337 Write32(NumRelocations ? RelocationsStart : 0);
338 Write32(NumRelocations);
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000339 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000340 Write32(0); // reserved1
341 Write32(Section.getStubSize()); // reserved2
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000342 if (Is64Bit)
343 Write32(0); // reserved3
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000344
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000345 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000346 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000347
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000348 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
349 uint32_t StringTableOffset,
350 uint32_t StringTableSize) {
351 // struct symtab_command (24 bytes)
352
353 uint64_t Start = OS.tell();
354 (void) Start;
355
356 Write32(LCT_Symtab);
357 Write32(SymtabLoadCommandSize);
358 Write32(SymbolOffset);
359 Write32(NumSymbols);
360 Write32(StringTableOffset);
361 Write32(StringTableSize);
362
363 assert(OS.tell() - Start == SymtabLoadCommandSize);
364 }
365
366 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
367 uint32_t NumLocalSymbols,
368 uint32_t FirstExternalSymbol,
369 uint32_t NumExternalSymbols,
370 uint32_t FirstUndefinedSymbol,
371 uint32_t NumUndefinedSymbols,
372 uint32_t IndirectSymbolOffset,
373 uint32_t NumIndirectSymbols) {
374 // struct dysymtab_command (80 bytes)
375
376 uint64_t Start = OS.tell();
377 (void) Start;
378
379 Write32(LCT_Dysymtab);
380 Write32(DysymtabLoadCommandSize);
381 Write32(FirstLocalSymbol);
382 Write32(NumLocalSymbols);
383 Write32(FirstExternalSymbol);
384 Write32(NumExternalSymbols);
385 Write32(FirstUndefinedSymbol);
386 Write32(NumUndefinedSymbols);
387 Write32(0); // tocoff
388 Write32(0); // ntoc
389 Write32(0); // modtaboff
390 Write32(0); // nmodtab
391 Write32(0); // extrefsymoff
392 Write32(0); // nextrefsyms
393 Write32(IndirectSymbolOffset);
394 Write32(NumIndirectSymbols);
395 Write32(0); // extreloff
396 Write32(0); // nextrel
397 Write32(0); // locreloff
398 Write32(0); // nlocrel
399
400 assert(OS.tell() - Start == DysymtabLoadCommandSize);
401 }
402
Daniel Dunbar5691e742010-03-13 22:49:35 +0000403 void WriteNlist(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000404 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000405 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000406 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000407 uint16_t Flags = Data.getFlags();
408 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000409
410 // Set the N_TYPE bits. See <mach-o/nlist.h>.
411 //
412 // FIXME: Are the prebound or indirect fields possible here?
413 if (Symbol.isUndefined())
414 Type = STT_Undefined;
415 else if (Symbol.isAbsolute())
416 Type = STT_Absolute;
417 else
418 Type = STT_Section;
419
420 // FIXME: Set STAB bits.
421
Daniel Dunbar5e835962009-08-26 02:48:04 +0000422 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000423 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000424
425 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000426 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000427 Type |= STF_External;
428
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000429 // Compute the symbol address.
430 if (Symbol.isDefined()) {
431 if (Symbol.isAbsolute()) {
432 llvm_unreachable("FIXME: Not yet implemented!");
433 } else {
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000434 Address = Data.getAddress();
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000435 }
436 } else if (Data.isCommon()) {
437 // Common symbols are encoded with the size in the address
438 // field, and their alignment in the flags.
439 Address = Data.getCommonSize();
440
441 // Common alignment is packed into the 'desc' bits.
442 if (unsigned Align = Data.getCommonAlignment()) {
443 unsigned Log2Size = Log2_32(Align);
444 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
445 if (Log2Size > 15)
446 llvm_report_error("invalid 'common' alignment '" +
447 Twine(Align) + "'");
448 // FIXME: Keep this mask with the SymbolFlags enumeration.
449 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
450 }
451 }
452
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000453 // struct nlist (12 bytes)
454
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000455 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000456 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000457 Write8(MSD.SectionIndex);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000458
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000459 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
460 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000461 Write16(Flags);
Daniel Dunbar5691e742010-03-13 22:49:35 +0000462 if (Is64Bit)
463 Write64(Address);
464 else
465 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000466 }
467
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000468 struct MachRelocationEntry {
469 uint32_t Word0;
470 uint32_t Word1;
471 };
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000472 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000473 MCAsmFixup &Fixup,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000474 const MCValue &Target,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000475 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000476 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000477 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000478 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000479 unsigned Type = RIT_Vanilla;
480
481 // See <reloc.h>.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000482 const MCSymbol *A = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000483 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000484
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000485 if (!A_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000486 llvm_report_error("symbol '" + A->getName() +
487 "' can not be undefined in a subtraction expression");
488
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000489 uint32_t Value = A_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000490 uint32_t Value2 = 0;
491
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000492 if (const MCSymbol *B = Target.getSymB()) {
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000493 MCSymbolData *B_SD = &Asm.getSymbolData(*B);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000494
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000495 if (!B_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000496 llvm_report_error("symbol '" + B->getName() +
497 "' can not be undefined in a subtraction expression");
498
Daniel Dunbar07a96412010-03-10 02:10:29 +0000499 // Select the appropriate difference relocation type.
500 //
501 // Note that there is no longer any semantic difference between these two
502 // relocation types from the linkers point of view, this is done solely
503 // for pedantic compatibility with 'as'.
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000504 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000505 Value2 = B_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000506 }
507
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000508 MachRelocationEntry MRE;
509 MRE.Word0 = ((Address << 0) |
510 (Type << 24) |
511 (Log2Size << 28) |
512 (IsPCRel << 30) |
513 RF_Scattered);
514 MRE.Word1 = Value;
515 Relocs.push_back(MRE);
516
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000517 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000518 MachRelocationEntry MRE;
519 MRE.Word0 = ((0 << 0) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000520 (RIT_Pair << 24) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000521 (Log2Size << 28) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000522 (IsPCRel << 30) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000523 RF_Scattered);
524 MRE.Word1 = Value2;
525 Relocs.push_back(MRE);
526 }
527 }
528
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000529 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000530 MCAsmFixup &Fixup,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000531 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000532 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
533 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
534
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000535 // FIXME: Share layout object.
536 MCAsmLayout Layout(Asm);
537
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000538 // Evaluate the fixup; if the value was resolved, no relocation is needed.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000539 MCValue Target;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000540 if (Asm.EvaluateFixup(Layout, Fixup, &Fragment, Target, Fixup.FixedValue))
541 return;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000542
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000543 // If this is a difference or a defined symbol plus an offset, then we need
544 // a scattered relocation entry.
545 uint32_t Offset = Target.getConstant();
546 if (IsPCRel)
547 Offset += 1 << Log2Size;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000548 if (Target.getSymB() ||
549 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000550 Offset))
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000551 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000552 Relocs);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000553
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000554 // See <reloc.h>.
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000555 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000556 uint32_t Value = 0;
557 unsigned Index = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000558 unsigned IsExtern = 0;
559 unsigned Type = 0;
560
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000561 if (Target.isAbsolute()) { // constant
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000562 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000563 //
Daniel Dunbar979ba5b2010-03-11 05:53:37 +0000564 // FIXME: Currently, these are never generated (see code below). I cannot
565 // find a case where they are actually emitted.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000566 Type = RIT_Vanilla;
567 Value = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000568 } else {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000569 const MCSymbol *Symbol = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000570 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000571
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000572 if (Symbol->isUndefined()) {
573 IsExtern = 1;
574 Index = SD->getIndex();
575 Value = 0;
576 } else {
577 // The index is the section ordinal.
578 //
579 // FIXME: O(N)
580 Index = 1;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000581 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
582 for (; it != ie; ++it, ++Index)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000583 if (&*it == SD->getFragment()->getParent())
584 break;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000585 assert(it != ie && "Unable to find section index!");
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000586 Value = SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000587 }
588
589 Type = RIT_Vanilla;
590 }
591
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000592 // struct relocation_info (8 bytes)
593 MachRelocationEntry MRE;
594 MRE.Word0 = Address;
595 MRE.Word1 = ((Index << 0) |
596 (IsPCRel << 24) |
597 (Log2Size << 25) |
598 (IsExtern << 27) |
599 (Type << 28));
600 Relocs.push_back(MRE);
601 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000602
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000603 void BindIndirectSymbols(MCAssembler &Asm) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000604 // This is the point where 'as' creates actual symbols for indirect symbols
605 // (in the following two passes). It would be easier for us to do this
606 // sooner when we see the attribute, but that makes getting the order in the
607 // symbol table much more complicated than it is worth.
608 //
609 // FIXME: Revisit this when the dust settles.
610
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000611 // Bind non lazy symbol pointers first.
612 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
613 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
614 // FIXME: cast<> support!
615 const MCSectionMachO &Section =
616 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
617
618 unsigned Type =
619 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
620 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
621 continue;
622
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000623 Asm.getOrCreateSymbolData(*it->Symbol);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000624 }
625
626 // Then lazy symbol pointers and symbol stubs.
627 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
628 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
629 // FIXME: cast<> support!
630 const MCSectionMachO &Section =
631 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
632
633 unsigned Type =
634 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
635 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
636 Type != MCSectionMachO::S_SYMBOL_STUBS)
637 continue;
638
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000639 // Set the symbol type to undefined lazy, but only on construction.
640 //
641 // FIXME: Do not hardcode.
642 bool Created;
643 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
644 if (Created)
645 Entry.setFlags(Entry.getFlags() | 0x0001);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000646 }
647 }
648
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000649 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000650 ///
651 /// \param StringTable [out] - The string table data.
652 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
653 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000654 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
655 std::vector<MachSymbolData> &LocalSymbolData,
656 std::vector<MachSymbolData> &ExternalSymbolData,
657 std::vector<MachSymbolData> &UndefinedSymbolData) {
658 // Build section lookup table.
659 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
660 unsigned Index = 1;
661 for (MCAssembler::iterator it = Asm.begin(),
662 ie = Asm.end(); it != ie; ++it, ++Index)
663 SectionIndexMap[&it->getSection()] = Index;
664 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000665
666 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000667 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000668 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000669
670 // Build the symbol arrays and the string table, but only for non-local
671 // symbols.
672 //
673 // The particular order that we collect the symbols and create the string
674 // table, then sort the symbols is chosen to match 'as'. Even though it
675 // doesn't matter for correctness, this is important for letting us diff .o
676 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000677 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
678 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000679 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000680
Daniel Dunbar959fd882009-08-26 22:13:22 +0000681 // Ignore assembler temporaries.
682 if (it->getSymbol().isTemporary())
683 continue;
684
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000685 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000686 continue;
687
688 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000689 if (!Entry) {
690 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000691 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000692 StringTable += '\x00';
693 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000694
695 MachSymbolData MSD;
696 MSD.SymbolData = it;
697 MSD.StringIndex = Entry;
698
699 if (Symbol.isUndefined()) {
700 MSD.SectionIndex = 0;
701 UndefinedSymbolData.push_back(MSD);
702 } else if (Symbol.isAbsolute()) {
703 MSD.SectionIndex = 0;
704 ExternalSymbolData.push_back(MSD);
705 } else {
706 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
707 assert(MSD.SectionIndex && "Invalid section index!");
708 ExternalSymbolData.push_back(MSD);
709 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000710 }
711
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000712 // Now add the data for local symbols.
713 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
714 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000715 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000716
Daniel Dunbar959fd882009-08-26 22:13:22 +0000717 // Ignore assembler temporaries.
718 if (it->getSymbol().isTemporary())
719 continue;
720
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000721 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000722 continue;
723
724 uint64_t &Entry = StringIndexMap[Symbol.getName()];
725 if (!Entry) {
726 Entry = StringTable.size();
727 StringTable += Symbol.getName();
728 StringTable += '\x00';
729 }
730
731 MachSymbolData MSD;
732 MSD.SymbolData = it;
733 MSD.StringIndex = Entry;
734
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000735 if (Symbol.isAbsolute()) {
736 MSD.SectionIndex = 0;
737 LocalSymbolData.push_back(MSD);
738 } else {
739 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
740 assert(MSD.SectionIndex && "Invalid section index!");
741 LocalSymbolData.push_back(MSD);
742 }
743 }
744
745 // External and undefined symbols are required to be in lexicographic order.
746 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
747 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
748
Daniel Dunbarbe963552009-08-26 13:57:54 +0000749 // Set the symbol indices.
750 Index = 0;
751 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
752 LocalSymbolData[i].SymbolData->setIndex(Index++);
753 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
754 ExternalSymbolData[i].SymbolData->setIndex(Index++);
755 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
756 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
757
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000758 // The string table is padded to a multiple of 4.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000759 while (StringTable.size() % 4)
760 StringTable += '\x00';
761 }
762
763 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000764 unsigned NumSections = Asm.size();
765
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000766 // Create symbol data for any indirect symbols.
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000767 BindIndirectSymbols(Asm);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000768
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000769 // Compute symbol table information.
770 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000771 std::vector<MachSymbolData> LocalSymbolData;
772 std::vector<MachSymbolData> ExternalSymbolData;
773 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000774 unsigned NumSymbols = Asm.symbol_size();
775
776 // No symbol table command is written if there are no symbols.
777 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000778 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
779 UndefinedSymbolData);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000780
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000781 // The section data starts after the header, the segment load command (and
782 // section headers) and the symbol table.
783 unsigned NumLoadCommands = 1;
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000784 uint64_t LoadCommandsSize = Is64Bit ?
785 SegmentLoadCommand64Size + NumSections * Section64Size :
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000786 SegmentLoadCommand32Size + NumSections * Section32Size;
787
788 // Add the symbol table load command sizes, if used.
789 if (NumSymbols) {
790 NumLoadCommands += 2;
791 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
792 }
793
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000794 // Compute the total size of the section data, as well as its file size and
795 // vm size.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000796 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
797 + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000798 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000799 uint64_t SectionDataFileSize = 0;
800 uint64_t VMSize = 0;
801 for (MCAssembler::iterator it = Asm.begin(),
802 ie = Asm.end(); it != ie; ++it) {
803 MCSectionData &SD = *it;
804
805 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
806
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000807 if (isVirtualSection(SD.getSection()))
808 continue;
809
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000810 SectionDataSize = std::max(SectionDataSize,
811 SD.getAddress() + SD.getSize());
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000812 SectionDataFileSize = std::max(SectionDataFileSize,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000813 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000814 }
815
Daniel Dunbar6b716532010-02-09 23:00:14 +0000816 // The section data is padded to 4 bytes.
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000817 //
818 // FIXME: Is this machine dependent?
819 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
820 SectionDataFileSize += SectionDataPadding;
821
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000822 // Write the prolog, starting with the header and load command...
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000823 WriteHeader(NumLoadCommands, LoadCommandsSize,
824 Asm.getSubsectionsViaSymbols());
825 WriteSegmentLoadCommand(NumSections, VMSize,
826 SectionDataStart, SectionDataSize);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000827
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000828 // ... and then the section headers.
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000829 //
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000830 // We also compute the section relocations while we do this. Note that
Daniel Dunbar6b716532010-02-09 23:00:14 +0000831 // computing relocation info will also update the fixup to have the correct
832 // value; this will overwrite the appropriate data in the fragment when it
833 // is written.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000834 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000835 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000836 for (MCAssembler::iterator it = Asm.begin(),
837 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000838 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000839
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000840 // The assembler writes relocations in the reverse order they were seen.
841 //
842 // FIXME: It is probably more complicated than this.
843 unsigned NumRelocsStart = RelocInfos.size();
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000844 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
845 ie2 = SD.rend(); it2 != ie2; ++it2)
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000846 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
847 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
848 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000849 RelocInfos);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000850
851 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
852 uint64_t SectionStart = SectionDataStart + SD.getAddress();
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000853 WriteSection(SD, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000854 RelocTableEnd += NumRelocs * RelocationInfoSize;
855 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000856
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000857 // Write the symbol table load command, if used.
858 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000859 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000860 unsigned NumLocalSymbols = LocalSymbolData.size();
861 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
862 unsigned NumExternalSymbols = ExternalSymbolData.size();
863 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
864 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000865 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
866 unsigned NumSymTabSymbols =
867 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
868 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
869 uint64_t IndirectSymbolOffset = 0;
870
871 // If used, the indirect symbols are written after the section data.
872 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000873 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000874
875 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000876 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000877
878 // The string table is written after symbol table.
879 uint64_t StringTableOffset =
Daniel Dunbar5691e742010-03-13 22:49:35 +0000880 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
881 Nlist32Size);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000882 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
883 StringTableOffset, StringTable.size());
884
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000885 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
886 FirstExternalSymbol, NumExternalSymbols,
887 FirstUndefinedSymbol, NumUndefinedSymbols,
888 IndirectSymbolOffset, NumIndirectSymbols);
889 }
890
891 // Write the actual section data.
892 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
893 WriteFileData(OS, *it, *this);
894
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000895 // Write the extra padding.
896 WriteZeros(SectionDataPadding);
897
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000898 // Write the relocation entries.
899 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
900 Write32(RelocInfos[i].Word0);
901 Write32(RelocInfos[i].Word1);
902 }
903
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000904 // Write the symbol table data, if used.
905 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000906 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000907 for (MCAssembler::indirect_symbol_iterator
908 it = Asm.indirect_symbol_begin(),
909 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
910 // Indirect symbols in the non lazy symbol pointer section have some
911 // special handling.
912 const MCSectionMachO &Section =
913 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
914 unsigned Type =
915 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
916 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
917 // If this symbol is defined and internal, mark it as such.
918 if (it->Symbol->isDefined() &&
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000919 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000920 uint32_t Flags = ISF_Local;
921 if (it->Symbol->isAbsolute())
922 Flags |= ISF_Absolute;
923 Write32(Flags);
924 continue;
925 }
926 }
927
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000928 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000929 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000930
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000931 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000932
933 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000934 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar5691e742010-03-13 22:49:35 +0000935 WriteNlist(LocalSymbolData[i]);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000936 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar5691e742010-03-13 22:49:35 +0000937 WriteNlist(ExternalSymbolData[i]);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000938 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar5691e742010-03-13 22:49:35 +0000939 WriteNlist(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000940
941 // Write the string table.
942 OS << StringTable.str();
943 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000944 }
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000945
946 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000947 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
948
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000949 // FIXME: Endianness assumption.
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000950 assert(Fixup.Offset + Size <= DF.getContents().size() &&
951 "Invalid fixup offset!");
952 for (unsigned i = 0; i != Size; ++i)
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000953 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
954 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000955};
956
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000957/* *** */
958
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000959MCFragment::MCFragment() : Kind(FragmentType(~0)) {
960}
961
Daniel Dunbar5e835962009-08-26 02:48:04 +0000962MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000963 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000964 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000965 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000966{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000967 if (Parent)
968 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000969}
970
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000971MCFragment::~MCFragment() {
972}
973
Daniel Dunbar5e835962009-08-26 02:48:04 +0000974uint64_t MCFragment::getAddress() const {
975 assert(getParent() && "Missing Section!");
976 return getParent()->getAddress() + Offset;
977}
978
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000979/* *** */
980
Daniel Dunbar81e40002009-08-27 00:38:04 +0000981MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000982
983MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000984 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000985 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000986 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000987 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000988 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000989 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000990{
991 if (A)
992 A->getSectionList().push_back(this);
993}
994
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000995/* *** */
996
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000997MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000998
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000999MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001000 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +00001001 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +00001002 IsExternal(false), IsPrivateExtern(false),
1003 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001004{
1005 if (A)
1006 A->getSymbolList().push_back(this);
1007}
1008
1009/* *** */
1010
Daniel Dunbar1f3e4452010-03-11 01:34:27 +00001011MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
1012 raw_ostream &_OS)
1013 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +00001014{
1015}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001016
1017MCAssembler::~MCAssembler() {
1018}
1019
Daniel Dunbardf3c8f22010-03-12 21:00:49 +00001020bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1021 MCDataFragment *DF,
1022 MCValue &Target, uint64_t &Value) const {
1023 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1024 llvm_report_error("expected relocatable expression");
1025
1026 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1027 // doesn't support small relocations, but then under what criteria does the
1028 // assembler allow symbol differences?
1029
1030 Value = Target.getConstant();
1031
1032 // FIXME: This "resolved" check isn't quite right. The assumption is that if
1033 // we have a PCrel access to a temporary, then that temporary is in the same
1034 // atom, and so the value is resolved. We need explicit atom's to implement
1035 // this more precisely.
1036 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1037 if (const MCSymbol *Symbol = Target.getSymA()) {
1038 if (Symbol->isDefined())
1039 Value += getSymbolData(*Symbol).getAddress();
1040 else
1041 IsResolved = false;
1042
1043 // With scattered symbols, we assume anything that isn't a PCrel temporary
1044 // access can have an arbitrary value.
1045 if (getBackend().hasScatteredSymbols() &&
1046 (!IsPCRel || !Symbol->isTemporary()))
1047 IsResolved = false;
1048 }
1049 if (const MCSymbol *Symbol = Target.getSymB()) {
1050 if (Symbol->isDefined())
1051 Value -= getSymbolData(*Symbol).getAddress();
1052 else
1053 IsResolved = false;
1054
1055 // With scattered symbols, we assume anything that isn't a PCrel temporary
1056 // access can have an arbitrary value.
1057 if (getBackend().hasScatteredSymbols() &&
1058 (!IsPCRel || !Symbol->isTemporary()))
1059 IsResolved = false;
1060 }
1061
1062 if (IsPCRel)
Daniel Dunbarda3e9f72010-03-13 02:38:00 +00001063 Value -= DF->getAddress() + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +00001064
1065 return IsResolved;
1066}
1067
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001068void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001069 MCAsmLayout Layout(*this);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001070 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001071
1072 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1073 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001074
Daniel Dunbar6742e342009-08-26 04:13:32 +00001075 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001076
1077 // Evaluate fragment size.
1078 switch (F.getKind()) {
1079 case MCFragment::FT_Align: {
1080 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001081
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001082 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +00001083 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001084 AF.setFileSize(0);
1085 else
Daniel Dunbar6742e342009-08-26 04:13:32 +00001086 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001087 break;
1088 }
1089
1090 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +00001091 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001092 F.setFileSize(F.getMaxFileSize());
1093 break;
1094
1095 case MCFragment::FT_Org: {
1096 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1097
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001098 int64_t TargetLocation;
1099 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1100 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001101
1102 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001103 int64_t Offset = TargetLocation - F.getOffset();
1104 if (Offset < 0)
1105 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1106 "' (at offset '" + Twine(F.getOffset()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001107
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001108 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001109 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001110 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001111
1112 case MCFragment::FT_ZeroFill: {
1113 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1114
1115 // Align the fragment offset; it is safe to adjust the offset freely since
1116 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +00001117 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1118 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001119
1120 // FIXME: This is misnamed.
1121 F.setFileSize(ZFF.getSize());
1122 break;
1123 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001124 }
1125
Daniel Dunbar6742e342009-08-26 04:13:32 +00001126 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001127 }
1128
Daniel Dunbar6742e342009-08-26 04:13:32 +00001129 // Set the section sizes.
1130 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001131 if (isVirtualSection(SD.getSection()))
1132 SD.setFileSize(0);
1133 else
1134 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001135}
1136
Kevin Enderby6e720482010-02-23 18:26:34 +00001137/// WriteNopData - Write optimal nops to the output file for the \arg Count
1138/// bytes. This returns the number of bytes written. It may return 0 if
1139/// the \arg Count is more than the maximum optimal nops.
1140///
1141/// FIXME this is X86 32-bit specific and should move to a better place.
1142static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
Kevin Enderby76687082010-02-23 21:41:24 +00001143 static const uint8_t Nops[16][16] = {
1144 // nop
1145 {0x90},
1146 // xchg %ax,%ax
1147 {0x66, 0x90},
1148 // nopl (%[re]ax)
1149 {0x0f, 0x1f, 0x00},
1150 // nopl 0(%[re]ax)
1151 {0x0f, 0x1f, 0x40, 0x00},
1152 // nopl 0(%[re]ax,%[re]ax,1)
1153 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1154 // nopw 0(%[re]ax,%[re]ax,1)
1155 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1156 // nopl 0L(%[re]ax)
1157 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1158 // nopl 0L(%[re]ax,%[re]ax,1)
1159 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1160 // nopw 0L(%[re]ax,%[re]ax,1)
1161 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1162 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1163 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1164 // nopl 0(%[re]ax,%[re]ax,1)
1165 // nopw 0(%[re]ax,%[re]ax,1)
1166 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1167 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1168 // nopw 0(%[re]ax,%[re]ax,1)
1169 // nopw 0(%[re]ax,%[re]ax,1)
1170 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1171 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1172 // nopw 0(%[re]ax,%[re]ax,1)
1173 // nopl 0L(%[re]ax) */
1174 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1175 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1176 // nopl 0L(%[re]ax)
1177 // nopl 0L(%[re]ax)
1178 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1179 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1180 // nopl 0L(%[re]ax)
1181 // nopl 0L(%[re]ax,%[re]ax,1)
1182 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1183 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1184 };
1185
1186 if (Count > 15)
1187 return 0;
1188
Kevin Enderby6e720482010-02-23 18:26:34 +00001189 for (uint64_t i = 0; i < Count; i++)
Kevin Enderby76687082010-02-23 21:41:24 +00001190 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +00001191
1192 return Count;
1193}
1194
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001195/// WriteFileData - Write the \arg F data to the output file.
1196static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1197 MachObjectWriter &MOW) {
1198 uint64_t Start = OS.tell();
1199 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001200
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001201 ++EmittedFragments;
1202
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001203 // FIXME: Embed in fragments instead?
1204 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001205 case MCFragment::FT_Align: {
1206 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1207 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1208
1209 // FIXME: This error shouldn't actually occur (the front end should emit
1210 // multiple .align directives to enforce the semantics it wants), but is
1211 // severe enough that we want to report it. How to handle this?
1212 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001213 llvm_report_error("undefined .align directive, value size '" +
1214 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001215 "' is not a divisor of padding size '" +
1216 Twine(AF.getFileSize()) + "'");
1217
Kevin Enderby6e720482010-02-23 18:26:34 +00001218 // See if we are aligning with nops, and if so do that first to try to fill
1219 // the Count bytes. Then if that did not fill any bytes or there are any
1220 // bytes left to fill use the the Value and ValueSize to fill the rest.
1221 if (AF.getEmitNops()) {
1222 uint64_t NopByteCount = WriteNopData(Count, MOW);
1223 Count -= NopByteCount;
1224 }
1225
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001226 for (uint64_t i = 0; i != Count; ++i) {
1227 switch (AF.getValueSize()) {
1228 default:
1229 assert(0 && "Invalid size!");
1230 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1231 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1232 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1233 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1234 }
1235 }
1236 break;
1237 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001238
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001239 case MCFragment::FT_Data: {
1240 MCDataFragment &DF = cast<MCDataFragment>(F);
1241
1242 // Apply the fixups.
1243 //
1244 // FIXME: Move elsewhere.
1245 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1246 ie = DF.fixup_end(); it != ie; ++it)
1247 MOW.ApplyFixup(*it, DF);
1248
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001249 OS << cast<MCDataFragment>(F).getContents().str();
1250 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001251 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001252
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001253 case MCFragment::FT_Fill: {
1254 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001255 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1256 switch (FF.getValueSize()) {
1257 default:
1258 assert(0 && "Invalid size!");
Daniel Dunbara4766d72010-02-13 09:28:32 +00001259 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1260 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1261 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1262 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001263 }
1264 }
1265 break;
1266 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001267
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001268 case MCFragment::FT_Org: {
1269 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1270
1271 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1272 MOW.Write8(uint8_t(OF.getValue()));
1273
1274 break;
1275 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001276
1277 case MCFragment::FT_ZeroFill: {
1278 assert(0 && "Invalid zero fill fragment in concrete section!");
1279 break;
1280 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001281 }
1282
1283 assert(OS.tell() - Start == F.getFileSize());
1284}
1285
1286/// WriteFileData - Write the \arg SD data to the output file.
1287static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1288 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001289 // Ignore virtual sections.
1290 if (isVirtualSection(SD.getSection())) {
1291 assert(SD.getFileSize() == 0);
1292 return;
1293 }
1294
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001295 uint64_t Start = OS.tell();
1296 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001297
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001298 for (MCSectionData::const_iterator it = SD.begin(),
1299 ie = SD.end(); it != ie; ++it)
1300 WriteFileData(OS, *it, MOW);
1301
Daniel Dunbar6742e342009-08-26 04:13:32 +00001302 // Add section padding.
1303 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1304 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1305
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001306 assert(OS.tell() - Start == SD.getFileSize());
1307}
1308
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001309void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001310 DEBUG_WITH_TYPE("mc-dump", {
1311 llvm::errs() << "assembler backend - pre-layout\n--\n";
1312 dump(); });
1313
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001314 // Layout until everything fits.
1315 while (LayoutOnce())
1316 continue;
1317
1318 DEBUG_WITH_TYPE("mc-dump", {
1319 llvm::errs() << "assembler backend - post-layout\n--\n";
1320 dump(); });
1321
1322 // Write the object file.
Daniel Dunbaree0d8922010-03-13 22:10:17 +00001323 //
1324 // FIXME: Factor out MCObjectWriter.
1325 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1326 MachObjectWriter MOW(OS, Is64Bit);
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001327 MOW.WriteObject(*this);
1328
1329 OS.flush();
1330}
1331
1332bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1333 // FIXME: Share layout object.
1334 MCAsmLayout Layout(*this);
1335
1336 // Currently we only need to relax X86::reloc_pcrel_1byte.
1337 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1338 return false;
1339
1340 // If we cannot resolve the fixup value, it requires relaxation.
1341 MCValue Target;
1342 uint64_t Value;
1343 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1344 return true;
1345
1346 // Otherwise, relax if the value is too big for a (signed) i8.
1347 return int64_t(Value) != int64_t(int8_t(Value));
1348}
1349
1350bool MCAssembler::LayoutOnce() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001351 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001352 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001353 MCSectionData *Prev = 0;
1354 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001355 MCSectionData &SD = *it;
1356
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001357 // Skip virtual sections.
1358 if (isVirtualSection(SD.getSection()))
1359 continue;
1360
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001361 // Align this section if necessary by adding padding bytes to the previous
1362 // section.
1363 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1364 assert(Prev && "Missing prev section!");
1365 Prev->setFileSize(Prev->getFileSize() + Pad);
1366 Address += Pad;
1367 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001368
1369 // Layout the section fragments and its size.
1370 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001371 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001372 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001373
1374 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001375 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001376
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001377 // Layout the virtual sections.
1378 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1379 MCSectionData &SD = *it;
1380
1381 if (!isVirtualSection(SD.getSection()))
1382 continue;
1383
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001384 // Align this section if necessary by adding padding bytes to the previous
1385 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +00001386 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001387 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001388
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001389 SD.setAddress(Address);
1390 LayoutSection(SD);
1391 Address += SD.getSize();
1392 }
1393
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001394 // Scan the fixups in order and relax any that don't fit.
1395 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1396 MCSectionData &SD = *it;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001397
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001398 for (MCSectionData::iterator it2 = SD.begin(),
1399 ie2 = SD.end(); it2 != ie2; ++it2) {
1400 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1401 if (!DF)
1402 continue;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001403
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001404 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1405 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1406 MCAsmFixup &Fixup = *it3;
1407
1408 // Check whether we need to relax this fixup.
1409 if (!FixupNeedsRelaxation(Fixup, DF))
1410 continue;
1411
1412 // Relax the instruction.
1413 //
1414 // FIXME: This is a huge temporary hack which just looks for x86
1415 // branches; the only thing we need to relax on x86 is
1416 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1417 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1418 // an individual MCInst.
1419 SmallVectorImpl<char> &C = DF->getContents();
1420 uint64_t PrevOffset = Fixup.Offset;
1421 unsigned Amt = 0;
1422
1423 // jcc instructions
1424 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1425 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1426 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1427 C[Fixup.Offset-1] = char(0x0f);
1428 ++Fixup.Offset;
1429 Amt = 4;
1430
1431 // jmp rel8
1432 } else if (C[Fixup.Offset-1] == char(0xeb)) {
1433 C[Fixup.Offset-1] = char(0xe9);
1434 Amt = 3;
1435
1436 } else
1437 llvm_unreachable("unknown 1 byte pcrel instruction!");
1438
1439 Fixup.Value = MCBinaryExpr::Create(
1440 MCBinaryExpr::Sub, Fixup.Value,
1441 MCConstantExpr::Create(3, getContext()),
1442 getContext());
1443 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1444 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1445
1446 // Update the remaining fixups, which have slid.
1447 //
1448 // FIXME: This is bad for performance, but will be eliminated by the
1449 // move to MCInst specific fragments.
1450 ++it3;
1451 for (; it3 != ie3; ++it3)
1452 it3->Offset += Amt;
1453
1454 // Update all the symbols for this fragment, which may have slid.
1455 //
1456 // FIXME: This is really really bad for performance, but will be
1457 // eliminated by the move to MCInst specific fragments.
1458 for (MCAssembler::symbol_iterator it = symbol_begin(),
1459 ie = symbol_end(); it != ie; ++it) {
1460 MCSymbolData &SD = *it;
1461
1462 if (it->getFragment() != DF)
1463 continue;
1464
1465 if (SD.getOffset() > PrevOffset)
1466 SD.setOffset(SD.getOffset() + Amt);
1467 }
1468
1469 // Restart layout.
1470 //
1471 // FIXME: This is O(N^2), but will be eliminated once we have a smart
1472 // MCAsmLayout object.
1473 return true;
1474 }
1475 }
1476 }
1477
1478 return false;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001479}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001480
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001481// Debugging methods
1482
1483namespace llvm {
1484
1485raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001486 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1487 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001488 return OS;
1489}
1490
1491}
1492
1493void MCFragment::dump() {
1494 raw_ostream &OS = llvm::errs();
1495
1496 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1497 << " FileSize:" << FileSize;
1498
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001499 OS << ">";
1500}
1501
1502void MCAlignFragment::dump() {
1503 raw_ostream &OS = llvm::errs();
1504
1505 OS << "<MCAlignFragment ";
1506 this->MCFragment::dump();
1507 OS << "\n ";
1508 OS << " Alignment:" << getAlignment()
1509 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1510 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1511}
1512
1513void MCDataFragment::dump() {
1514 raw_ostream &OS = llvm::errs();
1515
1516 OS << "<MCDataFragment ";
1517 this->MCFragment::dump();
1518 OS << "\n ";
1519 OS << " Contents:[";
1520 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1521 if (i) OS << ",";
1522 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1523 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001524 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001525
1526 if (!getFixups().empty()) {
1527 OS << ",\n ";
1528 OS << " Fixups:[";
1529 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001530 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001531 OS << *it;
1532 }
1533 OS << "]";
1534 }
1535
1536 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001537}
1538
1539void MCFillFragment::dump() {
1540 raw_ostream &OS = llvm::errs();
1541
1542 OS << "<MCFillFragment ";
1543 this->MCFragment::dump();
1544 OS << "\n ";
1545 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1546 << " Count:" << getCount() << ">";
1547}
1548
1549void MCOrgFragment::dump() {
1550 raw_ostream &OS = llvm::errs();
1551
1552 OS << "<MCOrgFragment ";
1553 this->MCFragment::dump();
1554 OS << "\n ";
1555 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1556}
1557
1558void MCZeroFillFragment::dump() {
1559 raw_ostream &OS = llvm::errs();
1560
1561 OS << "<MCZeroFillFragment ";
1562 this->MCFragment::dump();
1563 OS << "\n ";
1564 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1565}
1566
1567void MCSectionData::dump() {
1568 raw_ostream &OS = llvm::errs();
1569
1570 OS << "<MCSectionData";
1571 OS << " Alignment:" << getAlignment() << " Address:" << Address
1572 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001573 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001574 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1575 if (it != begin()) OS << ",\n ";
1576 it->dump();
1577 }
1578 OS << "]>";
1579}
1580
1581void MCSymbolData::dump() {
1582 raw_ostream &OS = llvm::errs();
1583
1584 OS << "<MCSymbolData Symbol:" << getSymbol()
1585 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1586 << " Flags:" << getFlags() << " Index:" << getIndex();
1587 if (isCommon())
1588 OS << " (common, size:" << getCommonSize()
1589 << " align: " << getCommonAlignment() << ")";
1590 if (isExternal())
1591 OS << " (external)";
1592 if (isPrivateExtern())
1593 OS << " (private extern)";
1594 OS << ">";
1595}
1596
1597void MCAssembler::dump() {
1598 raw_ostream &OS = llvm::errs();
1599
1600 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001601 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001602 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1603 if (it != begin()) OS << ",\n ";
1604 it->dump();
1605 }
1606 OS << "],\n";
1607 OS << " Symbols:[";
1608
1609 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001610 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001611 it->dump();
1612 }
1613 OS << "]>\n";
1614}