1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/MC/MCAssembler.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/SmallVector.h" 13 #include "llvm/ADT/Statistic.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/Twine.h" 16 #include "llvm/MC/MCAsmBackend.h" 17 #include "llvm/MC/MCAsmInfo.h" 18 #include "llvm/MC/MCAsmLayout.h" 19 #include "llvm/MC/MCCodeEmitter.h" 20 #include "llvm/MC/MCCodeView.h" 21 #include "llvm/MC/MCContext.h" 22 #include "llvm/MC/MCDwarf.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCFixup.h" 25 #include "llvm/MC/MCFixupKindInfo.h" 26 #include "llvm/MC/MCFragment.h" 27 #include "llvm/MC/MCInst.h" 28 #include "llvm/MC/MCObjectWriter.h" 29 #include "llvm/MC/MCSection.h" 30 #include "llvm/MC/MCSectionELF.h" 31 #include "llvm/MC/MCSymbol.h" 32 #include "llvm/MC/MCValue.h" 33 #include "llvm/Support/Alignment.h" 34 #include "llvm/Support/Casting.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/EndianStream.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/LEB128.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include <cassert> 42 #include <cstdint> 43 #include <cstring> 44 #include <tuple> 45 #include <utility> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "assembler" 50 51 namespace { 52 namespace stats { 53 54 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total"); 55 STATISTIC(EmittedRelaxableFragments, 56 "Number of emitted assembler fragments - relaxable"); 57 STATISTIC(EmittedDataFragments, 58 "Number of emitted assembler fragments - data"); 59 STATISTIC(EmittedCompactEncodedInstFragments, 60 "Number of emitted assembler fragments - compact encoded inst"); 61 STATISTIC(EmittedAlignFragments, 62 "Number of emitted assembler fragments - align"); 63 STATISTIC(EmittedFillFragments, 64 "Number of emitted assembler fragments - fill"); 65 STATISTIC(EmittedOrgFragments, 66 "Number of emitted assembler fragments - org"); 67 STATISTIC(evaluateFixup, "Number of evaluated fixups"); 68 STATISTIC(FragmentLayouts, "Number of fragment layouts"); 69 STATISTIC(ObjectBytes, "Number of emitted object file bytes"); 70 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps"); 71 STATISTIC(RelaxedInstructions, "Number of relaxed instructions"); 72 73 } // end namespace stats 74 } // end anonymous namespace 75 76 // FIXME FIXME FIXME: There are number of places in this file where we convert 77 // what is a 64-bit assembler value used for computation into a value in the 78 // object file, which may truncate it. We should detect that truncation where 79 // invalid and report errors back. 80 81 /* *** */ 82 83 MCAssembler::MCAssembler(MCContext &Context, 84 std::unique_ptr<MCAsmBackend> Backend, 85 std::unique_ptr<MCCodeEmitter> Emitter, 86 std::unique_ptr<MCObjectWriter> Writer) 87 : Context(Context), Backend(std::move(Backend)), 88 Emitter(std::move(Emitter)), Writer(std::move(Writer)), 89 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false), 90 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) { 91 VersionInfo.Major = 0; // Major version == 0 for "none specified" 92 } 93 94 MCAssembler::~MCAssembler() = default; 95 96 void MCAssembler::reset() { 97 Sections.clear(); 98 Symbols.clear(); 99 IndirectSymbols.clear(); 100 DataRegions.clear(); 101 LinkerOptions.clear(); 102 FileNames.clear(); 103 ThumbFuncs.clear(); 104 BundleAlignSize = 0; 105 RelaxAll = false; 106 SubsectionsViaSymbols = false; 107 IncrementalLinkerCompatible = false; 108 ELFHeaderEFlags = 0; 109 LOHContainer.reset(); 110 VersionInfo.Major = 0; 111 VersionInfo.SDKVersion = VersionTuple(); 112 113 // reset objects owned by us 114 if (getBackendPtr()) 115 getBackendPtr()->reset(); 116 if (getEmitterPtr()) 117 getEmitterPtr()->reset(); 118 if (getWriterPtr()) 119 getWriterPtr()->reset(); 120 getLOHContainer().reset(); 121 } 122 123 bool MCAssembler::registerSection(MCSection &Section) { 124 if (Section.isRegistered()) 125 return false; 126 Sections.push_back(&Section); 127 Section.setIsRegistered(true); 128 return true; 129 } 130 131 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const { 132 if (ThumbFuncs.count(Symbol)) 133 return true; 134 135 if (!Symbol->isVariable()) 136 return false; 137 138 const MCExpr *Expr = Symbol->getVariableValue(); 139 140 MCValue V; 141 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr)) 142 return false; 143 144 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None) 145 return false; 146 147 const MCSymbolRefExpr *Ref = V.getSymA(); 148 if (!Ref) 149 return false; 150 151 if (Ref->getKind() != MCSymbolRefExpr::VK_None) 152 return false; 153 154 const MCSymbol &Sym = Ref->getSymbol(); 155 if (!isThumbFunc(&Sym)) 156 return false; 157 158 ThumbFuncs.insert(Symbol); // Cache it. 159 return true; 160 } 161 162 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const { 163 // Non-temporary labels should always be visible to the linker. 164 if (!Symbol.isTemporary()) 165 return true; 166 167 if (Symbol.isUsedInReloc()) 168 return true; 169 170 return false; 171 } 172 173 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const { 174 // Linker visible symbols define atoms. 175 if (isSymbolLinkerVisible(S)) 176 return &S; 177 178 // Absolute and undefined symbols have no defining atom. 179 if (!S.isInSection()) 180 return nullptr; 181 182 // Non-linker visible symbols in sections which can't be atomized have no 183 // defining atom. 184 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols( 185 *S.getFragment()->getParent())) 186 return nullptr; 187 188 // Otherwise, return the atom for the containing fragment. 189 return S.getFragment()->getAtom(); 190 } 191 192 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout, 193 const MCFixup &Fixup, const MCFragment *DF, 194 MCValue &Target, uint64_t &Value, 195 bool &WasForced) const { 196 ++stats::evaluateFixup; 197 198 // FIXME: This code has some duplication with recordRelocation. We should 199 // probably merge the two into a single callback that tries to evaluate a 200 // fixup and records a relocation if one is needed. 201 202 // On error claim to have completely evaluated the fixup, to prevent any 203 // further processing from being done. 204 const MCExpr *Expr = Fixup.getValue(); 205 MCContext &Ctx = getContext(); 206 Value = 0; 207 WasForced = false; 208 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) { 209 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression"); 210 return true; 211 } 212 if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 213 if (RefB->getKind() != MCSymbolRefExpr::VK_None) { 214 Ctx.reportError(Fixup.getLoc(), 215 "unsupported subtraction of qualified symbol"); 216 return true; 217 } 218 } 219 220 assert(getBackendPtr() && "Expected assembler backend"); 221 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags & 222 MCFixupKindInfo::FKF_IsTarget; 223 224 if (IsTarget) 225 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target, 226 Value, WasForced); 227 228 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags; 229 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags & 230 MCFixupKindInfo::FKF_IsPCRel; 231 232 bool IsResolved = false; 233 if (IsPCRel) { 234 if (Target.getSymB()) { 235 IsResolved = false; 236 } else if (!Target.getSymA()) { 237 IsResolved = false; 238 } else { 239 const MCSymbolRefExpr *A = Target.getSymA(); 240 const MCSymbol &SA = A->getSymbol(); 241 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) { 242 IsResolved = false; 243 } else if (auto *Writer = getWriterPtr()) { 244 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) || 245 Writer->isSymbolRefDifferenceFullyResolvedImpl( 246 *this, SA, *DF, false, true); 247 } 248 } 249 } else { 250 IsResolved = Target.isAbsolute(); 251 } 252 253 Value = Target.getConstant(); 254 255 if (const MCSymbolRefExpr *A = Target.getSymA()) { 256 const MCSymbol &Sym = A->getSymbol(); 257 if (Sym.isDefined()) 258 Value += Layout.getSymbolOffset(Sym); 259 } 260 if (const MCSymbolRefExpr *B = Target.getSymB()) { 261 const MCSymbol &Sym = B->getSymbol(); 262 if (Sym.isDefined()) 263 Value -= Layout.getSymbolOffset(Sym); 264 } 265 266 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags & 267 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits; 268 assert((ShouldAlignPC ? IsPCRel : true) && 269 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!"); 270 271 if (IsPCRel) { 272 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset(); 273 274 // A number of ARM fixups in Thumb mode require that the effective PC 275 // address be determined as the 32-bit aligned version of the actual offset. 276 if (ShouldAlignPC) Offset &= ~0x3; 277 Value -= Offset; 278 } 279 280 // Let the backend force a relocation if needed. 281 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) { 282 IsResolved = false; 283 WasForced = true; 284 } 285 286 return IsResolved; 287 } 288 289 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout, 290 const MCFragment &F) const { 291 assert(getBackendPtr() && "Requires assembler backend"); 292 switch (F.getKind()) { 293 case MCFragment::FT_Data: 294 return cast<MCDataFragment>(F).getContents().size(); 295 case MCFragment::FT_Relaxable: 296 return cast<MCRelaxableFragment>(F).getContents().size(); 297 case MCFragment::FT_CompactEncodedInst: 298 return cast<MCCompactEncodedInstFragment>(F).getContents().size(); 299 case MCFragment::FT_Fill: { 300 auto &FF = cast<MCFillFragment>(F); 301 int64_t NumValues = 0; 302 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) { 303 getContext().reportError(FF.getLoc(), 304 "expected assembly-time absolute expression"); 305 return 0; 306 } 307 int64_t Size = NumValues * FF.getValueSize(); 308 if (Size < 0) { 309 getContext().reportError(FF.getLoc(), "invalid number of bytes"); 310 return 0; 311 } 312 return Size; 313 } 314 315 case MCFragment::FT_LEB: 316 return cast<MCLEBFragment>(F).getContents().size(); 317 318 case MCFragment::FT_BoundaryAlign: 319 return cast<MCBoundaryAlignFragment>(F).getSize(); 320 321 case MCFragment::FT_SymbolId: 322 return 4; 323 324 case MCFragment::FT_Align: { 325 const MCAlignFragment &AF = cast<MCAlignFragment>(F); 326 unsigned Offset = Layout.getFragmentOffset(&AF); 327 unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment())); 328 329 // Insert extra Nops for code alignment if the target define 330 // shouldInsertExtraNopBytesForCodeAlign target hook. 331 if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() && 332 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size)) 333 return Size; 334 335 // If we are padding with nops, force the padding to be larger than the 336 // minimum nop size. 337 if (Size > 0 && AF.hasEmitNops()) { 338 while (Size % getBackend().getMinimumNopSize()) 339 Size += AF.getAlignment(); 340 } 341 if (Size > AF.getMaxBytesToEmit()) 342 return 0; 343 return Size; 344 } 345 346 case MCFragment::FT_Org: { 347 const MCOrgFragment &OF = cast<MCOrgFragment>(F); 348 MCValue Value; 349 if (!OF.getOffset().evaluateAsValue(Value, Layout)) { 350 getContext().reportError(OF.getLoc(), 351 "expected assembly-time absolute expression"); 352 return 0; 353 } 354 355 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF); 356 int64_t TargetLocation = Value.getConstant(); 357 if (const MCSymbolRefExpr *A = Value.getSymA()) { 358 uint64_t Val; 359 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) { 360 getContext().reportError(OF.getLoc(), "expected absolute expression"); 361 return 0; 362 } 363 TargetLocation += Val; 364 } 365 int64_t Size = TargetLocation - FragmentOffset; 366 if (Size < 0 || Size >= 0x40000000) { 367 getContext().reportError( 368 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) + 369 "' (at offset '" + Twine(FragmentOffset) + "')"); 370 return 0; 371 } 372 return Size; 373 } 374 375 case MCFragment::FT_Dwarf: 376 return cast<MCDwarfLineAddrFragment>(F).getContents().size(); 377 case MCFragment::FT_DwarfFrame: 378 return cast<MCDwarfCallFrameFragment>(F).getContents().size(); 379 case MCFragment::FT_CVInlineLines: 380 return cast<MCCVInlineLineTableFragment>(F).getContents().size(); 381 case MCFragment::FT_CVDefRange: 382 return cast<MCCVDefRangeFragment>(F).getContents().size(); 383 case MCFragment::FT_Dummy: 384 llvm_unreachable("Should not have been added"); 385 } 386 387 llvm_unreachable("invalid fragment kind"); 388 } 389 390 void MCAsmLayout::layoutFragment(MCFragment *F) { 391 MCFragment *Prev = F->getPrevNode(); 392 393 // We should never try to recompute something which is valid. 394 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!"); 395 // We should never try to compute the fragment layout if its predecessor 396 // isn't valid. 397 assert((!Prev || isFragmentValid(Prev)) && 398 "Attempt to compute fragment before its predecessor!"); 399 400 ++stats::FragmentLayouts; 401 402 // Compute fragment offset and size. 403 if (Prev) 404 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev); 405 else 406 F->Offset = 0; 407 LastValidFragment[F->getParent()] = F; 408 409 // If bundling is enabled and this fragment has instructions in it, it has to 410 // obey the bundling restrictions. With padding, we'll have: 411 // 412 // 413 // BundlePadding 414 // ||| 415 // ------------------------------------- 416 // Prev |##########| F | 417 // ------------------------------------- 418 // ^ 419 // | 420 // F->Offset 421 // 422 // The fragment's offset will point to after the padding, and its computed 423 // size won't include the padding. 424 // 425 // When the -mc-relax-all flag is used, we optimize bundling by writting the 426 // padding directly into fragments when the instructions are emitted inside 427 // the streamer. When the fragment is larger than the bundle size, we need to 428 // ensure that it's bundle aligned. This means that if we end up with 429 // multiple fragments, we must emit bundle padding between fragments. 430 // 431 // ".align N" is an example of a directive that introduces multiple 432 // fragments. We could add a special case to handle ".align N" by emitting 433 // within-fragment padding (which would produce less padding when N is less 434 // than the bundle size), but for now we don't. 435 // 436 if (Assembler.isBundlingEnabled() && F->hasInstructions()) { 437 assert(isa<MCEncodedFragment>(F) && 438 "Only MCEncodedFragment implementations have instructions"); 439 MCEncodedFragment *EF = cast<MCEncodedFragment>(F); 440 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF); 441 442 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize()) 443 report_fatal_error("Fragment can't be larger than a bundle size"); 444 445 uint64_t RequiredBundlePadding = 446 computeBundlePadding(Assembler, EF, EF->Offset, FSize); 447 if (RequiredBundlePadding > UINT8_MAX) 448 report_fatal_error("Padding cannot exceed 255 bytes"); 449 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding)); 450 EF->Offset += RequiredBundlePadding; 451 } 452 } 453 454 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) { 455 bool New = !Symbol.isRegistered(); 456 if (Created) 457 *Created = New; 458 if (New) { 459 Symbol.setIsRegistered(true); 460 Symbols.push_back(&Symbol); 461 } 462 } 463 464 void MCAssembler::writeFragmentPadding(raw_ostream &OS, 465 const MCEncodedFragment &EF, 466 uint64_t FSize) const { 467 assert(getBackendPtr() && "Expected assembler backend"); 468 // Should NOP padding be written out before this fragment? 469 unsigned BundlePadding = EF.getBundlePadding(); 470 if (BundlePadding > 0) { 471 assert(isBundlingEnabled() && 472 "Writing bundle padding with disabled bundling"); 473 assert(EF.hasInstructions() && 474 "Writing bundle padding for a fragment without instructions"); 475 476 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize); 477 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) { 478 // If the padding itself crosses a bundle boundary, it must be emitted 479 // in 2 pieces, since even nop instructions must not cross boundaries. 480 // v--------------v <- BundleAlignSize 481 // v---------v <- BundlePadding 482 // ---------------------------- 483 // | Prev |####|####| F | 484 // ---------------------------- 485 // ^-------------------^ <- TotalLength 486 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize(); 487 if (!getBackend().writeNopData(OS, DistanceToBoundary)) 488 report_fatal_error("unable to write NOP sequence of " + 489 Twine(DistanceToBoundary) + " bytes"); 490 BundlePadding -= DistanceToBoundary; 491 } 492 if (!getBackend().writeNopData(OS, BundlePadding)) 493 report_fatal_error("unable to write NOP sequence of " + 494 Twine(BundlePadding) + " bytes"); 495 } 496 } 497 498 /// Write the fragment \p F to the output file. 499 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm, 500 const MCAsmLayout &Layout, const MCFragment &F) { 501 // FIXME: Embed in fragments instead? 502 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F); 503 504 support::endianness Endian = Asm.getBackend().Endian; 505 506 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F)) 507 Asm.writeFragmentPadding(OS, *EF, FragmentSize); 508 509 // This variable (and its dummy usage) is to participate in the assert at 510 // the end of the function. 511 uint64_t Start = OS.tell(); 512 (void) Start; 513 514 ++stats::EmittedFragments; 515 516 switch (F.getKind()) { 517 case MCFragment::FT_Align: { 518 ++stats::EmittedAlignFragments; 519 const MCAlignFragment &AF = cast<MCAlignFragment>(F); 520 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!"); 521 522 uint64_t Count = FragmentSize / AF.getValueSize(); 523 524 // FIXME: This error shouldn't actually occur (the front end should emit 525 // multiple .align directives to enforce the semantics it wants), but is 526 // severe enough that we want to report it. How to handle this? 527 if (Count * AF.getValueSize() != FragmentSize) 528 report_fatal_error("undefined .align directive, value size '" + 529 Twine(AF.getValueSize()) + 530 "' is not a divisor of padding size '" + 531 Twine(FragmentSize) + "'"); 532 533 // See if we are aligning with nops, and if so do that first to try to fill 534 // the Count bytes. Then if that did not fill any bytes or there are any 535 // bytes left to fill use the Value and ValueSize to fill the rest. 536 // If we are aligning with nops, ask that target to emit the right data. 537 if (AF.hasEmitNops()) { 538 if (!Asm.getBackend().writeNopData(OS, Count)) 539 report_fatal_error("unable to write nop sequence of " + 540 Twine(Count) + " bytes"); 541 break; 542 } 543 544 // Otherwise, write out in multiples of the value size. 545 for (uint64_t i = 0; i != Count; ++i) { 546 switch (AF.getValueSize()) { 547 default: llvm_unreachable("Invalid size!"); 548 case 1: OS << char(AF.getValue()); break; 549 case 2: 550 support::endian::write<uint16_t>(OS, AF.getValue(), Endian); 551 break; 552 case 4: 553 support::endian::write<uint32_t>(OS, AF.getValue(), Endian); 554 break; 555 case 8: 556 support::endian::write<uint64_t>(OS, AF.getValue(), Endian); 557 break; 558 } 559 } 560 break; 561 } 562 563 case MCFragment::FT_Data: 564 ++stats::EmittedDataFragments; 565 OS << cast<MCDataFragment>(F).getContents(); 566 break; 567 568 case MCFragment::FT_Relaxable: 569 ++stats::EmittedRelaxableFragments; 570 OS << cast<MCRelaxableFragment>(F).getContents(); 571 break; 572 573 case MCFragment::FT_CompactEncodedInst: 574 ++stats::EmittedCompactEncodedInstFragments; 575 OS << cast<MCCompactEncodedInstFragment>(F).getContents(); 576 break; 577 578 case MCFragment::FT_Fill: { 579 ++stats::EmittedFillFragments; 580 const MCFillFragment &FF = cast<MCFillFragment>(F); 581 uint64_t V = FF.getValue(); 582 unsigned VSize = FF.getValueSize(); 583 const unsigned MaxChunkSize = 16; 584 char Data[MaxChunkSize]; 585 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size"); 586 // Duplicate V into Data as byte vector to reduce number of 587 // writes done. As such, do endian conversion here. 588 for (unsigned I = 0; I != VSize; ++I) { 589 unsigned index = Endian == support::little ? I : (VSize - I - 1); 590 Data[I] = uint8_t(V >> (index * 8)); 591 } 592 for (unsigned I = VSize; I < MaxChunkSize; ++I) 593 Data[I] = Data[I - VSize]; 594 595 // Set to largest multiple of VSize in Data. 596 const unsigned NumPerChunk = MaxChunkSize / VSize; 597 // Set ChunkSize to largest multiple of VSize in Data 598 const unsigned ChunkSize = VSize * NumPerChunk; 599 600 // Do copies by chunk. 601 StringRef Ref(Data, ChunkSize); 602 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I) 603 OS << Ref; 604 605 // do remainder if needed. 606 unsigned TrailingCount = FragmentSize % ChunkSize; 607 if (TrailingCount) 608 OS.write(Data, TrailingCount); 609 break; 610 } 611 612 case MCFragment::FT_LEB: { 613 const MCLEBFragment &LF = cast<MCLEBFragment>(F); 614 OS << LF.getContents(); 615 break; 616 } 617 618 case MCFragment::FT_BoundaryAlign: { 619 if (!Asm.getBackend().writeNopData(OS, FragmentSize)) 620 report_fatal_error("unable to write nop sequence of " + 621 Twine(FragmentSize) + " bytes"); 622 break; 623 } 624 625 case MCFragment::FT_SymbolId: { 626 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F); 627 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian); 628 break; 629 } 630 631 case MCFragment::FT_Org: { 632 ++stats::EmittedOrgFragments; 633 const MCOrgFragment &OF = cast<MCOrgFragment>(F); 634 635 for (uint64_t i = 0, e = FragmentSize; i != e; ++i) 636 OS << char(OF.getValue()); 637 638 break; 639 } 640 641 case MCFragment::FT_Dwarf: { 642 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F); 643 OS << OF.getContents(); 644 break; 645 } 646 case MCFragment::FT_DwarfFrame: { 647 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F); 648 OS << CF.getContents(); 649 break; 650 } 651 case MCFragment::FT_CVInlineLines: { 652 const auto &OF = cast<MCCVInlineLineTableFragment>(F); 653 OS << OF.getContents(); 654 break; 655 } 656 case MCFragment::FT_CVDefRange: { 657 const auto &DRF = cast<MCCVDefRangeFragment>(F); 658 OS << DRF.getContents(); 659 break; 660 } 661 case MCFragment::FT_Dummy: 662 llvm_unreachable("Should not have been added"); 663 } 664 665 assert(OS.tell() - Start == FragmentSize && 666 "The stream should advance by fragment size"); 667 } 668 669 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec, 670 const MCAsmLayout &Layout) const { 671 assert(getBackendPtr() && "Expected assembler backend"); 672 673 // Ignore virtual sections. 674 if (Sec->isVirtualSection()) { 675 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!"); 676 677 // Check that contents are only things legal inside a virtual section. 678 for (const MCFragment &F : *Sec) { 679 switch (F.getKind()) { 680 default: llvm_unreachable("Invalid fragment in virtual section!"); 681 case MCFragment::FT_Data: { 682 // Check that we aren't trying to write a non-zero contents (or fixups) 683 // into a virtual section. This is to support clients which use standard 684 // directives to fill the contents of virtual sections. 685 const MCDataFragment &DF = cast<MCDataFragment>(F); 686 if (DF.fixup_begin() != DF.fixup_end()) 687 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() + 688 " section '" + Sec->getName() + 689 "' cannot have fixups"); 690 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i) 691 if (DF.getContents()[i]) { 692 getContext().reportError(SMLoc(), 693 Sec->getVirtualSectionKind() + 694 " section '" + Sec->getName() + 695 "' cannot have non-zero initializers"); 696 break; 697 } 698 break; 699 } 700 case MCFragment::FT_Align: 701 // Check that we aren't trying to write a non-zero value into a virtual 702 // section. 703 assert((cast<MCAlignFragment>(F).getValueSize() == 0 || 704 cast<MCAlignFragment>(F).getValue() == 0) && 705 "Invalid align in virtual section!"); 706 break; 707 case MCFragment::FT_Fill: 708 assert((cast<MCFillFragment>(F).getValue() == 0) && 709 "Invalid fill in virtual section!"); 710 break; 711 } 712 } 713 714 return; 715 } 716 717 uint64_t Start = OS.tell(); 718 (void)Start; 719 720 for (const MCFragment &F : *Sec) 721 writeFragment(OS, *this, Layout, F); 722 723 assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec)); 724 } 725 726 std::tuple<MCValue, uint64_t, bool> 727 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F, 728 const MCFixup &Fixup) { 729 // Evaluate the fixup. 730 MCValue Target; 731 uint64_t FixedValue; 732 bool WasForced; 733 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue, 734 WasForced); 735 if (!IsResolved) { 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. 739 if (Target.getSymA() && Target.getSymB() && 740 getBackend().requiresDiffExpressionRelocations()) { 741 // The fixup represents the difference between two symbols, which the 742 // backend has indicated must be resolved at link time. Split up the fixup 743 // into two relocations, one for the add, and one for the sub, and emit 744 // both of these. The constant will be associated with the add half of the 745 // expression. 746 MCFixup FixupAdd = MCFixup::createAddFor(Fixup); 747 MCValue TargetAdd = 748 MCValue::get(Target.getSymA(), nullptr, Target.getConstant()); 749 getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd, 750 FixedValue); 751 MCFixup FixupSub = MCFixup::createSubFor(Fixup); 752 MCValue TargetSub = MCValue::get(Target.getSymB()); 753 getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub, 754 FixedValue); 755 } else { 756 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, 757 FixedValue); 758 } 759 } 760 return std::make_tuple(Target, FixedValue, IsResolved); 761 } 762 763 void MCAssembler::layout(MCAsmLayout &Layout) { 764 assert(getBackendPtr() && "Expected assembler backend"); 765 DEBUG_WITH_TYPE("mc-dump", { 766 errs() << "assembler backend - pre-layout\n--\n"; 767 dump(); }); 768 769 // Create dummy fragments and assign section ordinals. 770 unsigned SectionIndex = 0; 771 for (MCSection &Sec : *this) { 772 // Create dummy fragments to eliminate any empty sections, this simplifies 773 // layout. 774 if (Sec.getFragmentList().empty()) 775 new MCDataFragment(&Sec); 776 777 Sec.setOrdinal(SectionIndex++); 778 } 779 780 // Assign layout order indices to sections and fragments. 781 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) { 782 MCSection *Sec = Layout.getSectionOrder()[i]; 783 Sec->setLayoutOrder(i); 784 785 unsigned FragmentIndex = 0; 786 for (MCFragment &Frag : *Sec) 787 Frag.setLayoutOrder(FragmentIndex++); 788 } 789 790 // Layout until everything fits. 791 while (layoutOnce(Layout)) { 792 if (getContext().hadError()) 793 return; 794 // Size of fragments in one section can depend on the size of fragments in 795 // another. If any fragment has changed size, we have to re-layout (and 796 // as a result possibly further relax) all. 797 for (MCSection &Sec : *this) 798 Layout.invalidateFragmentsFrom(&*Sec.begin()); 799 } 800 801 DEBUG_WITH_TYPE("mc-dump", { 802 errs() << "assembler backend - post-relaxation\n--\n"; 803 dump(); }); 804 805 // Finalize the layout, including fragment lowering. 806 finishLayout(Layout); 807 808 DEBUG_WITH_TYPE("mc-dump", { 809 errs() << "assembler backend - final-layout\n--\n"; 810 dump(); }); 811 812 // Allow the object writer a chance to perform post-layout binding (for 813 // example, to set the index fields in the symbol data). 814 getWriter().executePostLayoutBinding(*this, Layout); 815 816 // Evaluate and apply the fixups, generating relocation entries as necessary. 817 for (MCSection &Sec : *this) { 818 for (MCFragment &Frag : Sec) { 819 // Data and relaxable fragments both have fixups. So only process 820 // those here. 821 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups 822 // being templated makes this tricky. 823 if (isa<MCEncodedFragment>(&Frag) && 824 isa<MCCompactEncodedInstFragment>(&Frag)) 825 continue; 826 if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag) && 827 !isa<MCAlignFragment>(&Frag)) 828 continue; 829 ArrayRef<MCFixup> Fixups; 830 MutableArrayRef<char> Contents; 831 const MCSubtargetInfo *STI = nullptr; 832 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) { 833 Fixups = FragWithFixups->getFixups(); 834 Contents = FragWithFixups->getContents(); 835 STI = FragWithFixups->getSubtargetInfo(); 836 assert(!FragWithFixups->hasInstructions() || STI != nullptr); 837 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) { 838 Fixups = FragWithFixups->getFixups(); 839 Contents = FragWithFixups->getContents(); 840 STI = FragWithFixups->getSubtargetInfo(); 841 assert(!FragWithFixups->hasInstructions() || STI != nullptr); 842 } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) { 843 Fixups = FragWithFixups->getFixups(); 844 Contents = FragWithFixups->getContents(); 845 } else if (auto *FragWithFixups = dyn_cast<MCDwarfLineAddrFragment>(&Frag)) { 846 Fixups = FragWithFixups->getFixups(); 847 Contents = FragWithFixups->getContents(); 848 } else if (auto *AF = dyn_cast<MCAlignFragment>(&Frag)) { 849 // Insert fixup type for code alignment if the target define 850 // shouldInsertFixupForCodeAlign target hook. 851 if (Sec.UseCodeAlign() && AF->hasEmitNops()) { 852 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, *AF); 853 } 854 continue; 855 } else if (auto *FragWithFixups = 856 dyn_cast<MCDwarfCallFrameFragment>(&Frag)) { 857 Fixups = FragWithFixups->getFixups(); 858 Contents = FragWithFixups->getContents(); 859 } else 860 llvm_unreachable("Unknown fragment with fixups!"); 861 for (const MCFixup &Fixup : Fixups) { 862 uint64_t FixedValue; 863 bool IsResolved; 864 MCValue Target; 865 std::tie(Target, FixedValue, IsResolved) = 866 handleFixup(Layout, Frag, Fixup); 867 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue, 868 IsResolved, STI); 869 } 870 } 871 } 872 } 873 874 void MCAssembler::Finish() { 875 // Create the layout object. 876 MCAsmLayout Layout(*this); 877 layout(Layout); 878 879 // Write the object file. 880 stats::ObjectBytes += getWriter().writeObject(*this, Layout); 881 } 882 883 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup, 884 const MCRelaxableFragment *DF, 885 const MCAsmLayout &Layout) const { 886 assert(getBackendPtr() && "Expected assembler backend"); 887 MCValue Target; 888 uint64_t Value; 889 bool WasForced; 890 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced); 891 if (Target.getSymA() && 892 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 && 893 Fixup.getKind() == FK_Data_1) 894 return false; 895 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF, 896 Layout, WasForced); 897 } 898 899 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F, 900 const MCAsmLayout &Layout) const { 901 assert(getBackendPtr() && "Expected assembler backend"); 902 // If this inst doesn't ever need relaxation, ignore it. This occurs when we 903 // are intentionally pushing out inst fragments, or because we relaxed a 904 // previous instruction to one that doesn't need relaxation. 905 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo())) 906 return false; 907 908 for (const MCFixup &Fixup : F->getFixups()) 909 if (fixupNeedsRelaxation(Fixup, F, Layout)) 910 return true; 911 912 return false; 913 } 914 915 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout, 916 MCRelaxableFragment &F) { 917 assert(getEmitterPtr() && 918 "Expected CodeEmitter defined for relaxInstruction"); 919 if (!fragmentNeedsRelaxation(&F, Layout)) 920 return false; 921 922 ++stats::RelaxedInstructions; 923 924 // FIXME-PERF: We could immediately lower out instructions if we can tell 925 // they are fully resolved, to avoid retesting on later passes. 926 927 // Relax the fragment. 928 929 MCInst Relaxed = F.getInst(); 930 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo()); 931 932 // Encode the new instruction. 933 // 934 // FIXME-PERF: If it matters, we could let the target do this. It can 935 // probably do so more efficiently in many cases. 936 SmallVector<MCFixup, 4> Fixups; 937 SmallString<256> Code; 938 raw_svector_ostream VecOS(Code); 939 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo()); 940 941 // Update the fragment. 942 F.setInst(Relaxed); 943 F.getContents() = Code; 944 F.getFixups() = Fixups; 945 946 return true; 947 } 948 949 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) { 950 uint64_t OldSize = LF.getContents().size(); 951 int64_t Value; 952 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout); 953 if (!Abs) 954 report_fatal_error("sleb128 and uleb128 expressions must be absolute"); 955 SmallString<8> &Data = LF.getContents(); 956 Data.clear(); 957 raw_svector_ostream OSE(Data); 958 // The compiler can generate EH table assembly that is impossible to assemble 959 // without either adding padding to an LEB fragment or adding extra padding 960 // to a later alignment fragment. To accommodate such tables, relaxation can 961 // only increase an LEB fragment size here, not decrease it. See PR35809. 962 if (LF.isSigned()) 963 encodeSLEB128(Value, OSE, OldSize); 964 else 965 encodeULEB128(Value, OSE, OldSize); 966 return OldSize != LF.getContents().size(); 967 } 968 969 /// Check if the branch crosses the boundary. 970 /// 971 /// \param StartAddr start address of the fused/unfused branch. 972 /// \param Size size of the fused/unfused branch. 973 /// \param BoundaryAlignment alignment requirement of the branch. 974 /// \returns true if the branch cross the boundary. 975 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size, 976 Align BoundaryAlignment) { 977 uint64_t EndAddr = StartAddr + Size; 978 return (StartAddr >> Log2(BoundaryAlignment)) != 979 ((EndAddr - 1) >> Log2(BoundaryAlignment)); 980 } 981 982 /// Check if the branch is against the boundary. 983 /// 984 /// \param StartAddr start address of the fused/unfused branch. 985 /// \param Size size of the fused/unfused branch. 986 /// \param BoundaryAlignment alignment requirement of the branch. 987 /// \returns true if the branch is against the boundary. 988 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size, 989 Align BoundaryAlignment) { 990 uint64_t EndAddr = StartAddr + Size; 991 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0; 992 } 993 994 /// Check if the branch needs padding. 995 /// 996 /// \param StartAddr start address of the fused/unfused branch. 997 /// \param Size size of the fused/unfused branch. 998 /// \param BoundaryAlignment alignment requirement of the branch. 999 /// \returns true if the branch needs padding. 1000 static bool needPadding(uint64_t StartAddr, uint64_t Size, 1001 Align BoundaryAlignment) { 1002 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) || 1003 isAgainstBoundary(StartAddr, Size, BoundaryAlignment); 1004 } 1005 1006 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout, 1007 MCBoundaryAlignFragment &BF) { 1008 // BoundaryAlignFragment that doesn't need to align any fragment should not be 1009 // relaxed. 1010 if (!BF.getLastFragment()) 1011 return false; 1012 1013 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF); 1014 uint64_t AlignedSize = 0; 1015 for (const MCFragment *F = BF.getLastFragment(); F != &BF; 1016 F = F->getPrevNode()) 1017 AlignedSize += computeFragmentSize(Layout, *F); 1018 1019 Align BoundaryAlignment = BF.getAlignment(); 1020 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment) 1021 ? offsetToAlignment(AlignedOffset, BoundaryAlignment) 1022 : 0U; 1023 if (NewSize == BF.getSize()) 1024 return false; 1025 BF.setSize(NewSize); 1026 Layout.invalidateFragmentsFrom(&BF); 1027 return true; 1028 } 1029 1030 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout, 1031 MCDwarfLineAddrFragment &DF) { 1032 MCContext &Context = Layout.getAssembler().getContext(); 1033 uint64_t OldSize = DF.getContents().size(); 1034 int64_t AddrDelta; 1035 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout); 1036 assert(Abs && "We created a line delta with an invalid expression"); 1037 (void)Abs; 1038 int64_t LineDelta; 1039 LineDelta = DF.getLineDelta(); 1040 SmallVectorImpl<char> &Data = DF.getContents(); 1041 Data.clear(); 1042 raw_svector_ostream OSE(Data); 1043 DF.getFixups().clear(); 1044 1045 if (!getBackend().requiresDiffExpressionRelocations()) { 1046 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta, 1047 AddrDelta, OSE); 1048 } else { 1049 uint32_t Offset; 1050 uint32_t Size; 1051 bool SetDelta = MCDwarfLineAddr::FixedEncode(Context, 1052 getDWARFLinetableParams(), 1053 LineDelta, AddrDelta, 1054 OSE, &Offset, &Size); 1055 // Add Fixups for address delta or new address. 1056 const MCExpr *FixupExpr; 1057 if (SetDelta) { 1058 FixupExpr = &DF.getAddrDelta(); 1059 } else { 1060 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta()); 1061 FixupExpr = ABE->getLHS(); 1062 } 1063 DF.getFixups().push_back( 1064 MCFixup::create(Offset, FixupExpr, 1065 MCFixup::getKindForSize(Size, false /*isPCRel*/))); 1066 } 1067 1068 return OldSize != Data.size(); 1069 } 1070 1071 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout, 1072 MCDwarfCallFrameFragment &DF) { 1073 MCContext &Context = Layout.getAssembler().getContext(); 1074 uint64_t OldSize = DF.getContents().size(); 1075 int64_t AddrDelta; 1076 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout); 1077 assert(Abs && "We created call frame with an invalid expression"); 1078 (void) Abs; 1079 SmallVectorImpl<char> &Data = DF.getContents(); 1080 Data.clear(); 1081 raw_svector_ostream OSE(Data); 1082 DF.getFixups().clear(); 1083 1084 if (getBackend().requiresDiffExpressionRelocations()) { 1085 uint32_t Offset; 1086 uint32_t Size; 1087 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE, &Offset, 1088 &Size); 1089 if (Size) { 1090 DF.getFixups().push_back(MCFixup::create( 1091 Offset, &DF.getAddrDelta(), 1092 MCFixup::getKindForSizeInBits(Size /*In bits.*/, false /*isPCRel*/))); 1093 } 1094 } else { 1095 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE); 1096 } 1097 1098 return OldSize != Data.size(); 1099 } 1100 1101 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout, 1102 MCCVInlineLineTableFragment &F) { 1103 unsigned OldSize = F.getContents().size(); 1104 getContext().getCVContext().encodeInlineLineTable(Layout, F); 1105 return OldSize != F.getContents().size(); 1106 } 1107 1108 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout, 1109 MCCVDefRangeFragment &F) { 1110 unsigned OldSize = F.getContents().size(); 1111 getContext().getCVContext().encodeDefRange(Layout, F); 1112 return OldSize != F.getContents().size(); 1113 } 1114 1115 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) { 1116 switch(F.getKind()) { 1117 default: 1118 return false; 1119 case MCFragment::FT_Relaxable: 1120 assert(!getRelaxAll() && 1121 "Did not expect a MCRelaxableFragment in RelaxAll mode"); 1122 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F)); 1123 case MCFragment::FT_Dwarf: 1124 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F)); 1125 case MCFragment::FT_DwarfFrame: 1126 return relaxDwarfCallFrameFragment(Layout, 1127 cast<MCDwarfCallFrameFragment>(F)); 1128 case MCFragment::FT_LEB: 1129 return relaxLEB(Layout, cast<MCLEBFragment>(F)); 1130 case MCFragment::FT_BoundaryAlign: 1131 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F)); 1132 case MCFragment::FT_CVInlineLines: 1133 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F)); 1134 case MCFragment::FT_CVDefRange: 1135 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F)); 1136 } 1137 } 1138 1139 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) { 1140 // Holds the first fragment which needed relaxing during this layout. It will 1141 // remain NULL if none were relaxed. 1142 // When a fragment is relaxed, all the fragments following it should get 1143 // invalidated because their offset is going to change. 1144 MCFragment *FirstRelaxedFragment = nullptr; 1145 1146 // Attempt to relax all the fragments in the section. 1147 for (MCFragment &Frag : Sec) { 1148 // Check if this is a fragment that needs relaxation. 1149 bool RelaxedFrag = relaxFragment(Layout, Frag); 1150 if (RelaxedFrag && !FirstRelaxedFragment) 1151 FirstRelaxedFragment = &Frag; 1152 } 1153 if (FirstRelaxedFragment) { 1154 Layout.invalidateFragmentsFrom(FirstRelaxedFragment); 1155 return true; 1156 } 1157 return false; 1158 } 1159 1160 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) { 1161 ++stats::RelaxationSteps; 1162 1163 bool WasRelaxed = false; 1164 for (MCSection &Sec : *this) { 1165 while (layoutSectionOnce(Layout, Sec)) 1166 WasRelaxed = true; 1167 } 1168 1169 return WasRelaxed; 1170 } 1171 1172 void MCAssembler::finishLayout(MCAsmLayout &Layout) { 1173 assert(getBackendPtr() && "Expected assembler backend"); 1174 // The layout is done. Mark every fragment as valid. 1175 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) { 1176 MCSection &Section = *Layout.getSectionOrder()[i]; 1177 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin()); 1178 computeFragmentSize(Layout, *Section.getFragmentList().rbegin()); 1179 } 1180 getBackend().finishLayout(*this, Layout); 1181 } 1182 1183 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1184 LLVM_DUMP_METHOD void MCAssembler::dump() const{ 1185 raw_ostream &OS = errs(); 1186 1187 OS << "<MCAssembler\n"; 1188 OS << " Sections:[\n "; 1189 for (const_iterator it = begin(), ie = end(); it != ie; ++it) { 1190 if (it != begin()) OS << ",\n "; 1191 it->dump(); 1192 } 1193 OS << "],\n"; 1194 OS << " Symbols:["; 1195 1196 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) { 1197 if (it != symbol_begin()) OS << ",\n "; 1198 OS << "("; 1199 it->dump(); 1200 OS << ", Index:" << it->getIndex() << ", "; 1201 OS << ")"; 1202 } 1203 OS << "]>\n"; 1204 } 1205 #endif 1206