blob: 0e4d3cc1efcd78f9f9cacf871cd99502070a2e17 [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 Dunbarb36052f2010-03-19 10:43:23 +000013#include "llvm/MC/MCCodeEmitter.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000014#include "llvm/MC/MCExpr.h"
Daniel Dunbar53b23382010-03-19 09:28:59 +000015#include "llvm/MC/MCObjectWriter.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000016#include "llvm/MC/MCSymbol.h"
17#include "llvm/MC/MCValue.h"
Daniel Dunbar1a9158c2010-03-19 10:43:26 +000018#include "llvm/ADT/OwningPtr.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 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"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000023#include "llvm/Support/raw_ostream.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000024#include "llvm/Support/Debug.h"
Daniel Dunbaree0d8922010-03-13 22:10:17 +000025#include "llvm/Target/TargetRegistry.h"
Daniel Dunbardf3c8f22010-03-12 21:00:49 +000026#include "llvm/Target/TargetAsmBackend.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000027
28// FIXME: Gross.
29#include "../Target/X86/X86FixupKinds.h"
30
Chris Lattner23132b12009-08-24 03:52:50 +000031#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000032using namespace llvm;
33
Daniel Dunbar0adcd352009-08-25 21:10:45 +000034STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
35
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000036// FIXME FIXME FIXME: There are number of places in this file where we convert
37// what is a 64-bit assembler value used for computation into a value in the
38// object file, which may truncate it. We should detect that truncation where
39// invalid and report errors back.
40
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000041/* *** */
42
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000043MCFragment::MCFragment() : Kind(FragmentType(~0)) {
44}
45
Daniel Dunbar5e835962009-08-26 02:48:04 +000046MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000047 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +000048 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000049 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000050{
Daniel Dunbar5e835962009-08-26 02:48:04 +000051 if (Parent)
52 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000053}
54
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000055MCFragment::~MCFragment() {
56}
57
Daniel Dunbar5e835962009-08-26 02:48:04 +000058uint64_t MCFragment::getAddress() const {
59 assert(getParent() && "Missing Section!");
60 return getParent()->getAddress() + Offset;
61}
62
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000063/* *** */
64
Daniel Dunbar81e40002009-08-27 00:38:04 +000065MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000066
67MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +000068 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000069 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +000070 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +000071 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000072 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +000073 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000074{
75 if (A)
76 A->getSectionList().push_back(this);
77}
78
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000079/* *** */
80
Daniel Dunbarefbb5332009-09-01 04:09:03 +000081MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000082
Daniel Dunbarcb579b32009-08-31 08:08:06 +000083MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000084 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +000085 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000086 IsExternal(false), IsPrivateExtern(false),
87 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000088{
89 if (A)
90 A->getSymbolList().push_back(this);
91}
92
93/* *** */
94
Daniel Dunbar1f3e4452010-03-11 01:34:27 +000095MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
Daniel Dunbarcf871e52010-03-19 10:43:18 +000096 MCCodeEmitter &_Emitter, raw_ostream &_OS)
97 : Context(_Context), Backend(_Backend), Emitter(_Emitter),
98 OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +000099{
100}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000101
102MCAssembler::~MCAssembler() {
103}
104
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000105static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
106 const MCAsmFixup &Fixup,
107 const MCDataFragment *DF,
108 const MCValue Target,
109 const MCSection *BaseSection) {
110 // The effective fixup address is
111 // addr(atom(A)) + offset(A)
112 // - addr(atom(B)) - offset(B)
113 // - addr(<base symbol>) + <fixup offset from base symbol>
114 // and the offsets are not relocatable, so the fixup is fully resolved when
115 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
116 //
117 // The simple (Darwin, except on x86_64) way of dealing with this was to
118 // assume that any reference to a temporary symbol *must* be a temporary
119 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
120 // relocation to a temporary symbol (in the same section) is fully
121 // resolved. This also works in conjunction with absolutized .set, which
122 // requires the compiler to use .set to absolutize the differences between
123 // symbols which the compiler knows to be assembly time constants, so we don't
124 // need to worry about consider symbol differences fully resolved.
125
126 // Non-relative fixups are only resolved if constant.
127 if (!BaseSection)
128 return Target.isAbsolute();
129
130 // Otherwise, relative fixups are only resolved if not a difference and the
131 // target is a temporary in the same section.
132 if (Target.isAbsolute() || Target.getSymB())
133 return false;
134
135 const MCSymbol *A = &Target.getSymA()->getSymbol();
136 if (!A->isTemporary() || !A->isInSection() ||
137 &A->getSection() != BaseSection)
138 return false;
139
140 return true;
141}
142
Daniel Dunbar034843a2010-03-19 03:18:18 +0000143static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
144 const MCAsmFixup &Fixup,
145 const MCDataFragment *DF,
146 const MCValue Target,
147 const MCSymbolData *BaseSymbol) {
148 // The effective fixup address is
149 // addr(atom(A)) + offset(A)
150 // - addr(atom(B)) - offset(B)
151 // - addr(BaseSymbol) + <fixup offset from base symbol>
152 // and the offsets are not relocatable, so the fixup is fully resolved when
153 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
154 //
155 // Note that "false" is almost always conservatively correct (it means we emit
156 // a relocation which is unnecessary), except when it would force us to emit a
157 // relocation which the target cannot encode.
158
159 const MCSymbolData *A_Base = 0, *B_Base = 0;
160 if (const MCSymbolRefExpr *A = Target.getSymA()) {
161 // Modified symbol references cannot be resolved.
162 if (A->getKind() != MCSymbolRefExpr::VK_None)
163 return false;
164
165 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
166 if (!A_Base)
167 return false;
168 }
169
170 if (const MCSymbolRefExpr *B = Target.getSymB()) {
171 // Modified symbol references cannot be resolved.
172 if (B->getKind() != MCSymbolRefExpr::VK_None)
173 return false;
174
175 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
176 if (!B_Base)
177 return false;
178 }
179
180 // If there is no base, A and B have to be the same atom for this fixup to be
181 // fully resolved.
182 if (!BaseSymbol)
183 return A_Base == B_Base;
184
185 // Otherwise, B must be missing and A must be the base.
186 return !B_Base && BaseSymbol == A_Base;
187}
188
Daniel Dunbar23869852010-03-19 03:18:09 +0000189bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
190 // Non-temporary labels should always be visible to the linker.
191 if (!SD->getSymbol().isTemporary())
192 return true;
193
194 // Absolute temporary labels are never visible.
195 if (!SD->getFragment())
196 return false;
197
198 // Otherwise, check if the section requires symbols even for temporary labels.
199 return getBackend().doesSectionRequireSymbols(
200 SD->getFragment()->getParent()->getSection());
201}
202
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000203const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
204 uint64_t Address) const {
205 const MCSymbolData *Best = 0;
206 for (MCAssembler::const_symbol_iterator it = symbol_begin(),
207 ie = symbol_end(); it != ie; ++it) {
208 // Ignore non-linker visible symbols.
209 if (!isSymbolLinkerVisible(it))
210 continue;
211
212 // Ignore symbols not in the same section.
213 if (!it->getFragment() || it->getFragment()->getParent() != Section)
214 continue;
215
216 // Otherwise, find the closest symbol preceding this address (ties are
217 // resolved in favor of the last defined symbol).
218 if (it->getAddress() <= Address &&
219 (!Best || it->getAddress() >= Best->getAddress()))
220 Best = it;
221 }
222
223 return Best;
224}
225
226const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
227 // Linker visible symbols define atoms.
228 if (isSymbolLinkerVisible(SD))
229 return SD;
230
231 // Absolute and undefined symbols have no defining atom.
232 if (!SD->getFragment())
233 return 0;
234
235 // Otherwise, search by address.
236 return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
237}
238
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000239bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
240 MCDataFragment *DF,
241 MCValue &Target, uint64_t &Value) const {
242 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
243 llvm_report_error("expected relocatable expression");
244
245 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
246 // doesn't support small relocations, but then under what criteria does the
247 // assembler allow symbol differences?
248
249 Value = Target.getConstant();
250
Daniel Dunbarb36052f2010-03-19 10:43:23 +0000251 bool IsPCRel =
252 Emitter.getFixupKindInfo(Fixup.Kind).Flags & MCFixupKindInfo::FKF_IsPCRel;
253 bool IsResolved = true;
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000254 if (const MCSymbolRefExpr *A = Target.getSymA()) {
255 if (A->getSymbol().isDefined())
256 Value += getSymbolData(A->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000257 else
258 IsResolved = false;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000259 }
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000260 if (const MCSymbolRefExpr *B = Target.getSymB()) {
261 if (B->getSymbol().isDefined())
262 Value -= getSymbolData(B->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000263 else
264 IsResolved = false;
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000265 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000266
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000267 // If we are using scattered symbols, determine whether this value is actually
268 // resolved; scattering may cause atoms to move.
269 if (IsResolved && getBackend().hasScatteredSymbols()) {
270 if (getBackend().hasReliableSymbolDifference()) {
Daniel Dunbar034843a2010-03-19 03:18:18 +0000271 // If this is a PCrel relocation, find the base atom (identified by its
272 // symbol) that the fixup value is relative to.
273 const MCSymbolData *BaseSymbol = 0;
274 if (IsPCRel) {
275 BaseSymbol = getAtomForAddress(
276 DF->getParent(), DF->getAddress() + Fixup.Offset);
277 if (!BaseSymbol)
278 IsResolved = false;
279 }
280
281 if (IsResolved)
282 IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
283 BaseSymbol);
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000284 } else {
285 const MCSection *BaseSection = 0;
286 if (IsPCRel)
287 BaseSection = &DF->getParent()->getSection();
288
289 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
290 BaseSection);
291 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000292 }
293
294 if (IsPCRel)
Daniel Dunbarda3e9f72010-03-13 02:38:00 +0000295 Value -= DF->getAddress() + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000296
297 return IsResolved;
298}
299
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000300void MCAssembler::LayoutSection(MCSectionData &SD,
301 MCAsmLayout &Layout) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000302 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000303
304 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
305 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000306
Daniel Dunbar6742e342009-08-26 04:13:32 +0000307 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000308
309 // Evaluate fragment size.
310 switch (F.getKind()) {
311 case MCFragment::FT_Align: {
312 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000313
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000314 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000315 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000316 AF.setFileSize(0);
317 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000318 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000319 break;
320 }
321
322 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +0000323 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000324 F.setFileSize(F.getMaxFileSize());
325 break;
326
327 case MCFragment::FT_Org: {
328 MCOrgFragment &OF = cast<MCOrgFragment>(F);
329
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000330 int64_t TargetLocation;
331 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
332 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000333
334 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000335 int64_t Offset = TargetLocation - F.getOffset();
336 if (Offset < 0)
337 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
338 "' (at offset '" + Twine(F.getOffset()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000339
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000340 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000341 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000342 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000343
344 case MCFragment::FT_ZeroFill: {
345 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
346
347 // Align the fragment offset; it is safe to adjust the offset freely since
348 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +0000349 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
350 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000351
352 // FIXME: This is misnamed.
353 F.setFileSize(ZFF.getSize());
354 break;
355 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000356 }
357
Daniel Dunbar6742e342009-08-26 04:13:32 +0000358 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000359 }
360
Daniel Dunbar6742e342009-08-26 04:13:32 +0000361 // Set the section sizes.
362 SD.setSize(Address - SD.getAddress());
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000363 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000364 SD.setFileSize(0);
365 else
366 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000367}
368
Kevin Enderby6e720482010-02-23 18:26:34 +0000369/// WriteNopData - Write optimal nops to the output file for the \arg Count
370/// bytes. This returns the number of bytes written. It may return 0 if
371/// the \arg Count is more than the maximum optimal nops.
372///
373/// FIXME this is X86 32-bit specific and should move to a better place.
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000374static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
Kevin Enderby76687082010-02-23 21:41:24 +0000375 static const uint8_t Nops[16][16] = {
376 // nop
377 {0x90},
378 // xchg %ax,%ax
379 {0x66, 0x90},
380 // nopl (%[re]ax)
381 {0x0f, 0x1f, 0x00},
382 // nopl 0(%[re]ax)
383 {0x0f, 0x1f, 0x40, 0x00},
384 // nopl 0(%[re]ax,%[re]ax,1)
385 {0x0f, 0x1f, 0x44, 0x00, 0x00},
386 // nopw 0(%[re]ax,%[re]ax,1)
387 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
388 // nopl 0L(%[re]ax)
389 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
390 // nopl 0L(%[re]ax,%[re]ax,1)
391 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
392 // nopw 0L(%[re]ax,%[re]ax,1)
393 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
394 // nopw %cs:0L(%[re]ax,%[re]ax,1)
395 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
396 // nopl 0(%[re]ax,%[re]ax,1)
397 // nopw 0(%[re]ax,%[re]ax,1)
398 {0x0f, 0x1f, 0x44, 0x00, 0x00,
399 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
400 // nopw 0(%[re]ax,%[re]ax,1)
401 // nopw 0(%[re]ax,%[re]ax,1)
402 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
403 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
404 // nopw 0(%[re]ax,%[re]ax,1)
405 // nopl 0L(%[re]ax) */
406 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
407 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
408 // nopl 0L(%[re]ax)
409 // nopl 0L(%[re]ax)
410 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
411 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
412 // nopl 0L(%[re]ax)
413 // nopl 0L(%[re]ax,%[re]ax,1)
414 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
415 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
416 };
417
418 if (Count > 15)
419 return 0;
420
Kevin Enderby6e720482010-02-23 18:26:34 +0000421 for (uint64_t i = 0; i < Count; i++)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000422 OW->Write8(uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +0000423
424 return Count;
425}
426
Daniel Dunbar53b23382010-03-19 09:28:59 +0000427/// WriteFragmentData - Write the \arg F data to the output file.
428static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
429 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000430 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000431
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000432 ++EmittedFragments;
433
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000434 // FIXME: Embed in fragments instead?
435 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000436 case MCFragment::FT_Align: {
437 MCAlignFragment &AF = cast<MCAlignFragment>(F);
438 uint64_t Count = AF.getFileSize() / AF.getValueSize();
439
440 // FIXME: This error shouldn't actually occur (the front end should emit
441 // multiple .align directives to enforce the semantics it wants), but is
442 // severe enough that we want to report it. How to handle this?
443 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000444 llvm_report_error("undefined .align directive, value size '" +
445 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000446 "' is not a divisor of padding size '" +
447 Twine(AF.getFileSize()) + "'");
448
Kevin Enderby6e720482010-02-23 18:26:34 +0000449 // See if we are aligning with nops, and if so do that first to try to fill
450 // the Count bytes. Then if that did not fill any bytes or there are any
451 // bytes left to fill use the the Value and ValueSize to fill the rest.
452 if (AF.getEmitNops()) {
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000453 uint64_t NopByteCount = WriteNopData(Count, OW);
Kevin Enderby6e720482010-02-23 18:26:34 +0000454 Count -= NopByteCount;
455 }
456
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000457 for (uint64_t i = 0; i != Count; ++i) {
458 switch (AF.getValueSize()) {
459 default:
460 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000461 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
462 case 2: OW->Write16(uint16_t(AF.getValue())); break;
463 case 4: OW->Write32(uint32_t(AF.getValue())); break;
464 case 8: OW->Write64(uint64_t(AF.getValue())); break;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000465 }
466 }
467 break;
468 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000469
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000470 case MCFragment::FT_Data: {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000471 OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000472 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000473 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000474
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000475 case MCFragment::FT_Fill: {
476 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000477 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
478 switch (FF.getValueSize()) {
479 default:
480 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000481 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
482 case 2: OW->Write16(uint16_t(FF.getValue())); break;
483 case 4: OW->Write32(uint32_t(FF.getValue())); break;
484 case 8: OW->Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000485 }
486 }
487 break;
488 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000489
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000490 case MCFragment::FT_Org: {
491 MCOrgFragment &OF = cast<MCOrgFragment>(F);
492
493 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000494 OW->Write8(uint8_t(OF.getValue()));
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000495
496 break;
497 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000498
499 case MCFragment::FT_ZeroFill: {
500 assert(0 && "Invalid zero fill fragment in concrete section!");
501 break;
502 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000503 }
504
Daniel Dunbar53b23382010-03-19 09:28:59 +0000505 assert(OW->getStream().tell() - Start == F.getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000506}
507
Daniel Dunbar53b23382010-03-19 09:28:59 +0000508void MCAssembler::WriteSectionData(const MCSectionData *SD,
509 MCObjectWriter *OW) const {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000510 // Ignore virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000511 if (getBackend().isVirtualSection(SD->getSection())) {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000512 assert(SD->getFileSize() == 0);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000513 return;
514 }
515
Daniel Dunbar53b23382010-03-19 09:28:59 +0000516 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000517 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000518
Daniel Dunbar53b23382010-03-19 09:28:59 +0000519 for (MCSectionData::const_iterator it = SD->begin(),
520 ie = SD->end(); it != ie; ++it)
521 WriteFragmentData(*it, OW);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000522
Daniel Dunbar6742e342009-08-26 04:13:32 +0000523 // Add section padding.
Daniel Dunbar53b23382010-03-19 09:28:59 +0000524 assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
525 OW->WriteZeros(SD->getFileSize() - SD->getSize());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000526
Daniel Dunbar53b23382010-03-19 09:28:59 +0000527 assert(OW->getStream().tell() - Start == SD->getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000528}
529
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000530void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000531 DEBUG_WITH_TYPE("mc-dump", {
532 llvm::errs() << "assembler backend - pre-layout\n--\n";
533 dump(); });
534
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000535 // Layout until everything fits.
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000536 MCAsmLayout Layout(*this);
537 while (LayoutOnce(Layout))
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000538 continue;
539
540 DEBUG_WITH_TYPE("mc-dump", {
541 llvm::errs() << "assembler backend - post-layout\n--\n";
542 dump(); });
543
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000544 llvm::OwningPtr<MCObjectWriter> Writer(getBackend().createObjectWriter(OS));
545 if (!Writer)
546 llvm_report_error("unable to create object writer!");
Daniel Dunbarbacba992010-03-19 07:09:33 +0000547
548 // Allow the object writer a chance to perform post-layout binding (for
549 // example, to set the index fields in the symbol data).
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000550 Writer->ExecutePostLayoutBinding(*this);
Daniel Dunbarbacba992010-03-19 07:09:33 +0000551
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000552 // Evaluate and apply the fixups, generating relocation entries as necessary.
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000553 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
554 for (MCSectionData::iterator it2 = it->begin(),
555 ie2 = it->end(); it2 != ie2; ++it2) {
556 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
557 if (!DF)
558 continue;
559
560 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
561 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
562 MCAsmFixup &Fixup = *it3;
563
564 // Evaluate the fixup.
565 MCValue Target;
566 uint64_t FixedValue;
567 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
568 // The fixup was unresolved, we need a relocation. Inform the object
569 // writer of the relocation, and give it an opportunity to adjust the
570 // fixup value if need be.
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000571 Writer->RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000572 }
573
Daniel Dunbar87190c42010-03-19 09:28:12 +0000574 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000575 }
576 }
577 }
578
Daniel Dunbarbacba992010-03-19 07:09:33 +0000579 // Write the object file.
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000580 Writer->WriteObject(*this);
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000581 OS.flush();
582}
583
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000584bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF,
585 const MCAsmLayout &Layout) const {
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000586 // Currently we only need to relax X86::reloc_pcrel_1byte.
587 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
588 return false;
589
590 // If we cannot resolve the fixup value, it requires relaxation.
591 MCValue Target;
592 uint64_t Value;
593 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
594 return true;
595
596 // Otherwise, relax if the value is too big for a (signed) i8.
597 return int64_t(Value) != int64_t(int8_t(Value));
598}
599
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000600bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000601 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000602 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000603 MCSectionData *Prev = 0;
604 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000605 MCSectionData &SD = *it;
606
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000607 // Skip virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000608 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000609 continue;
610
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000611 // Align this section if necessary by adding padding bytes to the previous
612 // section.
613 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
614 assert(Prev && "Missing prev section!");
615 Prev->setFileSize(Prev->getFileSize() + Pad);
616 Address += Pad;
617 }
Daniel Dunbar6742e342009-08-26 04:13:32 +0000618
619 // Layout the section fragments and its size.
620 SD.setAddress(Address);
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000621 LayoutSection(SD, Layout);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000622 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000623
624 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +0000625 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000626
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000627 // Layout the virtual sections.
628 for (iterator it = begin(), ie = end(); it != ie; ++it) {
629 MCSectionData &SD = *it;
630
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000631 if (!getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000632 continue;
633
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000634 // Align this section if necessary by adding padding bytes to the previous
635 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +0000636 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000637 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000638
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000639 SD.setAddress(Address);
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000640 LayoutSection(SD, Layout);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000641 Address += SD.getSize();
642 }
643
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000644 // Scan the fixups in order and relax any that don't fit.
645 for (iterator it = begin(), ie = end(); it != ie; ++it) {
646 MCSectionData &SD = *it;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000647
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000648 for (MCSectionData::iterator it2 = SD.begin(),
649 ie2 = SD.end(); it2 != ie2; ++it2) {
650 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
651 if (!DF)
652 continue;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000653
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000654 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
655 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
656 MCAsmFixup &Fixup = *it3;
657
658 // Check whether we need to relax this fixup.
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000659 if (!FixupNeedsRelaxation(Fixup, DF, Layout))
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000660 continue;
661
662 // Relax the instruction.
663 //
664 // FIXME: This is a huge temporary hack which just looks for x86
665 // branches; the only thing we need to relax on x86 is
666 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
667 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
668 // an individual MCInst.
669 SmallVectorImpl<char> &C = DF->getContents();
670 uint64_t PrevOffset = Fixup.Offset;
671 unsigned Amt = 0;
672
673 // jcc instructions
674 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
675 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
676 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
677 C[Fixup.Offset-1] = char(0x0f);
678 ++Fixup.Offset;
679 Amt = 4;
680
681 // jmp rel8
682 } else if (C[Fixup.Offset-1] == char(0xeb)) {
683 C[Fixup.Offset-1] = char(0xe9);
684 Amt = 3;
685
686 } else
687 llvm_unreachable("unknown 1 byte pcrel instruction!");
688
689 Fixup.Value = MCBinaryExpr::Create(
690 MCBinaryExpr::Sub, Fixup.Value,
691 MCConstantExpr::Create(3, getContext()),
692 getContext());
693 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
694 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
695
696 // Update the remaining fixups, which have slid.
697 //
698 // FIXME: This is bad for performance, but will be eliminated by the
699 // move to MCInst specific fragments.
700 ++it3;
701 for (; it3 != ie3; ++it3)
702 it3->Offset += Amt;
703
704 // Update all the symbols for this fragment, which may have slid.
705 //
706 // FIXME: This is really really bad for performance, but will be
707 // eliminated by the move to MCInst specific fragments.
708 for (MCAssembler::symbol_iterator it = symbol_begin(),
709 ie = symbol_end(); it != ie; ++it) {
710 MCSymbolData &SD = *it;
711
712 if (it->getFragment() != DF)
713 continue;
714
715 if (SD.getOffset() > PrevOffset)
716 SD.setOffset(SD.getOffset() + Amt);
717 }
718
719 // Restart layout.
720 //
721 // FIXME: This is O(N^2), but will be eliminated once we have a smart
722 // MCAsmLayout object.
723 return true;
724 }
725 }
726 }
727
728 return false;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000729}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000730
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000731// Debugging methods
732
733namespace llvm {
734
735raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000736 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
737 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000738 return OS;
739}
740
741}
742
743void MCFragment::dump() {
744 raw_ostream &OS = llvm::errs();
745
746 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
747 << " FileSize:" << FileSize;
748
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000749 OS << ">";
750}
751
752void MCAlignFragment::dump() {
753 raw_ostream &OS = llvm::errs();
754
755 OS << "<MCAlignFragment ";
756 this->MCFragment::dump();
757 OS << "\n ";
758 OS << " Alignment:" << getAlignment()
759 << " Value:" << getValue() << " ValueSize:" << getValueSize()
760 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
761}
762
763void MCDataFragment::dump() {
764 raw_ostream &OS = llvm::errs();
765
766 OS << "<MCDataFragment ";
767 this->MCFragment::dump();
768 OS << "\n ";
769 OS << " Contents:[";
770 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
771 if (i) OS << ",";
772 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
773 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000774 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000775
776 if (!getFixups().empty()) {
777 OS << ",\n ";
778 OS << " Fixups:[";
779 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000780 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000781 OS << *it;
782 }
783 OS << "]";
784 }
785
786 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000787}
788
789void MCFillFragment::dump() {
790 raw_ostream &OS = llvm::errs();
791
792 OS << "<MCFillFragment ";
793 this->MCFragment::dump();
794 OS << "\n ";
795 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
796 << " Count:" << getCount() << ">";
797}
798
799void MCOrgFragment::dump() {
800 raw_ostream &OS = llvm::errs();
801
802 OS << "<MCOrgFragment ";
803 this->MCFragment::dump();
804 OS << "\n ";
805 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
806}
807
808void MCZeroFillFragment::dump() {
809 raw_ostream &OS = llvm::errs();
810
811 OS << "<MCZeroFillFragment ";
812 this->MCFragment::dump();
813 OS << "\n ";
814 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
815}
816
817void MCSectionData::dump() {
818 raw_ostream &OS = llvm::errs();
819
820 OS << "<MCSectionData";
821 OS << " Alignment:" << getAlignment() << " Address:" << Address
822 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000823 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000824 for (iterator it = begin(), ie = end(); it != ie; ++it) {
825 if (it != begin()) OS << ",\n ";
826 it->dump();
827 }
828 OS << "]>";
829}
830
831void MCSymbolData::dump() {
832 raw_ostream &OS = llvm::errs();
833
834 OS << "<MCSymbolData Symbol:" << getSymbol()
835 << " Fragment:" << getFragment() << " Offset:" << getOffset()
836 << " Flags:" << getFlags() << " Index:" << getIndex();
837 if (isCommon())
838 OS << " (common, size:" << getCommonSize()
839 << " align: " << getCommonAlignment() << ")";
840 if (isExternal())
841 OS << " (external)";
842 if (isPrivateExtern())
843 OS << " (private extern)";
844 OS << ">";
845}
846
847void MCAssembler::dump() {
848 raw_ostream &OS = llvm::errs();
849
850 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000851 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000852 for (iterator it = begin(), ie = end(); it != ie; ++it) {
853 if (it != begin()) OS << ",\n ";
854 it->dump();
855 }
856 OS << "],\n";
857 OS << " Symbols:[";
858
859 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000860 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000861 it->dump();
862 }
863 OS << "]>\n";
864}