blob: 411c6d974831bccefd34cc57799b2c7ed21d22fd [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 Dunbarac2884a2010-03-25 22:49:09 +000022#include "llvm/Support/Debug.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000023#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000024#include "llvm/Support/raw_ostream.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
Chris Lattner23132b12009-08-24 03:52:50 +000028#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000029using namespace llvm;
30
Daniel Dunbarff547842010-03-23 23:47:14 +000031namespace {
32namespace stats {
Daniel Dunbar0adcd352009-08-25 21:10:45 +000033STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
Daniel Dunbarff547842010-03-23 23:47:14 +000034STATISTIC(EvaluateFixup, "Number of evaluated fixups");
Daniel Dunbarac2884a2010-03-25 22:49:09 +000035STATISTIC(FragmentLayouts, "Number of fragment layouts");
Daniel Dunbarff547842010-03-23 23:47:14 +000036STATISTIC(ObjectBytes, "Number of emitted object file bytes");
Daniel Dunbarac2884a2010-03-25 22:49:09 +000037STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
38STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
39STATISTIC(SectionLayouts, "Number of section layouts");
Daniel Dunbarff547842010-03-23 23:47:14 +000040}
41}
Daniel Dunbar0adcd352009-08-25 21:10:45 +000042
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000043// FIXME FIXME FIXME: There are number of places in this file where we convert
44// what is a 64-bit assembler value used for computation into a value in the
45// object file, which may truncate it. We should detect that truncation where
46// invalid and report errors back.
47
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000048/* *** */
49
Daniel Dunbar9005d452010-05-14 00:37:21 +000050MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
51 : Assembler(Asm), LastValidFragment(0)
52 {
Daniel Dunbarbc1a0cf2010-05-12 15:42:59 +000053 // Compute the section layout order. Virtual sections must go last.
54 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
55 if (!Asm.getBackend().isVirtualSection(it->getSection()))
56 SectionOrder.push_back(&*it);
57 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
58 if (Asm.getBackend().isVirtualSection(it->getSection()))
59 SectionOrder.push_back(&*it);
60}
61
Daniel Dunbar9005d452010-05-14 00:37:21 +000062bool MCAsmLayout::isSectionUpToDate(const MCSectionData *SD) const {
63 // The first section is always up-to-date.
64 unsigned Index = SD->getLayoutOrder();
65 if (!Index)
66 return true;
67
68 // Otherwise, sections are always implicitly computed when the preceeding
69 // fragment is layed out.
70 const MCSectionData *Prev = getSectionOrder()[Index - 1];
71 return isFragmentUpToDate(&(Prev->getFragmentList().back()));
72}
73
74bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
75 return (LastValidFragment &&
76 F->getLayoutOrder() <= LastValidFragment->getLayoutOrder());
77}
78
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +000079void MCAsmLayout::UpdateForSlide(MCFragment *F, int SlideAmount) {
80 // We shouldn't have to do anything special to support negative slides, and it
Daniel Dunbar651804c2010-05-11 17:22:50 +000081 // is a perfectly valid thing to do as long as other parts of the system can
82 // guarantee convergence.
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +000083 assert(SlideAmount >= 0 && "Negative slides not yet supported");
84
85 // Update the layout by simply recomputing the layout for the entire
86 // file. This is trivially correct, but very slow.
87 //
88 // FIXME-PERF: This is O(N^2), but will be eliminated once we get smarter.
89
Daniel Dunbard13a0ca2010-05-12 17:56:47 +000090 // Layout the sections in order.
Daniel Dunbarb69fc042010-05-13 20:40:12 +000091 LayoutFile();
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +000092}
93
Daniel Dunbaraa0d3502010-05-13 08:43:31 +000094void MCAsmLayout::FragmentReplaced(MCFragment *Src, MCFragment *Dst) {
Daniel Dunbar9005d452010-05-14 00:37:21 +000095 if (LastValidFragment == Src)
96 LastValidFragment = Dst;
97
Daniel Dunbaraa0d3502010-05-13 08:43:31 +000098 Dst->Offset = Src->Offset;
99 Dst->EffectiveSize = Src->EffectiveSize;
100}
101
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000102uint64_t MCAsmLayout::getFragmentAddress(const MCFragment *F) const {
Daniel Dunbar7c3d45a2010-03-25 01:03:24 +0000103 assert(F->getParent() && "Missing section()!");
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000104 return getSectionAddress(F->getParent()) + getFragmentOffset(F);
105}
106
107uint64_t MCAsmLayout::getFragmentEffectiveSize(const MCFragment *F) const {
108 assert(F->EffectiveSize != ~UINT64_C(0) && "Address not set!");
109 return F->EffectiveSize;
110}
111
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000112uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
113 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
114 return F->Offset;
115}
116
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000117uint64_t MCAsmLayout::getSymbolAddress(const MCSymbolData *SD) const {
Daniel Dunbar7c3d45a2010-03-25 01:03:24 +0000118 assert(SD->getFragment() && "Invalid getAddress() on undefined symbol!");
119 return getFragmentAddress(SD->getFragment()) + SD->getOffset();
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000120}
121
122uint64_t MCAsmLayout::getSectionAddress(const MCSectionData *SD) const {
Daniel Dunbar7c3d45a2010-03-25 01:03:24 +0000123 assert(SD->Address != ~UINT64_C(0) && "Address not set!");
124 return SD->Address;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000125}
126
Daniel Dunbar2661f112010-05-13 03:19:50 +0000127uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
Daniel Dunbarafc6acd2010-05-14 00:37:11 +0000128 // The size is the last fragment's end offset.
Daniel Dunbar2661f112010-05-13 03:19:50 +0000129 const MCFragment &F = SD->getFragmentList().back();
130 return getFragmentOffset(&F) + getFragmentEffectiveSize(&F);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000131}
132
133uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
Daniel Dunbar2661f112010-05-13 03:19:50 +0000134 // Virtual sections have no file size.
135 if (getAssembler().getBackend().isVirtualSection(SD->getSection()))
136 return 0;
137
138 // Otherwise, the file size is the same as the address space size.
139 return getSectionAddressSize(SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000140}
141
Daniel Dunbar2661f112010-05-13 03:19:50 +0000142uint64_t MCAsmLayout::getSectionSize(const MCSectionData *SD) const {
Daniel Dunbar2661f112010-05-13 03:19:50 +0000143 // The logical size is the address space size minus any tail padding.
144 uint64_t Size = getSectionAddressSize(SD);
145 const MCAlignFragment *AF =
146 dyn_cast<MCAlignFragment>(&(SD->getFragmentList().back()));
147 if (AF && AF->hasOnlyAlignAddress())
148 Size -= getFragmentEffectiveSize(AF);
149
150 return Size;
Daniel Dunbarb5844ff2010-05-13 01:10:22 +0000151}
152
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000153/* *** */
154
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000155MCFragment::MCFragment() : Kind(FragmentType(~0)) {
156}
157
Daniel Dunbar5e835962009-08-26 02:48:04 +0000158MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar071f73d2010-05-10 22:45:09 +0000159 : Kind(_Kind), Parent(_Parent), Atom(0), EffectiveSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000160{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000161 if (Parent)
162 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000163}
164
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000165MCFragment::~MCFragment() {
166}
167
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000168/* *** */
169
Daniel Dunbar81e40002009-08-27 00:38:04 +0000170MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000171
172MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000173 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000174 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000175 Address(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000176 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000177{
178 if (A)
179 A->getSectionList().push_back(this);
180}
181
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000182/* *** */
183
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000184MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000185
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000186MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000187 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000188 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000189 IsExternal(false), IsPrivateExtern(false),
190 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000191{
192 if (A)
193 A->getSymbolList().push_back(this);
194}
195
196/* *** */
197
Daniel Dunbar1f3e4452010-03-11 01:34:27 +0000198MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
Daniel Dunbarcf871e52010-03-19 10:43:18 +0000199 MCCodeEmitter &_Emitter, raw_ostream &_OS)
200 : Context(_Context), Backend(_Backend), Emitter(_Emitter),
Daniel Dunbarac2884a2010-03-25 22:49:09 +0000201 OS(_OS), RelaxAll(false), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000202{
203}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000204
205MCAssembler::~MCAssembler() {
206}
207
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000208static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
209 const MCAsmFixup &Fixup,
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000210 const MCValue Target,
211 const MCSection *BaseSection) {
212 // The effective fixup address is
213 // addr(atom(A)) + offset(A)
214 // - addr(atom(B)) - offset(B)
215 // - addr(<base symbol>) + <fixup offset from base symbol>
216 // and the offsets are not relocatable, so the fixup is fully resolved when
217 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
218 //
219 // The simple (Darwin, except on x86_64) way of dealing with this was to
220 // assume that any reference to a temporary symbol *must* be a temporary
221 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
222 // relocation to a temporary symbol (in the same section) is fully
223 // resolved. This also works in conjunction with absolutized .set, which
224 // requires the compiler to use .set to absolutize the differences between
225 // symbols which the compiler knows to be assembly time constants, so we don't
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +0000226 // need to worry about considering symbol differences fully resolved.
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000227
228 // Non-relative fixups are only resolved if constant.
229 if (!BaseSection)
230 return Target.isAbsolute();
231
232 // Otherwise, relative fixups are only resolved if not a difference and the
233 // target is a temporary in the same section.
234 if (Target.isAbsolute() || Target.getSymB())
235 return false;
236
237 const MCSymbol *A = &Target.getSymA()->getSymbol();
238 if (!A->isTemporary() || !A->isInSection() ||
239 &A->getSection() != BaseSection)
240 return false;
241
242 return true;
243}
244
Daniel Dunbar034843a2010-03-19 03:18:18 +0000245static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000246 const MCAsmLayout &Layout,
Daniel Dunbar034843a2010-03-19 03:18:18 +0000247 const MCAsmFixup &Fixup,
Daniel Dunbar034843a2010-03-19 03:18:18 +0000248 const MCValue Target,
249 const MCSymbolData *BaseSymbol) {
250 // The effective fixup address is
251 // addr(atom(A)) + offset(A)
252 // - addr(atom(B)) - offset(B)
253 // - addr(BaseSymbol) + <fixup offset from base symbol>
254 // and the offsets are not relocatable, so the fixup is fully resolved when
255 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
256 //
257 // Note that "false" is almost always conservatively correct (it means we emit
258 // a relocation which is unnecessary), except when it would force us to emit a
259 // relocation which the target cannot encode.
260
261 const MCSymbolData *A_Base = 0, *B_Base = 0;
262 if (const MCSymbolRefExpr *A = Target.getSymA()) {
263 // Modified symbol references cannot be resolved.
264 if (A->getKind() != MCSymbolRefExpr::VK_None)
265 return false;
266
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000267 A_Base = Asm.getAtom(Layout, &Asm.getSymbolData(A->getSymbol()));
Daniel Dunbar034843a2010-03-19 03:18:18 +0000268 if (!A_Base)
269 return false;
270 }
271
272 if (const MCSymbolRefExpr *B = Target.getSymB()) {
273 // Modified symbol references cannot be resolved.
274 if (B->getKind() != MCSymbolRefExpr::VK_None)
275 return false;
276
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000277 B_Base = Asm.getAtom(Layout, &Asm.getSymbolData(B->getSymbol()));
Daniel Dunbar034843a2010-03-19 03:18:18 +0000278 if (!B_Base)
279 return false;
280 }
281
282 // If there is no base, A and B have to be the same atom for this fixup to be
283 // fully resolved.
284 if (!BaseSymbol)
285 return A_Base == B_Base;
286
287 // Otherwise, B must be missing and A must be the base.
288 return !B_Base && BaseSymbol == A_Base;
289}
290
Daniel Dunbar23869852010-03-19 03:18:09 +0000291bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
292 // Non-temporary labels should always be visible to the linker.
293 if (!SD->getSymbol().isTemporary())
294 return true;
295
296 // Absolute temporary labels are never visible.
297 if (!SD->getFragment())
298 return false;
299
300 // Otherwise, check if the section requires symbols even for temporary labels.
301 return getBackend().doesSectionRequireSymbols(
302 SD->getFragment()->getParent()->getSection());
303}
304
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000305const MCSymbolData *MCAssembler::getAtom(const MCAsmLayout &Layout,
306 const MCSymbolData *SD) const {
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000307 // Linker visible symbols define atoms.
308 if (isSymbolLinkerVisible(SD))
309 return SD;
310
311 // Absolute and undefined symbols have no defining atom.
312 if (!SD->getFragment())
313 return 0;
314
Daniel Dunbara5f1d572010-05-12 00:38:17 +0000315 // Non-linker visible symbols in sections which can't be atomized have no
316 // defining atom.
317 if (!getBackend().isSectionAtomizable(
318 SD->getFragment()->getParent()->getSection()))
319 return 0;
320
Daniel Dunbar651804c2010-05-11 17:22:50 +0000321 // Otherwise, return the atom for the containing fragment.
322 return SD->getFragment()->getAtom();
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000323}
324
Daniel Dunbar9d39e612010-03-22 21:49:41 +0000325bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
326 const MCAsmFixup &Fixup, const MCFragment *DF,
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000327 MCValue &Target, uint64_t &Value) const {
Daniel Dunbarff547842010-03-23 23:47:14 +0000328 ++stats::EvaluateFixup;
329
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000330 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
Chris Lattner75361b62010-04-07 22:58:41 +0000331 report_fatal_error("expected relocatable expression");
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000332
333 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
334 // doesn't support small relocations, but then under what criteria does the
335 // assembler allow symbol differences?
336
337 Value = Target.getConstant();
338
Daniel Dunbarb36052f2010-03-19 10:43:23 +0000339 bool IsPCRel =
340 Emitter.getFixupKindInfo(Fixup.Kind).Flags & MCFixupKindInfo::FKF_IsPCRel;
341 bool IsResolved = true;
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000342 if (const MCSymbolRefExpr *A = Target.getSymA()) {
343 if (A->getSymbol().isDefined())
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000344 Value += Layout.getSymbolAddress(&getSymbolData(A->getSymbol()));
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000345 else
346 IsResolved = false;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000347 }
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000348 if (const MCSymbolRefExpr *B = Target.getSymB()) {
349 if (B->getSymbol().isDefined())
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000350 Value -= Layout.getSymbolAddress(&getSymbolData(B->getSymbol()));
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000351 else
352 IsResolved = false;
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000353 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000354
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000355 // If we are using scattered symbols, determine whether this value is actually
356 // resolved; scattering may cause atoms to move.
357 if (IsResolved && getBackend().hasScatteredSymbols()) {
358 if (getBackend().hasReliableSymbolDifference()) {
Daniel Dunbar034843a2010-03-19 03:18:18 +0000359 // If this is a PCrel relocation, find the base atom (identified by its
360 // symbol) that the fixup value is relative to.
361 const MCSymbolData *BaseSymbol = 0;
362 if (IsPCRel) {
Daniel Dunbar651804c2010-05-11 17:22:50 +0000363 BaseSymbol = DF->getAtom();
Daniel Dunbar034843a2010-03-19 03:18:18 +0000364 if (!BaseSymbol)
365 IsResolved = false;
366 }
367
368 if (IsResolved)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000369 IsResolved = isScatteredFixupFullyResolved(*this, Layout, Fixup, Target,
Daniel Dunbar034843a2010-03-19 03:18:18 +0000370 BaseSymbol);
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000371 } else {
372 const MCSection *BaseSection = 0;
373 if (IsPCRel)
374 BaseSection = &DF->getParent()->getSection();
375
Daniel Dunbarc6f59822010-03-22 21:49:38 +0000376 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, Target,
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000377 BaseSection);
378 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000379 }
380
381 if (IsPCRel)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000382 Value -= Layout.getFragmentAddress(DF) + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000383
384 return IsResolved;
385}
386
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000387uint64_t MCAssembler::ComputeFragmentSize(MCAsmLayout &Layout,
388 const MCFragment &F,
389 uint64_t SectionAddress,
390 uint64_t FragmentOffset) const {
391 switch (F.getKind()) {
392 case MCFragment::FT_Data:
393 return cast<MCDataFragment>(F).getContents().size();
394 case MCFragment::FT_Fill:
395 return cast<MCFillFragment>(F).getSize();
396 case MCFragment::FT_Inst:
397 return cast<MCInstFragment>(F).getInstSize();
398
399 case MCFragment::FT_Align: {
400 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
401
402 assert((!AF.hasOnlyAlignAddress() || !AF.getNextNode()) &&
403 "Invalid OnlyAlignAddress bit, not the last fragment!");
404
405 uint64_t Size = OffsetToAlignment(SectionAddress + FragmentOffset,
406 AF.getAlignment());
407
408 // Honor MaxBytesToEmit.
409 if (Size > AF.getMaxBytesToEmit())
410 return 0;
411
412 return Size;
413 }
414
415 case MCFragment::FT_Org: {
416 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
417
418 // FIXME: We should compute this sooner, we don't want to recurse here, and
419 // we would like to be more functional.
420 int64_t TargetLocation;
421 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
422 report_fatal_error("expected assembly-time absolute expression");
423
424 // FIXME: We need a way to communicate this error.
425 int64_t Offset = TargetLocation - FragmentOffset;
426 if (Offset < 0)
427 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
428 "' (at offset '" + Twine(FragmentOffset) + "'");
429
430 return Offset;
431 }
432 }
433
434 assert(0 && "invalid fragment kind");
435 return 0;
436}
437
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000438void MCAsmLayout::LayoutFile() {
Daniel Dunbar9005d452010-05-14 00:37:21 +0000439 // Initialize the first section and set the valid fragment layout point.
440 LastValidFragment = 0;
Daniel Dunbar11c41112010-05-14 00:37:17 +0000441 if (!getSectionOrder().empty())
442 getSectionOrder().front()->Address = 0;
443
Daniel Dunbarafc6acd2010-05-14 00:37:11 +0000444 for (unsigned i = 0, e = getSectionOrder().size(); i != e; ++i) {
445 MCSectionData *SD = getSectionOrder()[i];
446
Daniel Dunbarafc6acd2010-05-14 00:37:11 +0000447 for (MCSectionData::iterator it = SD->begin(),
448 ie = SD->end(); it != ie; ++it)
449 LayoutFragment(it);
450 }
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000451}
452
453void MCAsmLayout::LayoutFragment(MCFragment *F) {
Daniel Dunbar9005d452010-05-14 00:37:21 +0000454 MCFragment *Prev = F->getPrevNode();
Daniel Dunbarf0d17d22010-05-12 21:35:25 +0000455
Daniel Dunbar9005d452010-05-14 00:37:21 +0000456 // We should never try to recompute something which is up-to-date.
457 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
458 // We should never try to compute the fragment layout if the section isn't
459 // up-to-date.
460 assert(isSectionUpToDate(F->getParent()) &&
461 "Attempt to compute fragment before it's section!");
462 // We should never try to compute the fragment layout if it's predecessor
463 // isn't up-to-date.
464 assert((!Prev || isFragmentUpToDate(Prev)) &&
465 "Attempt to compute fragment before it's predecessor!");
Daniel Dunbarf0d17d22010-05-12 21:35:25 +0000466
467 ++stats::FragmentLayouts;
468
Daniel Dunbar9005d452010-05-14 00:37:21 +0000469 // Compute the fragment start address.
470 uint64_t StartAddress = F->getParent()->Address;
471 uint64_t Address = StartAddress;
472 if (Prev)
473 Address += Prev->Offset + Prev->EffectiveSize;
474
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000475 // Compute fragment offset and size.
Daniel Dunbarafc6acd2010-05-14 00:37:11 +0000476 F->Offset = Address - StartAddress;
477 F->EffectiveSize = getAssembler().ComputeFragmentSize(*this, *F, StartAddress,
478 F->Offset);
Daniel Dunbar9005d452010-05-14 00:37:21 +0000479 LastValidFragment = F;
Daniel Dunbar11c41112010-05-14 00:37:17 +0000480
481 // If this is the last fragment in a section, update the next section address.
482 if (!F->getNextNode()) {
483 unsigned NextIndex = F->getParent()->getLayoutOrder() + 1;
484 if (NextIndex != getSectionOrder().size())
485 LayoutSection(getSectionOrder()[NextIndex]);
486 }
Daniel Dunbarf0d17d22010-05-12 21:35:25 +0000487}
488
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000489void MCAsmLayout::LayoutSection(MCSectionData *SD) {
490 unsigned SectionOrderIndex = SD->getLayoutOrder();
Daniel Dunbarf476b002010-03-25 18:16:42 +0000491
Daniel Dunbarac2884a2010-03-25 22:49:09 +0000492 ++stats::SectionLayouts;
493
Daniel Dunbar61066db2010-05-13 02:34:14 +0000494 // Compute the section start address.
Daniel Dunbard13a0ca2010-05-12 17:56:47 +0000495 uint64_t StartAddress = 0;
496 if (SectionOrderIndex) {
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000497 MCSectionData *Prev = getSectionOrder()[SectionOrderIndex - 1];
498 StartAddress = getSectionAddress(Prev) + getSectionAddressSize(Prev);
Daniel Dunbard13a0ca2010-05-12 17:56:47 +0000499 }
500
Daniel Dunbar61066db2010-05-13 02:34:14 +0000501 // Honor the section alignment requirements.
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000502 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
Daniel Dunbarf476b002010-03-25 18:16:42 +0000503
Daniel Dunbar61066db2010-05-13 02:34:14 +0000504 // Set the section address.
Daniel Dunbarafc6acd2010-05-14 00:37:11 +0000505 SD->Address = StartAddress;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000506}
507
Daniel Dunbar53b23382010-03-19 09:28:59 +0000508/// WriteFragmentData - Write the \arg F data to the output file.
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000509static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
510 const MCFragment &F, MCObjectWriter *OW) {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000511 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000512 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000513
Daniel Dunbarff547842010-03-23 23:47:14 +0000514 ++stats::EmittedFragments;
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000515
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000516 // FIXME: Embed in fragments instead?
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000517 uint64_t FragmentSize = Layout.getFragmentEffectiveSize(&F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000518 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000519 case MCFragment::FT_Align: {
520 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000521 uint64_t Count = FragmentSize / AF.getValueSize();
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000522
Daniel Dunbare73d49e2010-05-12 22:51:27 +0000523 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
524
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000525 // FIXME: This error shouldn't actually occur (the front end should emit
526 // multiple .align directives to enforce the semantics it wants), but is
527 // severe enough that we want to report it. How to handle this?
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000528 if (Count * AF.getValueSize() != FragmentSize)
Chris Lattner75361b62010-04-07 22:58:41 +0000529 report_fatal_error("undefined .align directive, value size '" +
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000530 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000531 "' is not a divisor of padding size '" +
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000532 Twine(FragmentSize) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000533
Kevin Enderby6e720482010-02-23 18:26:34 +0000534 // See if we are aligning with nops, and if so do that first to try to fill
535 // the Count bytes. Then if that did not fill any bytes or there are any
536 // bytes left to fill use the the Value and ValueSize to fill the rest.
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000537 // If we are aligning with nops, ask that target to emit the right data.
Daniel Dunbar1c154132010-05-12 22:56:23 +0000538 if (AF.hasEmitNops()) {
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000539 if (!Asm.getBackend().WriteNopData(Count, OW))
Chris Lattner75361b62010-04-07 22:58:41 +0000540 report_fatal_error("unable to write nop sequence of " +
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000541 Twine(Count) + " bytes");
542 break;
Kevin Enderby6e720482010-02-23 18:26:34 +0000543 }
544
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000545 // Otherwise, write out in multiples of the value size.
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000546 for (uint64_t i = 0; i != Count; ++i) {
547 switch (AF.getValueSize()) {
548 default:
549 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000550 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
551 case 2: OW->Write16(uint16_t(AF.getValue())); break;
552 case 4: OW->Write32(uint32_t(AF.getValue())); break;
553 case 8: OW->Write64(uint64_t(AF.getValue())); break;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000554 }
555 }
556 break;
557 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000558
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000559 case MCFragment::FT_Data: {
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000560 MCDataFragment &DF = cast<MCDataFragment>(F);
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000561 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000562 OW->WriteBytes(DF.getContents().str());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000563 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000564 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000565
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000566 case MCFragment::FT_Fill: {
567 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000568
569 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
570
Daniel Dunbar3153fec2010-05-12 22:51:32 +0000571 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000572 switch (FF.getValueSize()) {
573 default:
574 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000575 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
576 case 2: OW->Write16(uint16_t(FF.getValue())); break;
577 case 4: OW->Write32(uint32_t(FF.getValue())); break;
578 case 8: OW->Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000579 }
580 }
581 break;
582 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000583
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000584 case MCFragment::FT_Inst:
585 llvm_unreachable("unexpected inst fragment after lowering");
586 break;
587
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000588 case MCFragment::FT_Org: {
589 MCOrgFragment &OF = cast<MCOrgFragment>(F);
590
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000591 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000592 OW->Write8(uint8_t(OF.getValue()));
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000593
594 break;
595 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000596 }
597
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000598 assert(OW->getStream().tell() - Start == FragmentSize);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000599}
600
Daniel Dunbar53b23382010-03-19 09:28:59 +0000601void MCAssembler::WriteSectionData(const MCSectionData *SD,
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000602 const MCAsmLayout &Layout,
Daniel Dunbar53b23382010-03-19 09:28:59 +0000603 MCObjectWriter *OW) const {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000604 // Ignore virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000605 if (getBackend().isVirtualSection(SD->getSection())) {
Daniel Dunbar054be922010-05-13 03:50:50 +0000606 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000607
608 // Check that contents are only things legal inside a virtual section.
609 for (MCSectionData::const_iterator it = SD->begin(),
610 ie = SD->end(); it != ie; ++it) {
611 switch (it->getKind()) {
612 default:
613 assert(0 && "Invalid fragment in virtual section!");
614 case MCFragment::FT_Align:
615 assert(!cast<MCAlignFragment>(it)->getValueSize() &&
616 "Invalid align in virtual section!");
617 break;
618 case MCFragment::FT_Fill:
619 assert(!cast<MCFillFragment>(it)->getValueSize() &&
620 "Invalid fill in virtual section!");
621 break;
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000622 }
623 }
624
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000625 return;
626 }
627
Daniel Dunbar53b23382010-03-19 09:28:59 +0000628 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000629 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000630
Daniel Dunbar53b23382010-03-19 09:28:59 +0000631 for (MCSectionData::const_iterator it = SD->begin(),
632 ie = SD->end(); it != ie; ++it)
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000633 WriteFragmentData(*this, Layout, *it, OW);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000634
Daniel Dunbar054be922010-05-13 03:50:50 +0000635 assert(OW->getStream().tell() - Start == Layout.getSectionFileSize(SD));
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000636}
637
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000638void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000639 DEBUG_WITH_TYPE("mc-dump", {
640 llvm::errs() << "assembler backend - pre-layout\n--\n";
641 dump(); });
642
Daniel Dunbar61066db2010-05-13 02:34:14 +0000643 // Create the layout object.
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000644 MCAsmLayout Layout(*this);
Daniel Dunbar61066db2010-05-13 02:34:14 +0000645
646 // Insert additional align fragments for concrete sections to explicitly pad
647 // the previous section to match their alignment requirements. This is for
648 // 'gas' compatibility, it shouldn't strictly be necessary.
649 //
650 // FIXME: This may be Mach-O specific.
651 for (unsigned i = 1, e = Layout.getSectionOrder().size(); i < e; ++i) {
652 MCSectionData *SD = Layout.getSectionOrder()[i];
653
654 // Ignore sections without alignment requirements.
655 unsigned Align = SD->getAlignment();
656 if (Align <= 1)
657 continue;
658
659 // Ignore virtual sections, they don't cause file size modifications.
660 if (getBackend().isVirtualSection(SD->getSection()))
661 continue;
662
663 // Otherwise, create a new align fragment at the end of the previous
664 // section.
665 MCAlignFragment *AF = new MCAlignFragment(Align, 0, 1, Align,
666 Layout.getSectionOrder()[i - 1]);
667 AF->setOnlyAlignAddress(true);
668 }
669
Daniel Dunbar337718e2010-05-14 00:37:14 +0000670 // Create dummy fragments and assign section ordinals.
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000671 unsigned SectionIndex = 0;
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000672 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
673 // Create dummy fragments to eliminate any empty sections, this simplifies
674 // layout.
675 if (it->getFragmentList().empty()) {
676 unsigned ValueSize = 1;
677 if (getBackend().isVirtualSection(it->getSection()))
678 ValueSize = 1;
679 new MCFillFragment(0, 1, 0, it);
680 }
681
682 it->setOrdinal(SectionIndex++);
Daniel Dunbar337718e2010-05-14 00:37:14 +0000683 }
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000684
Daniel Dunbar337718e2010-05-14 00:37:14 +0000685 // Assign layout order indices to sections and fragments.
686 unsigned FragmentIndex = 0;
687 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
688 MCSectionData *SD = Layout.getSectionOrder()[i];
689 SD->setLayoutOrder(i);
690
691 for (MCSectionData::iterator it2 = SD->begin(),
692 ie2 = SD->end(); it2 != ie2; ++it2)
693 it2->setLayoutOrder(FragmentIndex++);
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000694 }
695
Daniel Dunbar61066db2010-05-13 02:34:14 +0000696 // Layout until everything fits.
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000697 while (LayoutOnce(Layout))
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000698 continue;
699
700 DEBUG_WITH_TYPE("mc-dump", {
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000701 llvm::errs() << "assembler backend - post-relaxation\n--\n";
702 dump(); });
703
704 // Finalize the layout, including fragment lowering.
705 FinishLayout(Layout);
706
707 DEBUG_WITH_TYPE("mc-dump", {
708 llvm::errs() << "assembler backend - final-layout\n--\n";
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000709 dump(); });
710
Daniel Dunbarff547842010-03-23 23:47:14 +0000711 uint64_t StartOffset = OS.tell();
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000712 llvm::OwningPtr<MCObjectWriter> Writer(getBackend().createObjectWriter(OS));
713 if (!Writer)
Chris Lattner75361b62010-04-07 22:58:41 +0000714 report_fatal_error("unable to create object writer!");
Daniel Dunbarbacba992010-03-19 07:09:33 +0000715
716 // Allow the object writer a chance to perform post-layout binding (for
717 // example, to set the index fields in the symbol data).
Daniel Dunbar1a9158c2010-03-19 10:43:26 +0000718 Writer->ExecutePostLayoutBinding(*this);
Daniel Dunbarbacba992010-03-19 07:09:33 +0000719
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000720 // Evaluate and apply the fixups, generating relocation entries as necessary.
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000721 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
722 for (MCSectionData::iterator it2 = it->begin(),
723 ie2 = it->end(); it2 != ie2; ++it2) {
724 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
725 if (!DF)
726 continue;
727
728 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
729 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
730 MCAsmFixup &Fixup = *it3;
731
732 // Evaluate the fixup.
733 MCValue Target;
734 uint64_t FixedValue;
735 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
736 // The fixup was unresolved, we need a relocation. Inform the object
737 // writer of the relocation, and give it an opportunity to adjust the
738 // fixup value if need be.
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000739 Writer->RecordRelocation(*this, Layout, DF, Fixup, Target,FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000740 }
741
Daniel Dunbar87190c42010-03-19 09:28:12 +0000742 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000743 }
744 }
745 }
746
Daniel Dunbarbacba992010-03-19 07:09:33 +0000747 // Write the object file.
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000748 Writer->WriteObject(*this, Layout);
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000749 OS.flush();
Daniel Dunbarff547842010-03-23 23:47:14 +0000750
751 stats::ObjectBytes += OS.tell() - StartOffset;
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000752}
753
Daniel Dunbar9d39e612010-03-22 21:49:41 +0000754bool MCAssembler::FixupNeedsRelaxation(const MCAsmFixup &Fixup,
755 const MCFragment *DF,
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000756 const MCAsmLayout &Layout) const {
Daniel Dunbarac2884a2010-03-25 22:49:09 +0000757 if (getRelaxAll())
758 return true;
759
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000760 // If we cannot resolve the fixup value, it requires relaxation.
761 MCValue Target;
762 uint64_t Value;
763 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
764 return true;
765
766 // Otherwise, relax if the value is too big for a (signed) i8.
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +0000767 //
768 // FIXME: This is target dependent!
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000769 return int64_t(Value) != int64_t(int8_t(Value));
770}
771
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000772bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
773 const MCAsmLayout &Layout) const {
774 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
775 // are intentionally pushing out inst fragments, or because we relaxed a
776 // previous instruction to one that doesn't need relaxation.
777 if (!getBackend().MayNeedRelaxation(IF->getInst(), IF->getFixups()))
778 return false;
779
780 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
781 ie = IF->fixup_end(); it != ie; ++it)
782 if (FixupNeedsRelaxation(*it, IF, Layout))
783 return true;
784
785 return false;
786}
787
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000788bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
Daniel Dunbarff547842010-03-23 23:47:14 +0000789 ++stats::RelaxationSteps;
790
Daniel Dunbard13a0ca2010-05-12 17:56:47 +0000791 // Layout the sections in order.
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000792 Layout.LayoutFile();
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000793
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000794 // Scan for fragments that need relaxation.
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +0000795 bool WasRelaxed = false;
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000796 for (iterator it = begin(), ie = end(); it != ie; ++it) {
797 MCSectionData &SD = *it;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000798
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000799 for (MCSectionData::iterator it2 = SD.begin(),
800 ie2 = SD.end(); it2 != ie2; ++it2) {
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000801 // Check if this is an instruction fragment that needs relaxation.
802 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
803 if (!IF || !FragmentNeedsRelaxation(IF, Layout))
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000804 continue;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000805
Daniel Dunbarff547842010-03-23 23:47:14 +0000806 ++stats::RelaxedInstructions;
807
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000808 // FIXME-PERF: We could immediately lower out instructions if we can tell
809 // they are fully resolved, to avoid retesting on later passes.
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000810
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000811 // Relax the fragment.
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000812
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000813 MCInst Relaxed;
814 getBackend().RelaxInstruction(IF, Relaxed);
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000815
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000816 // Encode the new instruction.
817 //
818 // FIXME-PERF: If it matters, we could let the target do this. It can
819 // probably do so more efficiently in many cases.
820 SmallVector<MCFixup, 4> Fixups;
821 SmallString<256> Code;
822 raw_svector_ostream VecOS(Code);
823 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
824 VecOS.flush();
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000825
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000826 // Update the instruction fragment.
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +0000827 int SlideAmount = Code.size() - IF->getInstSize();
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000828 IF->setInst(Relaxed);
829 IF->getCode() = Code;
830 IF->getFixups().clear();
831 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
832 MCFixup &F = Fixups[i];
833 IF->getFixups().push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
834 F.getKind()));
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000835 }
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000836
Daniel Dunbarac2884a2010-03-25 22:49:09 +0000837 // Update the layout, and remember that we relaxed. If we are relaxing
838 // everything, we can skip this step since nothing will depend on updating
839 // the values.
840 if (!getRelaxAll())
841 Layout.UpdateForSlide(IF, SlideAmount);
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +0000842 WasRelaxed = true;
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000843 }
844 }
845
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +0000846 return WasRelaxed;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000847}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000848
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000849void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
850 // Lower out any instruction fragments, to simplify the fixup application and
851 // output.
852 //
853 // FIXME-PERF: We don't have to do this, but the assumption is that it is
854 // cheap (we will mostly end up eliminating fragments and appending on to data
855 // fragments), so the extra complexity downstream isn't worth it. Evaluate
856 // this assumption.
857 for (iterator it = begin(), ie = end(); it != ie; ++it) {
858 MCSectionData &SD = *it;
859
860 for (MCSectionData::iterator it2 = SD.begin(),
861 ie2 = SD.end(); it2 != ie2; ++it2) {
862 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
863 if (!IF)
864 continue;
865
866 // Create a new data fragment for the instruction.
867 //
Daniel Dunbar337055e2010-03-23 03:13:05 +0000868 // FIXME-PERF: Reuse previous data fragment if possible.
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000869 MCDataFragment *DF = new MCDataFragment();
870 SD.getFragmentList().insert(it2, DF);
871
872 // Update the data fragments layout data.
Daniel Dunbar9799de92010-03-23 01:39:05 +0000873 DF->setParent(IF->getParent());
Daniel Dunbar651804c2010-05-11 17:22:50 +0000874 DF->setAtom(IF->getAtom());
Daniel Dunbar337718e2010-05-14 00:37:14 +0000875 DF->setLayoutOrder(IF->getLayoutOrder());
Daniel Dunbaraa0d3502010-05-13 08:43:31 +0000876 Layout.FragmentReplaced(IF, DF);
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000877
Daniel Dunbar9799de92010-03-23 01:39:05 +0000878 // Copy in the data and the fixups.
879 DF->getContents().append(IF->getCode().begin(), IF->getCode().end());
880 for (unsigned i = 0, e = IF->getFixups().size(); i != e; ++i)
881 DF->getFixups().push_back(IF->getFixups()[i]);
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000882
883 // Delete the instruction fragment and update the iterator.
884 SD.getFragmentList().erase(IF);
885 it2 = DF;
886 }
887 }
888}
889
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000890// Debugging methods
891
892namespace llvm {
893
894raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000895 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
896 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000897 return OS;
898}
899
900}
901
902void MCFragment::dump() {
903 raw_ostream &OS = llvm::errs();
904
Daniel Dunbar337718e2010-05-14 00:37:14 +0000905 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
906 << " Offset:" << Offset << " EffectiveSize:" << EffectiveSize << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000907}
908
909void MCAlignFragment::dump() {
910 raw_ostream &OS = llvm::errs();
911
912 OS << "<MCAlignFragment ";
913 this->MCFragment::dump();
Daniel Dunbar456b5012010-05-13 01:10:26 +0000914 if (hasEmitNops())
915 OS << " (emit nops)";
916 if (hasOnlyAlignAddress())
917 OS << " (only align section)";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000918 OS << "\n ";
919 OS << " Alignment:" << getAlignment()
920 << " Value:" << getValue() << " ValueSize:" << getValueSize()
921 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
922}
923
924void MCDataFragment::dump() {
925 raw_ostream &OS = llvm::errs();
926
927 OS << "<MCDataFragment ";
928 this->MCFragment::dump();
929 OS << "\n ";
930 OS << " Contents:[";
931 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
932 if (i) OS << ",";
933 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
934 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000935 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000936
937 if (!getFixups().empty()) {
938 OS << ",\n ";
939 OS << " Fixups:[";
940 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000941 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000942 OS << *it;
943 }
944 OS << "]";
945 }
946
947 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000948}
949
950void MCFillFragment::dump() {
951 raw_ostream &OS = llvm::errs();
952
953 OS << "<MCFillFragment ";
954 this->MCFragment::dump();
955 OS << "\n ";
956 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
Daniel Dunbar3153fec2010-05-12 22:51:32 +0000957 << " Size:" << getSize() << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000958}
959
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000960void MCInstFragment::dump() {
961 raw_ostream &OS = llvm::errs();
962
963 OS << "<MCInstFragment ";
964 this->MCFragment::dump();
965 OS << "\n ";
966 OS << " Inst:";
967 getInst().dump_pretty(OS);
968 OS << ">";
969}
970
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000971void MCOrgFragment::dump() {
972 raw_ostream &OS = llvm::errs();
973
974 OS << "<MCOrgFragment ";
975 this->MCFragment::dump();
976 OS << "\n ";
977 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
978}
979
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000980void MCSectionData::dump() {
981 raw_ostream &OS = llvm::errs();
982
983 OS << "<MCSectionData";
984 OS << " Alignment:" << getAlignment() << " Address:" << Address
Daniel Dunbar2661f112010-05-13 03:19:50 +0000985 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000986 for (iterator it = begin(), ie = end(); it != ie; ++it) {
987 if (it != begin()) OS << ",\n ";
988 it->dump();
989 }
990 OS << "]>";
991}
992
993void MCSymbolData::dump() {
994 raw_ostream &OS = llvm::errs();
995
996 OS << "<MCSymbolData Symbol:" << getSymbol()
997 << " Fragment:" << getFragment() << " Offset:" << getOffset()
998 << " Flags:" << getFlags() << " Index:" << getIndex();
999 if (isCommon())
1000 OS << " (common, size:" << getCommonSize()
1001 << " align: " << getCommonAlignment() << ")";
1002 if (isExternal())
1003 OS << " (external)";
1004 if (isPrivateExtern())
1005 OS << " (private extern)";
1006 OS << ">";
1007}
1008
1009void MCAssembler::dump() {
1010 raw_ostream &OS = llvm::errs();
1011
1012 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001013 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001014 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1015 if (it != begin()) OS << ",\n ";
1016 it->dump();
1017 }
1018 OS << "],\n";
1019 OS << " Symbols:[";
1020
1021 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001022 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001023 it->dump();
1024 }
1025 OS << "]>\n";
1026}