1 //===- bolt/Core/BinaryEmitter.cpp - Emit code and data -------------------===// 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 // This file implements the collection of functions and classes used for 10 // emission of code and data into object/binary file. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "bolt/Core/BinaryEmitter.h" 15 #include "bolt/Core/BinaryContext.h" 16 #include "bolt/Core/BinaryFunction.h" 17 #include "bolt/Core/DebugData.h" 18 #include "bolt/Core/FunctionLayout.h" 19 #include "bolt/Utils/CommandLineOpts.h" 20 #include "bolt/Utils/Utils.h" 21 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h" 22 #include "llvm/MC/MCSection.h" 23 #include "llvm/MC/MCStreamer.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/LEB128.h" 26 #include "llvm/Support/SMLoc.h" 27 28 #define DEBUG_TYPE "bolt" 29 30 using namespace llvm; 31 using namespace bolt; 32 33 namespace opts { 34 35 extern cl::opt<JumpTableSupportLevel> JumpTables; 36 extern cl::opt<bool> PreserveBlocksAlignment; 37 38 cl::opt<bool> AlignBlocks("align-blocks", cl::desc("align basic blocks"), 39 cl::cat(BoltOptCategory)); 40 41 cl::opt<MacroFusionType> 42 AlignMacroOpFusion("align-macro-fusion", 43 cl::desc("fix instruction alignment for macro-fusion (x86 relocation mode)"), 44 cl::init(MFT_HOT), 45 cl::values(clEnumValN(MFT_NONE, "none", 46 "do not insert alignment no-ops for macro-fusion"), 47 clEnumValN(MFT_HOT, "hot", 48 "only insert alignment no-ops on hot execution paths (default)"), 49 clEnumValN(MFT_ALL, "all", 50 "always align instructions to allow macro-fusion")), 51 cl::ZeroOrMore, 52 cl::cat(BoltRelocCategory)); 53 54 static cl::list<std::string> 55 BreakFunctionNames("break-funcs", 56 cl::CommaSeparated, 57 cl::desc("list of functions to core dump on (debugging)"), 58 cl::value_desc("func1,func2,func3,..."), 59 cl::Hidden, 60 cl::cat(BoltCategory)); 61 62 static cl::list<std::string> 63 FunctionPadSpec("pad-funcs", 64 cl::CommaSeparated, 65 cl::desc("list of functions to pad with amount of bytes"), 66 cl::value_desc("func1:pad1,func2:pad2,func3:pad3,..."), 67 cl::Hidden, 68 cl::cat(BoltCategory)); 69 70 static cl::opt<bool> MarkFuncs( 71 "mark-funcs", 72 cl::desc("mark function boundaries with break instruction to make " 73 "sure we accidentally don't cross them"), 74 cl::ReallyHidden, cl::cat(BoltCategory)); 75 76 static cl::opt<bool> PrintJumpTables("print-jump-tables", 77 cl::desc("print jump tables"), cl::Hidden, 78 cl::cat(BoltCategory)); 79 80 static cl::opt<bool> 81 X86AlignBranchBoundaryHotOnly("x86-align-branch-boundary-hot-only", 82 cl::desc("only apply branch boundary alignment in hot code"), 83 cl::init(true), 84 cl::cat(BoltOptCategory)); 85 86 size_t padFunction(const BinaryFunction &Function) { 87 static std::map<std::string, size_t> FunctionPadding; 88 89 if (FunctionPadding.empty() && !FunctionPadSpec.empty()) { 90 for (std::string &Spec : FunctionPadSpec) { 91 size_t N = Spec.find(':'); 92 if (N == std::string::npos) 93 continue; 94 std::string Name = Spec.substr(0, N); 95 size_t Padding = std::stoull(Spec.substr(N + 1)); 96 FunctionPadding[Name] = Padding; 97 } 98 } 99 100 for (auto &FPI : FunctionPadding) { 101 std::string Name = FPI.first; 102 size_t Padding = FPI.second; 103 if (Function.hasNameRegex(Name)) 104 return Padding; 105 } 106 107 return 0; 108 } 109 110 } // namespace opts 111 112 namespace { 113 using JumpTable = bolt::JumpTable; 114 115 class BinaryEmitter { 116 private: 117 BinaryEmitter(const BinaryEmitter &) = delete; 118 BinaryEmitter &operator=(const BinaryEmitter &) = delete; 119 120 MCStreamer &Streamer; 121 BinaryContext &BC; 122 123 public: 124 BinaryEmitter(MCStreamer &Streamer, BinaryContext &BC) 125 : Streamer(Streamer), BC(BC) {} 126 127 /// Emit all code and data. 128 void emitAll(StringRef OrgSecPrefix); 129 130 /// Emit function code. The caller is responsible for emitting function 131 /// symbol(s) and setting the section to emit the code to. 132 void emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF, 133 bool EmitCodeOnly = false); 134 135 private: 136 /// Emit function code. 137 void emitFunctions(); 138 139 /// Emit a single function. 140 bool emitFunction(BinaryFunction &BF, FunctionFragment &FF); 141 142 /// Helper for emitFunctionBody to write data inside a function 143 /// (used for AArch64) 144 void emitConstantIslands(BinaryFunction &BF, bool EmitColdPart, 145 BinaryFunction *OnBehalfOf = nullptr); 146 147 /// Emit jump tables for the function. 148 void emitJumpTables(const BinaryFunction &BF); 149 150 /// Emit jump table data. Callee supplies sections for the data. 151 void emitJumpTable(const JumpTable &JT, MCSection *HotSection, 152 MCSection *ColdSection); 153 154 void emitCFIInstruction(const MCCFIInstruction &Inst) const; 155 156 /// Emit exception handling ranges for the function. 157 void emitLSDA(BinaryFunction &BF, const FunctionFragment &FF); 158 159 /// Emit line number information corresponding to \p NewLoc. \p PrevLoc 160 /// provides a context for de-duplication of line number info. 161 /// \p FirstInstr indicates if \p NewLoc represents the first instruction 162 /// in a sequence, such as a function fragment. 163 /// 164 /// Return new current location which is either \p NewLoc or \p PrevLoc. 165 SMLoc emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, SMLoc PrevLoc, 166 bool FirstInstr); 167 168 /// Use \p FunctionEndSymbol to mark the end of the line info sequence. 169 /// Note that it does not automatically result in the insertion of the EOS 170 /// marker in the line table program, but provides one to the DWARF generator 171 /// when it needs it. 172 void emitLineInfoEnd(const BinaryFunction &BF, MCSymbol *FunctionEndSymbol); 173 174 /// Emit debug line info for unprocessed functions from CUs that include 175 /// emitted functions. 176 void emitDebugLineInfoForOriginalFunctions(); 177 178 /// Emit debug line for CUs that were not modified. 179 void emitDebugLineInfoForUnprocessedCUs(); 180 181 /// Emit data sections that have code references in them. 182 void emitDataSections(StringRef OrgSecPrefix); 183 }; 184 185 } // anonymous namespace 186 187 void BinaryEmitter::emitAll(StringRef OrgSecPrefix) { 188 Streamer.initSections(false, *BC.STI); 189 190 if (opts::UpdateDebugSections && BC.isELF()) { 191 // Force the emission of debug line info into allocatable section to ensure 192 // RuntimeDyld will process it without ProcessAllSections flag. 193 // 194 // NB: on MachO all sections are required for execution, hence no need 195 // to change flags/attributes. 196 MCSectionELF *ELFDwarfLineSection = 197 static_cast<MCSectionELF *>(BC.MOFI->getDwarfLineSection()); 198 ELFDwarfLineSection->setFlags(ELF::SHF_ALLOC); 199 } 200 201 if (RuntimeLibrary *RtLibrary = BC.getRuntimeLibrary()) 202 RtLibrary->emitBinary(BC, Streamer); 203 204 BC.getTextSection()->setAlignment(Align(opts::AlignText)); 205 206 emitFunctions(); 207 208 if (opts::UpdateDebugSections) { 209 emitDebugLineInfoForOriginalFunctions(); 210 DwarfLineTable::emit(BC, Streamer); 211 } 212 213 emitDataSections(OrgSecPrefix); 214 215 Streamer.emitLabel(BC.Ctx->getOrCreateSymbol("_end")); 216 } 217 218 void BinaryEmitter::emitFunctions() { 219 auto emit = [&](const std::vector<BinaryFunction *> &Functions) { 220 const bool HasProfile = BC.NumProfiledFuncs > 0; 221 const bool OriginalAllowAutoPadding = Streamer.getAllowAutoPadding(); 222 for (BinaryFunction *Function : Functions) { 223 if (!BC.shouldEmit(*Function)) 224 continue; 225 226 LLVM_DEBUG(dbgs() << "BOLT: generating code for function \"" << *Function 227 << "\" : " << Function->getFunctionNumber() << '\n'); 228 229 // Was any part of the function emitted. 230 bool Emitted = false; 231 232 // Turn off Intel JCC Erratum mitigation for cold code if requested 233 if (HasProfile && opts::X86AlignBranchBoundaryHotOnly && 234 !Function->hasValidProfile()) 235 Streamer.setAllowAutoPadding(false); 236 237 FunctionLayout &Layout = Function->getLayout(); 238 Emitted |= emitFunction(*Function, Layout.getMainFragment()); 239 240 if (Function->isSplit()) { 241 if (opts::X86AlignBranchBoundaryHotOnly) 242 Streamer.setAllowAutoPadding(false); 243 244 assert((Layout.fragment_size() == 1 || Function->isSimple()) && 245 "Only simple functions can have fragments"); 246 for (FunctionFragment &FF : Layout.getSplitFragments()) { 247 // Skip empty fragments so no symbols and sections for empty fragments 248 // are generated 249 if (FF.empty() && !Function->hasConstantIsland()) 250 continue; 251 Emitted |= emitFunction(*Function, FF); 252 } 253 } 254 255 Streamer.setAllowAutoPadding(OriginalAllowAutoPadding); 256 257 if (Emitted) 258 Function->setEmitted(/*KeepCFG=*/opts::PrintCacheMetrics); 259 } 260 }; 261 262 // Mark the start of hot text. 263 if (opts::HotText) { 264 Streamer.switchSection(BC.getTextSection()); 265 Streamer.emitLabel(BC.getHotTextStartSymbol()); 266 } 267 268 // Emit functions in sorted order. 269 std::vector<BinaryFunction *> SortedFunctions = BC.getSortedFunctions(); 270 emit(SortedFunctions); 271 272 // Emit functions added by BOLT. 273 emit(BC.getInjectedBinaryFunctions()); 274 275 // Mark the end of hot text. 276 if (opts::HotText) { 277 Streamer.switchSection(BC.getTextSection()); 278 Streamer.emitLabel(BC.getHotTextEndSymbol()); 279 } 280 } 281 282 bool BinaryEmitter::emitFunction(BinaryFunction &Function, 283 FunctionFragment &FF) { 284 if (Function.size() == 0 && !Function.hasIslandsInfo()) 285 return false; 286 287 if (Function.getState() == BinaryFunction::State::Empty) 288 return false; 289 290 // Avoid emitting function without instructions when overwriting the original 291 // function in-place. Otherwise, emit the empty function to define the symbol. 292 if (!BC.HasRelocations && !Function.hasNonPseudoInstructions()) 293 return false; 294 295 MCSection *Section = 296 BC.getCodeSection(Function.getCodeSectionName(FF.getFragmentNum())); 297 Streamer.switchSection(Section); 298 Section->setHasInstructions(true); 299 BC.Ctx->addGenDwarfSection(Section); 300 301 if (BC.HasRelocations) { 302 // Set section alignment to at least maximum possible object alignment. 303 // We need this to support LongJmp and other passes that calculates 304 // tentative layout. 305 if (Section->getAlignment() < opts::AlignFunctions) 306 Section->setAlignment(Align(opts::AlignFunctions)); 307 308 Streamer.emitCodeAlignment(BinaryFunction::MinAlign, &*BC.STI); 309 uint16_t MaxAlignBytes = FF.isSplitFragment() 310 ? Function.getMaxColdAlignmentBytes() 311 : Function.getMaxAlignmentBytes(); 312 if (MaxAlignBytes > 0) 313 Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI, 314 MaxAlignBytes); 315 } else { 316 Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI); 317 } 318 319 MCContext &Context = Streamer.getContext(); 320 const MCAsmInfo *MAI = Context.getAsmInfo(); 321 322 MCSymbol *const StartSymbol = Function.getSymbol(FF.getFragmentNum()); 323 324 // Emit all symbols associated with the main function entry. 325 if (FF.isMainFragment()) { 326 for (MCSymbol *Symbol : Function.getSymbols()) { 327 Streamer.emitSymbolAttribute(Symbol, MCSA_ELF_TypeFunction); 328 Streamer.emitLabel(Symbol); 329 } 330 } else { 331 Streamer.emitSymbolAttribute(StartSymbol, MCSA_ELF_TypeFunction); 332 Streamer.emitLabel(StartSymbol); 333 } 334 335 // Emit CFI start 336 if (Function.hasCFI()) { 337 Streamer.emitCFIStartProc(/*IsSimple=*/false); 338 if (Function.getPersonalityFunction() != nullptr) 339 Streamer.emitCFIPersonality(Function.getPersonalityFunction(), 340 Function.getPersonalityEncoding()); 341 MCSymbol *LSDASymbol = Function.getLSDASymbol(FF.getFragmentNum()); 342 if (LSDASymbol) 343 Streamer.emitCFILsda(LSDASymbol, BC.LSDAEncoding); 344 else 345 Streamer.emitCFILsda(0, dwarf::DW_EH_PE_omit); 346 // Emit CFI instructions relative to the CIE 347 for (const MCCFIInstruction &CFIInstr : Function.cie()) { 348 // Only write CIE CFI insns that LLVM will not already emit 349 const std::vector<MCCFIInstruction> &FrameInstrs = 350 MAI->getInitialFrameState(); 351 if (!llvm::is_contained(FrameInstrs, CFIInstr)) 352 emitCFIInstruction(CFIInstr); 353 } 354 } 355 356 assert((Function.empty() || !(*Function.begin()).isCold()) && 357 "first basic block should never be cold"); 358 359 // Emit UD2 at the beginning if requested by user. 360 if (!opts::BreakFunctionNames.empty()) { 361 for (std::string &Name : opts::BreakFunctionNames) { 362 if (Function.hasNameRegex(Name)) { 363 Streamer.emitIntValue(0x0B0F, 2); // UD2: 0F 0B 364 break; 365 } 366 } 367 } 368 369 // Emit code. 370 emitFunctionBody(Function, FF, /*EmitCodeOnly=*/false); 371 372 // Emit padding if requested. 373 if (size_t Padding = opts::padFunction(Function)) { 374 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: padding function " << Function << " with " 375 << Padding << " bytes\n"); 376 Streamer.emitFill(Padding, MAI->getTextAlignFillValue()); 377 } 378 379 if (opts::MarkFuncs) 380 Streamer.emitIntValue(BC.MIB->getTrapFillValue(), 1); 381 382 // Emit CFI end 383 if (Function.hasCFI()) 384 Streamer.emitCFIEndProc(); 385 386 MCSymbol *EndSymbol = Function.getFunctionEndLabel(FF.getFragmentNum()); 387 Streamer.emitLabel(EndSymbol); 388 389 if (MAI->hasDotTypeDotSizeDirective()) { 390 const MCExpr *SizeExpr = MCBinaryExpr::createSub( 391 MCSymbolRefExpr::create(EndSymbol, Context), 392 MCSymbolRefExpr::create(StartSymbol, Context), Context); 393 Streamer.emitELFSize(StartSymbol, SizeExpr); 394 } 395 396 if (opts::UpdateDebugSections && Function.getDWARFUnit()) 397 emitLineInfoEnd(Function, EndSymbol); 398 399 // Exception handling info for the function. 400 emitLSDA(Function, FF); 401 402 if (FF.isMainFragment() && opts::JumpTables > JTS_NONE) 403 emitJumpTables(Function); 404 405 return true; 406 } 407 408 void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF, 409 bool EmitCodeOnly) { 410 if (!EmitCodeOnly && FF.isSplitFragment() && BF.hasConstantIsland()) { 411 assert(BF.getLayout().isHotColdSplit() && 412 "Constant island support only with hot/cold split"); 413 BF.duplicateConstantIslands(); 414 } 415 416 if (!FF.empty() && FF.front()->isLandingPad()) { 417 assert(!FF.front()->isEntryPoint() && 418 "Landing pad cannot be entry point of function"); 419 // If the first block of the fragment is a landing pad, it's offset from the 420 // start of the area that the corresponding LSDA describes is zero. In this 421 // case, the call site entries in that LSDA have 0 as offset to the landing 422 // pad, which the runtime interprets as "no handler". To prevent this, 423 // insert some padding. 424 Streamer.emitIntValue(BC.MIB->getTrapFillValue(), 1); 425 } 426 427 // Track the first emitted instruction with debug info. 428 bool FirstInstr = true; 429 for (BinaryBasicBlock *const BB : FF) { 430 if ((opts::AlignBlocks || opts::PreserveBlocksAlignment) && 431 BB->getAlignment() > 1) 432 Streamer.emitCodeAlignment(BB->getAlignment(), &*BC.STI, 433 BB->getAlignmentMaxBytes()); 434 Streamer.emitLabel(BB->getLabel()); 435 if (!EmitCodeOnly) { 436 if (MCSymbol *EntrySymbol = BF.getSecondaryEntryPointSymbol(*BB)) 437 Streamer.emitLabel(EntrySymbol); 438 } 439 440 // Check if special alignment for macro-fusion is needed. 441 bool MayNeedMacroFusionAlignment = 442 (opts::AlignMacroOpFusion == MFT_ALL) || 443 (opts::AlignMacroOpFusion == MFT_HOT && BB->getKnownExecutionCount()); 444 BinaryBasicBlock::const_iterator MacroFusionPair; 445 if (MayNeedMacroFusionAlignment) { 446 MacroFusionPair = BB->getMacroOpFusionPair(); 447 if (MacroFusionPair == BB->end()) 448 MayNeedMacroFusionAlignment = false; 449 } 450 451 SMLoc LastLocSeen; 452 // Remember if the last instruction emitted was a prefix. 453 bool LastIsPrefix = false; 454 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 455 MCInst &Instr = *I; 456 457 if (EmitCodeOnly && BC.MIB->isPseudo(Instr)) 458 continue; 459 460 // Handle pseudo instructions. 461 if (BC.MIB->isEHLabel(Instr)) { 462 const MCSymbol *Label = BC.MIB->getTargetSymbol(Instr); 463 assert(Instr.getNumOperands() >= 1 && Label && 464 "bad EH_LABEL instruction"); 465 Streamer.emitLabel(const_cast<MCSymbol *>(Label)); 466 continue; 467 } 468 if (BC.MIB->isCFI(Instr)) { 469 emitCFIInstruction(*BF.getCFIFor(Instr)); 470 continue; 471 } 472 473 // Handle macro-fusion alignment. If we emitted a prefix as 474 // the last instruction, we should've already emitted the associated 475 // alignment hint, so don't emit it twice. 476 if (MayNeedMacroFusionAlignment && !LastIsPrefix && 477 I == MacroFusionPair) { 478 // This assumes the second instruction in the macro-op pair will get 479 // assigned to its own MCRelaxableFragment. Since all JCC instructions 480 // are relaxable, we should be safe. 481 } 482 483 if (!EmitCodeOnly && opts::UpdateDebugSections && BF.getDWARFUnit()) { 484 LastLocSeen = emitLineInfo(BF, Instr.getLoc(), LastLocSeen, FirstInstr); 485 FirstInstr = false; 486 } 487 488 // Prepare to tag this location with a label if we need to keep track of 489 // the location of calls/returns for BOLT address translation maps 490 if (!EmitCodeOnly && BF.requiresAddressTranslation() && 491 BC.MIB->getOffset(Instr)) { 492 const uint32_t Offset = *BC.MIB->getOffset(Instr); 493 MCSymbol *LocSym = BC.Ctx->createTempSymbol(); 494 Streamer.emitLabel(LocSym); 495 BB->getLocSyms().emplace_back(Offset, LocSym); 496 } 497 498 Streamer.emitInstruction(Instr, *BC.STI); 499 LastIsPrefix = BC.MIB->isPrefix(Instr); 500 } 501 } 502 503 if (!EmitCodeOnly) 504 emitConstantIslands(BF, FF.isSplitFragment()); 505 } 506 507 void BinaryEmitter::emitConstantIslands(BinaryFunction &BF, bool EmitColdPart, 508 BinaryFunction *OnBehalfOf) { 509 if (!BF.hasIslandsInfo()) 510 return; 511 512 BinaryFunction::IslandInfo &Islands = BF.getIslandInfo(); 513 if (Islands.DataOffsets.empty() && Islands.Dependency.empty()) 514 return; 515 516 // AArch64 requires CI to be aligned to 8 bytes due to access instructions 517 // restrictions. E.g. the ldr with imm, where imm must be aligned to 8 bytes. 518 const uint16_t Alignment = OnBehalfOf 519 ? OnBehalfOf->getConstantIslandAlignment() 520 : BF.getConstantIslandAlignment(); 521 Streamer.emitCodeAlignment(Alignment, &*BC.STI); 522 523 if (!OnBehalfOf) { 524 if (!EmitColdPart) 525 Streamer.emitLabel(BF.getFunctionConstantIslandLabel()); 526 else 527 Streamer.emitLabel(BF.getFunctionColdConstantIslandLabel()); 528 } 529 530 assert((!OnBehalfOf || Islands.Proxies[OnBehalfOf].size() > 0) && 531 "spurious OnBehalfOf constant island emission"); 532 533 assert(!BF.isInjected() && 534 "injected functions should not have constant islands"); 535 // Raw contents of the function. 536 StringRef SectionContents = BF.getOriginSection()->getContents(); 537 538 // Raw contents of the function. 539 StringRef FunctionContents = SectionContents.substr( 540 BF.getAddress() - BF.getOriginSection()->getAddress(), BF.getMaxSize()); 541 542 if (opts::Verbosity && !OnBehalfOf) 543 outs() << "BOLT-INFO: emitting constant island for function " << BF << "\n"; 544 545 // We split the island into smaller blocks and output labels between them. 546 auto IS = Islands.Offsets.begin(); 547 for (auto DataIter = Islands.DataOffsets.begin(); 548 DataIter != Islands.DataOffsets.end(); ++DataIter) { 549 uint64_t FunctionOffset = *DataIter; 550 uint64_t EndOffset = 0ULL; 551 552 // Determine size of this data chunk 553 auto NextData = std::next(DataIter); 554 auto CodeIter = Islands.CodeOffsets.lower_bound(*DataIter); 555 if (CodeIter == Islands.CodeOffsets.end() && 556 NextData == Islands.DataOffsets.end()) 557 EndOffset = BF.getMaxSize(); 558 else if (CodeIter == Islands.CodeOffsets.end()) 559 EndOffset = *NextData; 560 else if (NextData == Islands.DataOffsets.end()) 561 EndOffset = *CodeIter; 562 else 563 EndOffset = (*CodeIter > *NextData) ? *NextData : *CodeIter; 564 565 if (FunctionOffset == EndOffset) 566 continue; // Size is zero, nothing to emit 567 568 auto emitCI = [&](uint64_t &FunctionOffset, uint64_t EndOffset) { 569 if (FunctionOffset >= EndOffset) 570 return; 571 572 for (auto It = Islands.Relocations.lower_bound(FunctionOffset); 573 It != Islands.Relocations.end(); ++It) { 574 if (It->first >= EndOffset) 575 break; 576 577 const Relocation &Relocation = It->second; 578 if (FunctionOffset < Relocation.Offset) { 579 Streamer.emitBytes( 580 FunctionContents.slice(FunctionOffset, Relocation.Offset)); 581 FunctionOffset = Relocation.Offset; 582 } 583 584 LLVM_DEBUG( 585 dbgs() << "BOLT-DEBUG: emitting constant island relocation" 586 << " for " << BF << " at offset 0x" 587 << Twine::utohexstr(Relocation.Offset) << " with size " 588 << Relocation::getSizeForType(Relocation.Type) << '\n'); 589 590 FunctionOffset += Relocation.emit(&Streamer); 591 } 592 593 assert(FunctionOffset <= EndOffset && "overflow error"); 594 if (FunctionOffset < EndOffset) { 595 Streamer.emitBytes(FunctionContents.slice(FunctionOffset, EndOffset)); 596 FunctionOffset = EndOffset; 597 } 598 }; 599 600 // Emit labels, relocs and data 601 while (IS != Islands.Offsets.end() && IS->first < EndOffset) { 602 auto NextLabelOffset = 603 IS == Islands.Offsets.end() ? EndOffset : IS->first; 604 auto NextStop = std::min(NextLabelOffset, EndOffset); 605 assert(NextStop <= EndOffset && "internal overflow error"); 606 emitCI(FunctionOffset, NextStop); 607 if (IS != Islands.Offsets.end() && FunctionOffset == IS->first) { 608 // This is a slightly complex code to decide which label to emit. We 609 // have 4 cases to handle: regular symbol, cold symbol, regular or cold 610 // symbol being emitted on behalf of an external function. 611 if (!OnBehalfOf) { 612 if (!EmitColdPart) { 613 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " 614 << IS->second->getName() << " at offset 0x" 615 << Twine::utohexstr(IS->first) << '\n'); 616 if (IS->second->isUndefined()) 617 Streamer.emitLabel(IS->second); 618 else 619 assert(BF.hasName(std::string(IS->second->getName()))); 620 } else if (Islands.ColdSymbols.count(IS->second) != 0) { 621 LLVM_DEBUG(dbgs() 622 << "BOLT-DEBUG: emitted label " 623 << Islands.ColdSymbols[IS->second]->getName() << '\n'); 624 if (Islands.ColdSymbols[IS->second]->isUndefined()) 625 Streamer.emitLabel(Islands.ColdSymbols[IS->second]); 626 } 627 } else { 628 if (!EmitColdPart) { 629 if (MCSymbol *Sym = Islands.Proxies[OnBehalfOf][IS->second]) { 630 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " 631 << Sym->getName() << '\n'); 632 Streamer.emitLabel(Sym); 633 } 634 } else if (MCSymbol *Sym = 635 Islands.ColdProxies[OnBehalfOf][IS->second]) { 636 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " << Sym->getName() 637 << '\n'); 638 Streamer.emitLabel(Sym); 639 } 640 } 641 ++IS; 642 } 643 } 644 assert(FunctionOffset <= EndOffset && "overflow error"); 645 emitCI(FunctionOffset, EndOffset); 646 } 647 assert(IS == Islands.Offsets.end() && "some symbols were not emitted!"); 648 649 if (OnBehalfOf) 650 return; 651 // Now emit constant islands from other functions that we may have used in 652 // this function. 653 for (BinaryFunction *ExternalFunc : Islands.Dependency) 654 emitConstantIslands(*ExternalFunc, EmitColdPart, &BF); 655 } 656 657 SMLoc BinaryEmitter::emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, 658 SMLoc PrevLoc, bool FirstInstr) { 659 DWARFUnit *FunctionCU = BF.getDWARFUnit(); 660 const DWARFDebugLine::LineTable *FunctionLineTable = BF.getDWARFLineTable(); 661 assert(FunctionCU && "cannot emit line info for function without CU"); 662 663 DebugLineTableRowRef RowReference = DebugLineTableRowRef::fromSMLoc(NewLoc); 664 665 // Check if no new line info needs to be emitted. 666 if (RowReference == DebugLineTableRowRef::NULL_ROW || 667 NewLoc.getPointer() == PrevLoc.getPointer()) 668 return PrevLoc; 669 670 unsigned CurrentFilenum = 0; 671 const DWARFDebugLine::LineTable *CurrentLineTable = FunctionLineTable; 672 673 // If the CU id from the current instruction location does not 674 // match the CU id from the current function, it means that we 675 // have come across some inlined code. We must look up the CU 676 // for the instruction's original function and get the line table 677 // from that. 678 const uint64_t FunctionUnitIndex = FunctionCU->getOffset(); 679 const uint32_t CurrentUnitIndex = RowReference.DwCompileUnitIndex; 680 if (CurrentUnitIndex != FunctionUnitIndex) { 681 CurrentLineTable = BC.DwCtx->getLineTableForUnit( 682 BC.DwCtx->getCompileUnitForOffset(CurrentUnitIndex)); 683 // Add filename from the inlined function to the current CU. 684 CurrentFilenum = BC.addDebugFilenameToUnit( 685 FunctionUnitIndex, CurrentUnitIndex, 686 CurrentLineTable->Rows[RowReference.RowIndex - 1].File); 687 } 688 689 const DWARFDebugLine::Row &CurrentRow = 690 CurrentLineTable->Rows[RowReference.RowIndex - 1]; 691 if (!CurrentFilenum) 692 CurrentFilenum = CurrentRow.File; 693 694 unsigned Flags = (DWARF2_FLAG_IS_STMT * CurrentRow.IsStmt) | 695 (DWARF2_FLAG_BASIC_BLOCK * CurrentRow.BasicBlock) | 696 (DWARF2_FLAG_PROLOGUE_END * CurrentRow.PrologueEnd) | 697 (DWARF2_FLAG_EPILOGUE_BEGIN * CurrentRow.EpilogueBegin); 698 699 // Always emit is_stmt at the beginning of function fragment. 700 if (FirstInstr) 701 Flags |= DWARF2_FLAG_IS_STMT; 702 703 BC.Ctx->setCurrentDwarfLoc(CurrentFilenum, CurrentRow.Line, CurrentRow.Column, 704 Flags, CurrentRow.Isa, CurrentRow.Discriminator); 705 const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc(); 706 BC.Ctx->clearDwarfLocSeen(); 707 708 MCSymbol *LineSym = BC.Ctx->createTempSymbol(); 709 Streamer.emitLabel(LineSym); 710 711 BC.getDwarfLineTable(FunctionUnitIndex) 712 .getMCLineSections() 713 .addLineEntry(MCDwarfLineEntry(LineSym, DwarfLoc), 714 Streamer.getCurrentSectionOnly()); 715 716 return NewLoc; 717 } 718 719 void BinaryEmitter::emitLineInfoEnd(const BinaryFunction &BF, 720 MCSymbol *FunctionEndLabel) { 721 DWARFUnit *FunctionCU = BF.getDWARFUnit(); 722 assert(FunctionCU && "DWARF unit expected"); 723 BC.Ctx->setCurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_END_SEQUENCE, 0, 0); 724 const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc(); 725 BC.Ctx->clearDwarfLocSeen(); 726 BC.getDwarfLineTable(FunctionCU->getOffset()) 727 .getMCLineSections() 728 .addLineEntry(MCDwarfLineEntry(FunctionEndLabel, DwarfLoc), 729 Streamer.getCurrentSectionOnly()); 730 } 731 732 void BinaryEmitter::emitJumpTables(const BinaryFunction &BF) { 733 MCSection *ReadOnlySection = BC.MOFI->getReadOnlySection(); 734 MCSection *ReadOnlyColdSection = BC.MOFI->getContext().getELFSection( 735 ".rodata.cold", ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 736 737 if (!BF.hasJumpTables()) 738 return; 739 740 if (opts::PrintJumpTables) 741 outs() << "BOLT-INFO: jump tables for function " << BF << ":\n"; 742 743 for (auto &JTI : BF.jumpTables()) { 744 JumpTable &JT = *JTI.second; 745 if (opts::PrintJumpTables) 746 JT.print(outs()); 747 if ((opts::JumpTables == JTS_BASIC || !BF.isSimple()) && 748 BC.HasRelocations) { 749 JT.updateOriginal(); 750 } else { 751 MCSection *HotSection, *ColdSection; 752 if (opts::JumpTables == JTS_BASIC) { 753 // In non-relocation mode we have to emit jump tables in local sections. 754 // This way we only overwrite them when the corresponding function is 755 // overwritten. 756 std::string Name = ".local." + JT.Labels[0]->getName().str(); 757 std::replace(Name.begin(), Name.end(), '/', '.'); 758 BinarySection &Section = 759 BC.registerOrUpdateSection(Name, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 760 Section.setAnonymous(true); 761 JT.setOutputSection(Section); 762 HotSection = BC.getDataSection(Name); 763 ColdSection = HotSection; 764 } else { 765 if (BF.isSimple()) { 766 HotSection = ReadOnlySection; 767 ColdSection = ReadOnlyColdSection; 768 } else { 769 HotSection = BF.hasProfile() ? ReadOnlySection : ReadOnlyColdSection; 770 ColdSection = HotSection; 771 } 772 } 773 emitJumpTable(JT, HotSection, ColdSection); 774 } 775 } 776 } 777 778 void BinaryEmitter::emitJumpTable(const JumpTable &JT, MCSection *HotSection, 779 MCSection *ColdSection) { 780 // Pre-process entries for aggressive splitting. 781 // Each label represents a separate switch table and gets its own count 782 // determining its destination. 783 std::map<MCSymbol *, uint64_t> LabelCounts; 784 if (opts::JumpTables > JTS_SPLIT && !JT.Counts.empty()) { 785 MCSymbol *CurrentLabel = JT.Labels.at(0); 786 uint64_t CurrentLabelCount = 0; 787 for (unsigned Index = 0; Index < JT.Entries.size(); ++Index) { 788 auto LI = JT.Labels.find(Index * JT.EntrySize); 789 if (LI != JT.Labels.end()) { 790 LabelCounts[CurrentLabel] = CurrentLabelCount; 791 CurrentLabel = LI->second; 792 CurrentLabelCount = 0; 793 } 794 CurrentLabelCount += JT.Counts[Index].Count; 795 } 796 LabelCounts[CurrentLabel] = CurrentLabelCount; 797 } else { 798 Streamer.switchSection(JT.Count > 0 ? HotSection : ColdSection); 799 Streamer.emitValueToAlignment(JT.EntrySize); 800 } 801 MCSymbol *LastLabel = nullptr; 802 uint64_t Offset = 0; 803 for (MCSymbol *Entry : JT.Entries) { 804 auto LI = JT.Labels.find(Offset); 805 if (LI != JT.Labels.end()) { 806 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitting jump table " 807 << LI->second->getName() 808 << " (originally was at address 0x" 809 << Twine::utohexstr(JT.getAddress() + Offset) 810 << (Offset ? "as part of larger jump table\n" : "\n")); 811 if (!LabelCounts.empty()) { 812 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump table count: " 813 << LabelCounts[LI->second] << '\n'); 814 if (LabelCounts[LI->second] > 0) 815 Streamer.switchSection(HotSection); 816 else 817 Streamer.switchSection(ColdSection); 818 Streamer.emitValueToAlignment(JT.EntrySize); 819 } 820 Streamer.emitLabel(LI->second); 821 LastLabel = LI->second; 822 } 823 if (JT.Type == JumpTable::JTT_NORMAL) { 824 Streamer.emitSymbolValue(Entry, JT.OutputEntrySize); 825 } else { // JTT_PIC 826 const MCSymbolRefExpr *JTExpr = 827 MCSymbolRefExpr::create(LastLabel, Streamer.getContext()); 828 const MCSymbolRefExpr *E = 829 MCSymbolRefExpr::create(Entry, Streamer.getContext()); 830 const MCBinaryExpr *Value = 831 MCBinaryExpr::createSub(E, JTExpr, Streamer.getContext()); 832 Streamer.emitValue(Value, JT.EntrySize); 833 } 834 Offset += JT.EntrySize; 835 } 836 } 837 838 void BinaryEmitter::emitCFIInstruction(const MCCFIInstruction &Inst) const { 839 switch (Inst.getOperation()) { 840 default: 841 llvm_unreachable("Unexpected instruction"); 842 case MCCFIInstruction::OpDefCfaOffset: 843 Streamer.emitCFIDefCfaOffset(Inst.getOffset()); 844 break; 845 case MCCFIInstruction::OpAdjustCfaOffset: 846 Streamer.emitCFIAdjustCfaOffset(Inst.getOffset()); 847 break; 848 case MCCFIInstruction::OpDefCfa: 849 Streamer.emitCFIDefCfa(Inst.getRegister(), Inst.getOffset()); 850 break; 851 case MCCFIInstruction::OpDefCfaRegister: 852 Streamer.emitCFIDefCfaRegister(Inst.getRegister()); 853 break; 854 case MCCFIInstruction::OpOffset: 855 Streamer.emitCFIOffset(Inst.getRegister(), Inst.getOffset()); 856 break; 857 case MCCFIInstruction::OpRegister: 858 Streamer.emitCFIRegister(Inst.getRegister(), Inst.getRegister2()); 859 break; 860 case MCCFIInstruction::OpWindowSave: 861 Streamer.emitCFIWindowSave(); 862 break; 863 case MCCFIInstruction::OpNegateRAState: 864 Streamer.emitCFINegateRAState(); 865 break; 866 case MCCFIInstruction::OpSameValue: 867 Streamer.emitCFISameValue(Inst.getRegister()); 868 break; 869 case MCCFIInstruction::OpGnuArgsSize: 870 Streamer.emitCFIGnuArgsSize(Inst.getOffset()); 871 break; 872 case MCCFIInstruction::OpEscape: 873 Streamer.AddComment(Inst.getComment()); 874 Streamer.emitCFIEscape(Inst.getValues()); 875 break; 876 case MCCFIInstruction::OpRestore: 877 Streamer.emitCFIRestore(Inst.getRegister()); 878 break; 879 case MCCFIInstruction::OpUndefined: 880 Streamer.emitCFIUndefined(Inst.getRegister()); 881 break; 882 } 883 } 884 885 // The code is based on EHStreamer::emitExceptionTable(). 886 void BinaryEmitter::emitLSDA(BinaryFunction &BF, const FunctionFragment &FF) { 887 const BinaryFunction::CallSitesRange Sites = 888 BF.getCallSites(FF.getFragmentNum()); 889 if (llvm::empty(Sites)) 890 return; 891 892 // Calculate callsite table size. Size of each callsite entry is: 893 // 894 // sizeof(start) + sizeof(length) + sizeof(LP) + sizeof(uleb128(action)) 895 // 896 // or 897 // 898 // sizeof(dwarf::DW_EH_PE_data4) * 3 + sizeof(uleb128(action)) 899 uint64_t CallSiteTableLength = llvm::size(Sites) * 4 * 3; 900 for (const auto &FragmentCallSite : Sites) 901 CallSiteTableLength += getULEB128Size(FragmentCallSite.second.Action); 902 903 Streamer.switchSection(BC.MOFI->getLSDASection()); 904 905 const unsigned TTypeEncoding = BF.getLSDATypeEncoding(); 906 const unsigned TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding); 907 const uint16_t TTypeAlignment = 4; 908 909 // Type tables have to be aligned at 4 bytes. 910 Streamer.emitValueToAlignment(TTypeAlignment); 911 912 // Emit the LSDA label. 913 MCSymbol *LSDASymbol = BF.getLSDASymbol(FF.getFragmentNum()); 914 assert(LSDASymbol && "no LSDA symbol set"); 915 Streamer.emitLabel(LSDASymbol); 916 917 // Corresponding FDE start. 918 const MCSymbol *StartSymbol = BF.getSymbol(FF.getFragmentNum()); 919 920 // Emit the LSDA header. 921 922 // If LPStart is omitted, then the start of the FDE is used as a base for 923 // landing pad displacements. Then if a cold fragment starts with 924 // a landing pad, this means that the first landing pad offset will be 0. 925 // As a result, the exception handling runtime will ignore this landing pad 926 // because zero offset denotes the absence of a landing pad. 927 // For this reason, when the binary has fixed starting address we emit LPStart 928 // as 0 and output the absolute value of the landing pad in the table. 929 // 930 // If the base address can change, we cannot use absolute addresses for 931 // landing pads (at least not without runtime relocations). Hence, we fall 932 // back to emitting landing pads relative to the FDE start. 933 // As we are emitting label differences, we have to guarantee both labels are 934 // defined in the same section and hence cannot place the landing pad into a 935 // cold fragment when the corresponding call site is in the hot fragment. 936 // Because of this issue and the previously described issue of possible 937 // zero-offset landing pad we have to place landing pads in the same section 938 // as the corresponding invokes for shared objects. 939 std::function<void(const MCSymbol *)> emitLandingPad; 940 if (BC.HasFixedLoadAddress) { 941 Streamer.emitIntValue(dwarf::DW_EH_PE_udata4, 1); // LPStart format 942 Streamer.emitIntValue(0, 4); // LPStart 943 emitLandingPad = [&](const MCSymbol *LPSymbol) { 944 if (!LPSymbol) 945 Streamer.emitIntValue(0, 4); 946 else 947 Streamer.emitSymbolValue(LPSymbol, 4); 948 }; 949 } else { 950 Streamer.emitIntValue(dwarf::DW_EH_PE_omit, 1); // LPStart format 951 emitLandingPad = [&](const MCSymbol *LPSymbol) { 952 if (!LPSymbol) 953 Streamer.emitIntValue(0, 4); 954 else 955 Streamer.emitAbsoluteSymbolDiff(LPSymbol, StartSymbol, 4); 956 }; 957 } 958 959 Streamer.emitIntValue(TTypeEncoding, 1); // TType format 960 961 // See the comment in EHStreamer::emitExceptionTable() on to use 962 // uleb128 encoding (which can use variable number of bytes to encode the same 963 // value) to ensure type info table is properly aligned at 4 bytes without 964 // iteratively fixing sizes of the tables. 965 unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength); 966 unsigned TTypeBaseOffset = 967 sizeof(int8_t) + // Call site format 968 CallSiteTableLengthSize + // Call site table length size 969 CallSiteTableLength + // Call site table length 970 BF.getLSDAActionTable().size() + // Actions table size 971 BF.getLSDATypeTable().size() * TTypeEncodingSize; // Types table size 972 unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset); 973 unsigned TotalSize = sizeof(int8_t) + // LPStart format 974 sizeof(int8_t) + // TType format 975 TTypeBaseOffsetSize + // TType base offset size 976 TTypeBaseOffset; // TType base offset 977 unsigned SizeAlign = (4 - TotalSize) & 3; 978 979 if (TTypeEncoding != dwarf::DW_EH_PE_omit) 980 // Account for any extra padding that will be added to the call site table 981 // length. 982 Streamer.emitULEB128IntValue(TTypeBaseOffset, 983 /*PadTo=*/TTypeBaseOffsetSize + SizeAlign); 984 985 // Emit the landing pad call site table. We use signed data4 since we can emit 986 // a landing pad in a different part of the split function that could appear 987 // earlier in the address space than LPStart. 988 Streamer.emitIntValue(dwarf::DW_EH_PE_sdata4, 1); 989 Streamer.emitULEB128IntValue(CallSiteTableLength); 990 991 for (const auto &FragmentCallSite : Sites) { 992 const BinaryFunction::CallSite &CallSite = FragmentCallSite.second; 993 const MCSymbol *BeginLabel = CallSite.Start; 994 const MCSymbol *EndLabel = CallSite.End; 995 996 assert(BeginLabel && "start EH label expected"); 997 assert(EndLabel && "end EH label expected"); 998 999 // Start of the range is emitted relative to the start of current 1000 // function split part. 1001 Streamer.emitAbsoluteSymbolDiff(BeginLabel, StartSymbol, 4); 1002 Streamer.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 1003 emitLandingPad(CallSite.LP); 1004 Streamer.emitULEB128IntValue(CallSite.Action); 1005 } 1006 1007 // Write out action, type, and type index tables at the end. 1008 // 1009 // For action and type index tables there's no need to change the original 1010 // table format unless we are doing function splitting, in which case we can 1011 // split and optimize the tables. 1012 // 1013 // For type table we (re-)encode the table using TTypeEncoding matching 1014 // the current assembler mode. 1015 for (uint8_t const &Byte : BF.getLSDAActionTable()) 1016 Streamer.emitIntValue(Byte, 1); 1017 1018 const BinaryFunction::LSDATypeTableTy &TypeTable = 1019 (TTypeEncoding & dwarf::DW_EH_PE_indirect) ? BF.getLSDATypeAddressTable() 1020 : BF.getLSDATypeTable(); 1021 assert(TypeTable.size() == BF.getLSDATypeTable().size() && 1022 "indirect type table size mismatch"); 1023 1024 for (int Index = TypeTable.size() - 1; Index >= 0; --Index) { 1025 const uint64_t TypeAddress = TypeTable[Index]; 1026 switch (TTypeEncoding & 0x70) { 1027 default: 1028 llvm_unreachable("unsupported TTypeEncoding"); 1029 case dwarf::DW_EH_PE_absptr: 1030 Streamer.emitIntValue(TypeAddress, TTypeEncodingSize); 1031 break; 1032 case dwarf::DW_EH_PE_pcrel: { 1033 if (TypeAddress) { 1034 const MCSymbol *TypeSymbol = 1035 BC.getOrCreateGlobalSymbol(TypeAddress, "TI", 0, TTypeAlignment); 1036 MCSymbol *DotSymbol = BC.Ctx->createNamedTempSymbol(); 1037 Streamer.emitLabel(DotSymbol); 1038 const MCBinaryExpr *SubDotExpr = MCBinaryExpr::createSub( 1039 MCSymbolRefExpr::create(TypeSymbol, *BC.Ctx), 1040 MCSymbolRefExpr::create(DotSymbol, *BC.Ctx), *BC.Ctx); 1041 Streamer.emitValue(SubDotExpr, TTypeEncodingSize); 1042 } else { 1043 Streamer.emitIntValue(0, TTypeEncodingSize); 1044 } 1045 break; 1046 } 1047 } 1048 } 1049 for (uint8_t const &Byte : BF.getLSDATypeIndexTable()) 1050 Streamer.emitIntValue(Byte, 1); 1051 } 1052 1053 void BinaryEmitter::emitDebugLineInfoForOriginalFunctions() { 1054 // If a function is in a CU containing at least one processed function, we 1055 // have to rewrite the whole line table for that CU. For unprocessed functions 1056 // we use data from the input line table. 1057 for (auto &It : BC.getBinaryFunctions()) { 1058 const BinaryFunction &Function = It.second; 1059 1060 // If the function was emitted, its line info was emitted with it. 1061 if (Function.isEmitted()) 1062 continue; 1063 1064 const DWARFDebugLine::LineTable *LineTable = Function.getDWARFLineTable(); 1065 if (!LineTable) 1066 continue; // nothing to update for this function 1067 1068 const uint64_t Address = Function.getAddress(); 1069 std::vector<uint32_t> Results; 1070 if (!LineTable->lookupAddressRange( 1071 {Address, object::SectionedAddress::UndefSection}, 1072 Function.getSize(), Results)) 1073 continue; 1074 1075 if (Results.empty()) 1076 continue; 1077 1078 // The first row returned could be the last row matching the start address. 1079 // Find the first row with the same address that is not the end of the 1080 // sequence. 1081 uint64_t FirstRow = Results.front(); 1082 while (FirstRow > 0) { 1083 const DWARFDebugLine::Row &PrevRow = LineTable->Rows[FirstRow - 1]; 1084 if (PrevRow.Address.Address != Address || PrevRow.EndSequence) 1085 break; 1086 --FirstRow; 1087 } 1088 1089 const uint64_t EndOfSequenceAddress = 1090 Function.getAddress() + Function.getMaxSize(); 1091 BC.getDwarfLineTable(Function.getDWARFUnit()->getOffset()) 1092 .addLineTableSequence(LineTable, FirstRow, Results.back(), 1093 EndOfSequenceAddress); 1094 } 1095 1096 // For units that are completely unprocessed, use original debug line contents 1097 // eliminating the need to regenerate line info program. 1098 emitDebugLineInfoForUnprocessedCUs(); 1099 } 1100 1101 void BinaryEmitter::emitDebugLineInfoForUnprocessedCUs() { 1102 // Sorted list of section offsets provides boundaries for section fragments, 1103 // where each fragment is the unit's contribution to debug line section. 1104 std::vector<uint64_t> StmtListOffsets; 1105 StmtListOffsets.reserve(BC.DwCtx->getNumCompileUnits()); 1106 for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) { 1107 DWARFDie CUDie = CU->getUnitDIE(); 1108 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list)); 1109 if (!StmtList) 1110 continue; 1111 1112 StmtListOffsets.push_back(*StmtList); 1113 } 1114 llvm::sort(StmtListOffsets); 1115 1116 // For each CU that was not processed, emit its line info as a binary blob. 1117 for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) { 1118 if (BC.ProcessedCUs.count(CU.get())) 1119 continue; 1120 1121 DWARFDie CUDie = CU->getUnitDIE(); 1122 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list)); 1123 if (!StmtList) 1124 continue; 1125 1126 StringRef DebugLineContents = CU->getLineSection().Data; 1127 1128 const uint64_t Begin = *StmtList; 1129 1130 // Statement list ends where the next unit contribution begins, or at the 1131 // end of the section. 1132 auto It = llvm::upper_bound(StmtListOffsets, Begin); 1133 const uint64_t End = 1134 It == StmtListOffsets.end() ? DebugLineContents.size() : *It; 1135 1136 BC.getDwarfLineTable(CU->getOffset()) 1137 .addRawContents(DebugLineContents.slice(Begin, End)); 1138 } 1139 } 1140 1141 void BinaryEmitter::emitDataSections(StringRef OrgSecPrefix) { 1142 for (BinarySection &Section : BC.sections()) { 1143 if (!Section.hasRelocations() || !Section.hasSectionRef()) 1144 continue; 1145 1146 StringRef SectionName = Section.getName(); 1147 std::string EmitName = Section.isReordered() 1148 ? std::string(Section.getOutputName()) 1149 : OrgSecPrefix.str() + std::string(SectionName); 1150 Section.emitAsData(Streamer, EmitName); 1151 Section.clearRelocations(); 1152 } 1153 } 1154 1155 namespace llvm { 1156 namespace bolt { 1157 1158 void emitBinaryContext(MCStreamer &Streamer, BinaryContext &BC, 1159 StringRef OrgSecPrefix) { 1160 BinaryEmitter(Streamer, BC).emitAll(OrgSecPrefix); 1161 } 1162 1163 void emitFunctionBody(MCStreamer &Streamer, BinaryFunction &BF, 1164 FunctionFragment &FF, bool EmitCodeOnly) { 1165 BinaryEmitter(Streamer, BF.getBinaryContext()) 1166 .emitFunctionBody(BF, FF, EmitCodeOnly); 1167 } 1168 1169 } // namespace bolt 1170 } // namespace llvm 1171