1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===// 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 AsmPrinter class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/AsmPrinter.h" 14 #include "CodeViewDebug.h" 15 #include "DwarfDebug.h" 16 #include "DwarfException.h" 17 #include "WasmException.h" 18 #include "WinCFGuard.h" 19 #include "WinException.h" 20 #include "llvm/ADT/APFloat.h" 21 #include "llvm/ADT/APInt.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 34 #include "llvm/Analysis/ProfileSummaryInfo.h" 35 #include "llvm/BinaryFormat/COFF.h" 36 #include "llvm/BinaryFormat/Dwarf.h" 37 #include "llvm/BinaryFormat/ELF.h" 38 #include "llvm/CodeGen/GCMetadata.h" 39 #include "llvm/CodeGen/GCMetadataPrinter.h" 40 #include "llvm/CodeGen/GCStrategy.h" 41 #include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 44 #include "llvm/CodeGen/MachineConstantPool.h" 45 #include "llvm/CodeGen/MachineDominators.h" 46 #include "llvm/CodeGen/MachineFrameInfo.h" 47 #include "llvm/CodeGen/MachineFunction.h" 48 #include "llvm/CodeGen/MachineFunctionPass.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBundle.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineLoopInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineModuleInfo.h" 55 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 56 #include "llvm/CodeGen/MachineOperand.h" 57 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 58 #include "llvm/CodeGen/MachineSizeOpts.h" 59 #include "llvm/CodeGen/StackMaps.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/Comdat.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalIFunc.h" 75 #include "llvm/IR/GlobalIndirectSymbol.h" 76 #include "llvm/IR/GlobalObject.h" 77 #include "llvm/IR/GlobalValue.h" 78 #include "llvm/IR/GlobalVariable.h" 79 #include "llvm/IR/Instruction.h" 80 #include "llvm/IR/Mangler.h" 81 #include "llvm/IR/Metadata.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/RemarkStreamer.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCAsmInfo.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/MC/MCDirectives.h" 90 #include "llvm/MC/MCDwarf.h" 91 #include "llvm/MC/MCExpr.h" 92 #include "llvm/MC/MCInst.h" 93 #include "llvm/MC/MCSection.h" 94 #include "llvm/MC/MCSectionCOFF.h" 95 #include "llvm/MC/MCSectionELF.h" 96 #include "llvm/MC/MCSectionMachO.h" 97 #include "llvm/MC/MCSectionXCOFF.h" 98 #include "llvm/MC/MCStreamer.h" 99 #include "llvm/MC/MCSubtargetInfo.h" 100 #include "llvm/MC/MCSymbol.h" 101 #include "llvm/MC/MCSymbolELF.h" 102 #include "llvm/MC/MCSymbolXCOFF.h" 103 #include "llvm/MC/MCTargetOptions.h" 104 #include "llvm/MC/MCValue.h" 105 #include "llvm/MC/SectionKind.h" 106 #include "llvm/Pass.h" 107 #include "llvm/Remarks/Remark.h" 108 #include "llvm/Remarks/RemarkFormat.h" 109 #include "llvm/Remarks/RemarkStringTable.h" 110 #include "llvm/Support/Casting.h" 111 #include "llvm/Support/CommandLine.h" 112 #include "llvm/Support/Compiler.h" 113 #include "llvm/Support/ErrorHandling.h" 114 #include "llvm/Support/Format.h" 115 #include "llvm/Support/MathExtras.h" 116 #include "llvm/Support/Path.h" 117 #include "llvm/Support/TargetRegistry.h" 118 #include "llvm/Support/Timer.h" 119 #include "llvm/Support/raw_ostream.h" 120 #include "llvm/Target/TargetLoweringObjectFile.h" 121 #include "llvm/Target/TargetMachine.h" 122 #include "llvm/Target/TargetOptions.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <cinttypes> 126 #include <cstdint> 127 #include <iterator> 128 #include <limits> 129 #include <memory> 130 #include <string> 131 #include <utility> 132 #include <vector> 133 134 using namespace llvm; 135 136 #define DEBUG_TYPE "asm-printer" 137 138 static const char *const DWARFGroupName = "dwarf"; 139 static const char *const DWARFGroupDescription = "DWARF Emission"; 140 static const char *const DbgTimerName = "emit"; 141 static const char *const DbgTimerDescription = "Debug Info Emission"; 142 static const char *const EHTimerName = "write_exception"; 143 static const char *const EHTimerDescription = "DWARF Exception Writer"; 144 static const char *const CFGuardName = "Control Flow Guard"; 145 static const char *const CFGuardDescription = "Control Flow Guard"; 146 static const char *const CodeViewLineTablesGroupName = "linetables"; 147 static const char *const CodeViewLineTablesGroupDescription = 148 "CodeView Line Tables"; 149 150 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 151 152 char AsmPrinter::ID = 0; 153 154 using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>; 155 156 static gcp_map_type &getGCMap(void *&P) { 157 if (!P) 158 P = new gcp_map_type(); 159 return *(gcp_map_type*)P; 160 } 161 162 /// getGVAlignment - Return the alignment to use for the specified global 163 /// value. This rounds up to the preferred alignment if possible and legal. 164 Align AsmPrinter::getGVAlignment(const GlobalValue *GV, const DataLayout &DL, 165 Align InAlign) { 166 Align Alignment; 167 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 168 Alignment = Align(DL.getPreferredAlignment(GVar)); 169 170 // If InAlign is specified, round it to it. 171 if (InAlign > Alignment) 172 Alignment = InAlign; 173 174 // If the GV has a specified alignment, take it into account. 175 const MaybeAlign GVAlign(GV->getAlignment()); 176 if (!GVAlign) 177 return Alignment; 178 179 assert(GVAlign && "GVAlign must be set"); 180 181 // If the GVAlign is larger than NumBits, or if we are required to obey 182 // NumBits because the GV has an assigned section, obey it. 183 if (*GVAlign > Alignment || GV->hasSection()) 184 Alignment = *GVAlign; 185 return Alignment; 186 } 187 188 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 189 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 190 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) { 191 VerboseAsm = OutStreamer->isVerboseAsm(); 192 } 193 194 AsmPrinter::~AsmPrinter() { 195 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 196 197 if (GCMetadataPrinters) { 198 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 199 200 delete &GCMap; 201 GCMetadataPrinters = nullptr; 202 } 203 } 204 205 bool AsmPrinter::isPositionIndependent() const { 206 return TM.isPositionIndependent(); 207 } 208 209 /// getFunctionNumber - Return a unique ID for the current function. 210 unsigned AsmPrinter::getFunctionNumber() const { 211 return MF->getFunctionNumber(); 212 } 213 214 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 215 return *TM.getObjFileLowering(); 216 } 217 218 const DataLayout &AsmPrinter::getDataLayout() const { 219 return MMI->getModule()->getDataLayout(); 220 } 221 222 // Do not use the cached DataLayout because some client use it without a Module 223 // (dsymutil, llvm-dwarfdump). 224 unsigned AsmPrinter::getPointerSize() const { 225 return TM.getPointerSize(0); // FIXME: Default address space 226 } 227 228 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 229 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 230 return MF->getSubtarget<MCSubtargetInfo>(); 231 } 232 233 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 234 S.EmitInstruction(Inst, getSubtargetInfo()); 235 } 236 237 void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) { 238 assert(DD && "Dwarf debug file is not defined."); 239 assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode."); 240 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0); 241 } 242 243 /// getCurrentSection() - Return the current section we are emitting to. 244 const MCSection *AsmPrinter::getCurrentSection() const { 245 return OutStreamer->getCurrentSectionOnly(); 246 } 247 248 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 249 AU.setPreservesAll(); 250 MachineFunctionPass::getAnalysisUsage(AU); 251 AU.addRequired<MachineModuleInfoWrapperPass>(); 252 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 253 AU.addRequired<GCModuleInfo>(); 254 AU.addRequired<LazyMachineBlockFrequencyInfoPass>(); 255 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 256 } 257 258 bool AsmPrinter::doInitialization(Module &M) { 259 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>(); 260 MMI = MMIWP ? &MMIWP->getMMI() : nullptr; 261 262 // Initialize TargetLoweringObjectFile. 263 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 264 .Initialize(OutContext, TM); 265 266 const_cast<TargetLoweringObjectFile &>(getObjFileLowering()) 267 .getModuleMetadata(M); 268 269 OutStreamer->InitSections(false); 270 271 // Emit the version-min deployment target directive if needed. 272 // 273 // FIXME: If we end up with a collection of these sorts of Darwin-specific 274 // or ELF-specific things, it may make sense to have a platform helper class 275 // that will work with the target helper class. For now keep it here, as the 276 // alternative is duplicated code in each of the target asm printers that 277 // use the directive, where it would need the same conditionalization 278 // anyway. 279 const Triple &Target = TM.getTargetTriple(); 280 OutStreamer->EmitVersionForTarget(Target, M.getSDKVersion()); 281 282 // Allow the target to emit any magic that it wants at the start of the file. 283 EmitStartOfAsmFile(M); 284 285 // Very minimal debug info. It is ignored if we emit actual debug info. If we 286 // don't, this at least helps the user find where a global came from. 287 if (MAI->hasSingleParameterDotFile()) { 288 // .file "foo.c" 289 OutStreamer->EmitFileDirective( 290 llvm::sys::path::filename(M.getSourceFileName())); 291 } 292 293 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 294 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 295 for (auto &I : *MI) 296 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 297 MP->beginAssembly(M, *MI, *this); 298 299 // Emit module-level inline asm if it exists. 300 if (!M.getModuleInlineAsm().empty()) { 301 // We're at the module level. Construct MCSubtarget from the default CPU 302 // and target triple. 303 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 304 TM.getTargetTriple().str(), TM.getTargetCPU(), 305 TM.getTargetFeatureString())); 306 OutStreamer->AddComment("Start of file scope inline assembly"); 307 OutStreamer->AddBlankLine(); 308 EmitInlineAsm(M.getModuleInlineAsm()+"\n", 309 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 310 OutStreamer->AddComment("End of file scope inline assembly"); 311 OutStreamer->AddBlankLine(); 312 } 313 314 if (MAI->doesSupportDebugInformation()) { 315 bool EmitCodeView = MMI->getModule()->getCodeViewFlag(); 316 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) { 317 Handlers.emplace_back(std::make_unique<CodeViewDebug>(this), 318 DbgTimerName, DbgTimerDescription, 319 CodeViewLineTablesGroupName, 320 CodeViewLineTablesGroupDescription); 321 } 322 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) { 323 DD = new DwarfDebug(this, &M); 324 DD->beginModule(); 325 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName, 326 DbgTimerDescription, DWARFGroupName, 327 DWARFGroupDescription); 328 } 329 } 330 331 switch (MAI->getExceptionHandlingType()) { 332 case ExceptionHandling::SjLj: 333 case ExceptionHandling::DwarfCFI: 334 case ExceptionHandling::ARM: 335 isCFIMoveForDebugging = true; 336 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 337 break; 338 for (auto &F: M.getFunctionList()) { 339 // If the module contains any function with unwind data, 340 // .eh_frame has to be emitted. 341 // Ignore functions that won't get emitted. 342 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) { 343 isCFIMoveForDebugging = false; 344 break; 345 } 346 } 347 break; 348 default: 349 isCFIMoveForDebugging = false; 350 break; 351 } 352 353 EHStreamer *ES = nullptr; 354 switch (MAI->getExceptionHandlingType()) { 355 case ExceptionHandling::None: 356 break; 357 case ExceptionHandling::SjLj: 358 case ExceptionHandling::DwarfCFI: 359 ES = new DwarfCFIException(this); 360 break; 361 case ExceptionHandling::ARM: 362 ES = new ARMException(this); 363 break; 364 case ExceptionHandling::WinEH: 365 switch (MAI->getWinEHEncodingType()) { 366 default: llvm_unreachable("unsupported unwinding information encoding"); 367 case WinEH::EncodingType::Invalid: 368 break; 369 case WinEH::EncodingType::X86: 370 case WinEH::EncodingType::Itanium: 371 ES = new WinException(this); 372 break; 373 } 374 break; 375 case ExceptionHandling::Wasm: 376 ES = new WasmException(this); 377 break; 378 } 379 if (ES) 380 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName, 381 EHTimerDescription, DWARFGroupName, 382 DWARFGroupDescription); 383 384 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2). 385 if (mdconst::extract_or_null<ConstantInt>( 386 MMI->getModule()->getModuleFlag("cfguard"))) 387 Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName, 388 CFGuardDescription, DWARFGroupName, 389 DWARFGroupDescription); 390 return false; 391 } 392 393 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 394 if (!MAI.hasWeakDefCanBeHiddenDirective()) 395 return false; 396 397 return GV->canBeOmittedFromSymbolTable(); 398 } 399 400 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 401 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 402 switch (Linkage) { 403 case GlobalValue::CommonLinkage: 404 case GlobalValue::LinkOnceAnyLinkage: 405 case GlobalValue::LinkOnceODRLinkage: 406 case GlobalValue::WeakAnyLinkage: 407 case GlobalValue::WeakODRLinkage: 408 if (MAI->hasWeakDefDirective()) { 409 // .globl _foo 410 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 411 412 if (!canBeHidden(GV, *MAI)) 413 // .weak_definition _foo 414 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 415 else 416 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 417 } else if (MAI->hasLinkOnceDirective()) { 418 // .globl _foo 419 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 420 //NOTE: linkonce is handled by the section the symbol was assigned to. 421 } else { 422 // .weak _foo 423 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak); 424 } 425 return; 426 case GlobalValue::ExternalLinkage: 427 // If external, declare as a global symbol: .globl _foo 428 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 429 return; 430 case GlobalValue::PrivateLinkage: 431 return; 432 case GlobalValue::InternalLinkage: 433 if (MAI->hasDotLGloblDirective()) 434 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_LGlobal); 435 return; 436 case GlobalValue::AppendingLinkage: 437 case GlobalValue::AvailableExternallyLinkage: 438 case GlobalValue::ExternalWeakLinkage: 439 llvm_unreachable("Should never emit this"); 440 } 441 llvm_unreachable("Unknown linkage type!"); 442 } 443 444 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 445 const GlobalValue *GV) const { 446 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler()); 447 } 448 449 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 450 return TM.getSymbol(GV); 451 } 452 453 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 454 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 455 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal(); 456 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 457 "No emulated TLS variables in the common section"); 458 459 // Never emit TLS variable xyz in emulated TLS model. 460 // The initialization value is in __emutls_t.xyz instead of xyz. 461 if (IsEmuTLSVar) 462 return; 463 464 if (GV->hasInitializer()) { 465 // Check to see if this is a special global used by LLVM, if so, emit it. 466 if (EmitSpecialLLVMGlobal(GV)) 467 return; 468 469 // Skip the emission of global equivalents. The symbol can be emitted later 470 // on by emitGlobalGOTEquivs in case it turns out to be needed. 471 if (GlobalGOTEquivs.count(getSymbol(GV))) 472 return; 473 474 if (isVerbose()) { 475 // When printing the control variable __emutls_v.*, 476 // we don't need to print the original TLS variable name. 477 GV->printAsOperand(OutStreamer->GetCommentOS(), 478 /*PrintType=*/false, GV->getParent()); 479 OutStreamer->GetCommentOS() << '\n'; 480 } 481 } 482 483 MCSymbol *GVSym = getSymbol(GV); 484 MCSymbol *EmittedSym = GVSym; 485 486 // getOrCreateEmuTLSControlSym only creates the symbol with name and default 487 // attributes. 488 // GV's or GVSym's attributes will be used for the EmittedSym. 489 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 490 491 if (!GV->hasInitializer()) // External globals require no extra code. 492 return; 493 494 GVSym->redefineIfPossible(); 495 if (GVSym->isDefined() || GVSym->isVariable()) 496 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 497 "' is already defined"); 498 499 if (MAI->hasDotTypeDotSizeDirective()) 500 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 501 502 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 503 504 const DataLayout &DL = GV->getParent()->getDataLayout(); 505 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 506 507 // If the alignment is specified, we *must* obey it. Overaligning a global 508 // with a specified alignment is a prompt way to break globals emitted to 509 // sections and expected to be contiguous (e.g. ObjC metadata). 510 const Align Alignment = getGVAlignment(GV, DL); 511 512 for (const HandlerInfo &HI : Handlers) { 513 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 514 HI.TimerGroupName, HI.TimerGroupDescription, 515 TimePassesIsEnabled); 516 HI.Handler->setSymbolSize(GVSym, Size); 517 } 518 519 // Handle common symbols 520 if (GVKind.isCommon()) { 521 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 522 // .comm _foo, 42, 4 523 const bool SupportsAlignment = 524 getObjFileLowering().getCommDirectiveSupportsAlignment(); 525 OutStreamer->EmitCommonSymbol(GVSym, Size, 526 SupportsAlignment ? Alignment.value() : 0); 527 return; 528 } 529 530 // Determine to which section this global should be emitted. 531 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM); 532 533 // If we have a bss global going to a section that supports the 534 // zerofill directive, do so here. 535 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 536 TheSection->isVirtualSection()) { 537 if (Size == 0) 538 Size = 1; // zerofill of 0 bytes is undefined. 539 EmitLinkage(GV, GVSym); 540 // .zerofill __DATA, __bss, _foo, 400, 5 541 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Alignment.value()); 542 return; 543 } 544 545 // If this is a BSS local symbol and we are emitting in the BSS 546 // section use .lcomm/.comm directive. 547 if (GVKind.isBSSLocal() && 548 getObjFileLowering().getBSSSection() == TheSection) { 549 if (Size == 0) 550 Size = 1; // .comm Foo, 0 is undefined, avoid it. 551 552 // Use .lcomm only if it supports user-specified alignment. 553 // Otherwise, while it would still be correct to use .lcomm in some 554 // cases (e.g. when Align == 1), the external assembler might enfore 555 // some -unknown- default alignment behavior, which could cause 556 // spurious differences between external and integrated assembler. 557 // Prefer to simply fall back to .local / .comm in this case. 558 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 559 // .lcomm _foo, 42 560 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Alignment.value()); 561 return; 562 } 563 564 // .local _foo 565 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local); 566 // .comm _foo, 42, 4 567 const bool SupportsAlignment = 568 getObjFileLowering().getCommDirectiveSupportsAlignment(); 569 OutStreamer->EmitCommonSymbol(GVSym, Size, 570 SupportsAlignment ? Alignment.value() : 0); 571 return; 572 } 573 574 // Handle thread local data for mach-o which requires us to output an 575 // additional structure of data and mangle the original symbol so that we 576 // can reference it later. 577 // 578 // TODO: This should become an "emit thread local global" method on TLOF. 579 // All of this macho specific stuff should be sunk down into TLOFMachO and 580 // stuff like "TLSExtraDataSection" should no longer be part of the parent 581 // TLOF class. This will also make it more obvious that stuff like 582 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 583 // specific code. 584 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 585 // Emit the .tbss symbol 586 MCSymbol *MangSym = 587 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 588 589 if (GVKind.isThreadBSS()) { 590 TheSection = getObjFileLowering().getTLSBSSSection(); 591 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, Alignment.value()); 592 } else if (GVKind.isThreadData()) { 593 OutStreamer->SwitchSection(TheSection); 594 595 EmitAlignment(Alignment, GV); 596 OutStreamer->EmitLabel(MangSym); 597 598 EmitGlobalConstant(GV->getParent()->getDataLayout(), 599 GV->getInitializer()); 600 } 601 602 OutStreamer->AddBlankLine(); 603 604 // Emit the variable struct for the runtime. 605 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 606 607 OutStreamer->SwitchSection(TLVSect); 608 // Emit the linkage here. 609 EmitLinkage(GV, GVSym); 610 OutStreamer->EmitLabel(GVSym); 611 612 // Three pointers in size: 613 // - __tlv_bootstrap - used to make sure support exists 614 // - spare pointer, used when mapped by the runtime 615 // - pointer to mangled symbol above with initializer 616 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 617 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 618 PtrSize); 619 OutStreamer->EmitIntValue(0, PtrSize); 620 OutStreamer->EmitSymbolValue(MangSym, PtrSize); 621 622 OutStreamer->AddBlankLine(); 623 return; 624 } 625 626 MCSymbol *EmittedInitSym = GVSym; 627 628 OutStreamer->SwitchSection(TheSection); 629 630 EmitLinkage(GV, EmittedInitSym); 631 EmitAlignment(Alignment, GV); 632 633 OutStreamer->EmitLabel(EmittedInitSym); 634 635 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 636 637 if (MAI->hasDotTypeDotSizeDirective()) 638 // .size foo, 42 639 OutStreamer->emitELFSize(EmittedInitSym, 640 MCConstantExpr::create(Size, OutContext)); 641 642 OutStreamer->AddBlankLine(); 643 } 644 645 /// Emit the directive and value for debug thread local expression 646 /// 647 /// \p Value - The value to emit. 648 /// \p Size - The size of the integer (in bytes) to emit. 649 void AsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const { 650 OutStreamer->EmitValue(Value, Size); 651 } 652 653 /// EmitFunctionHeader - This method emits the header for the current 654 /// function. 655 void AsmPrinter::EmitFunctionHeader() { 656 const Function &F = MF->getFunction(); 657 658 if (isVerbose()) 659 OutStreamer->GetCommentOS() 660 << "-- Begin function " 661 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n'; 662 663 // Print out constants referenced by the function 664 EmitConstantPool(); 665 666 // Print the 'header' of function. 667 OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM)); 668 EmitVisibility(CurrentFnSym, F.getVisibility()); 669 670 if (MAI->needsFunctionDescriptors() && 671 F.getLinkage() != GlobalValue::InternalLinkage) 672 EmitLinkage(&F, CurrentFnDescSym); 673 674 EmitLinkage(&F, CurrentFnSym); 675 if (MAI->hasFunctionAlignment()) 676 EmitAlignment(MF->getAlignment(), &F); 677 678 if (MAI->hasDotTypeDotSizeDirective()) 679 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 680 681 if (F.hasFnAttribute(Attribute::Cold)) 682 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_Cold); 683 684 if (isVerbose()) { 685 F.printAsOperand(OutStreamer->GetCommentOS(), 686 /*PrintType=*/false, F.getParent()); 687 OutStreamer->GetCommentOS() << '\n'; 688 } 689 690 // Emit the prefix data. 691 if (F.hasPrefixData()) { 692 if (MAI->hasSubsectionsViaSymbols()) { 693 // Preserving prefix data on platforms which use subsections-via-symbols 694 // is a bit tricky. Here we introduce a symbol for the prefix data 695 // and use the .alt_entry attribute to mark the function's real entry point 696 // as an alternative entry point to the prefix-data symbol. 697 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol(); 698 OutStreamer->EmitLabel(PrefixSym); 699 700 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 701 702 // Emit an .alt_entry directive for the actual function symbol. 703 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry); 704 } else { 705 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 706 } 707 } 708 709 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily 710 // place prefix data before NOPs. 711 unsigned PatchableFunctionPrefix = 0; 712 (void)F.getFnAttribute("patchable-function-prefix") 713 .getValueAsString() 714 .getAsInteger(10, PatchableFunctionPrefix); 715 if (PatchableFunctionPrefix) { 716 CurrentPatchableFunctionEntrySym = 717 OutContext.createLinkerPrivateTempSymbol(); 718 OutStreamer->EmitLabel(CurrentPatchableFunctionEntrySym); 719 emitNops(PatchableFunctionPrefix); 720 } else { 721 CurrentPatchableFunctionEntrySym = CurrentFnBegin; 722 } 723 724 // Emit the function descriptor. This is a virtual function to allow targets 725 // to emit their specific function descriptor. 726 if (MAI->needsFunctionDescriptors()) 727 EmitFunctionDescriptor(); 728 729 // Emit the CurrentFnSym. This is a virtual function to allow targets to do 730 // their wild and crazy things as required. 731 EmitFunctionEntryLabel(); 732 733 // If the function had address-taken blocks that got deleted, then we have 734 // references to the dangling symbols. Emit them at the start of the function 735 // so that we don't get references to undefined symbols. 736 std::vector<MCSymbol*> DeadBlockSyms; 737 MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms); 738 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 739 OutStreamer->AddComment("Address taken block that was later removed"); 740 OutStreamer->EmitLabel(DeadBlockSyms[i]); 741 } 742 743 if (CurrentFnBegin) { 744 if (MAI->useAssignmentForEHBegin()) { 745 MCSymbol *CurPos = OutContext.createTempSymbol(); 746 OutStreamer->EmitLabel(CurPos); 747 OutStreamer->EmitAssignment(CurrentFnBegin, 748 MCSymbolRefExpr::create(CurPos, OutContext)); 749 } else { 750 OutStreamer->EmitLabel(CurrentFnBegin); 751 } 752 } 753 754 // Emit pre-function debug and/or EH information. 755 for (const HandlerInfo &HI : Handlers) { 756 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 757 HI.TimerGroupDescription, TimePassesIsEnabled); 758 HI.Handler->beginFunction(MF); 759 } 760 761 // Emit the prologue data. 762 if (F.hasPrologueData()) 763 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData()); 764 } 765 766 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 767 /// function. This can be overridden by targets as required to do custom stuff. 768 void AsmPrinter::EmitFunctionEntryLabel() { 769 CurrentFnSym->redefineIfPossible(); 770 771 // The function label could have already been emitted if two symbols end up 772 // conflicting due to asm renaming. Detect this and emit an error. 773 if (CurrentFnSym->isVariable()) 774 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 775 "' is a protected alias"); 776 if (CurrentFnSym->isDefined()) 777 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 778 "' label emitted multiple times to assembly file"); 779 780 return OutStreamer->EmitLabel(CurrentFnSym); 781 } 782 783 /// emitComments - Pretty-print comments for instructions. 784 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 785 const MachineFunction *MF = MI.getMF(); 786 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 787 788 // Check for spills and reloads 789 790 // We assume a single instruction only has a spill or reload, not 791 // both. 792 Optional<unsigned> Size; 793 if ((Size = MI.getRestoreSize(TII))) { 794 CommentOS << *Size << "-byte Reload\n"; 795 } else if ((Size = MI.getFoldedRestoreSize(TII))) { 796 if (*Size) 797 CommentOS << *Size << "-byte Folded Reload\n"; 798 } else if ((Size = MI.getSpillSize(TII))) { 799 CommentOS << *Size << "-byte Spill\n"; 800 } else if ((Size = MI.getFoldedSpillSize(TII))) { 801 if (*Size) 802 CommentOS << *Size << "-byte Folded Spill\n"; 803 } 804 805 // Check for spill-induced copies 806 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 807 CommentOS << " Reload Reuse\n"; 808 } 809 810 /// emitImplicitDef - This method emits the specified machine instruction 811 /// that is an implicit def. 812 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 813 Register RegNo = MI->getOperand(0).getReg(); 814 815 SmallString<128> Str; 816 raw_svector_ostream OS(Str); 817 OS << "implicit-def: " 818 << printReg(RegNo, MF->getSubtarget().getRegisterInfo()); 819 820 OutStreamer->AddComment(OS.str()); 821 OutStreamer->AddBlankLine(); 822 } 823 824 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 825 std::string Str; 826 raw_string_ostream OS(Str); 827 OS << "kill:"; 828 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 829 const MachineOperand &Op = MI->getOperand(i); 830 assert(Op.isReg() && "KILL instruction must have only register operands"); 831 OS << ' ' << (Op.isDef() ? "def " : "killed ") 832 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo()); 833 } 834 AP.OutStreamer->AddComment(OS.str()); 835 AP.OutStreamer->AddBlankLine(); 836 } 837 838 /// emitDebugValueComment - This method handles the target-independent form 839 /// of DBG_VALUE, returning true if it was able to do so. A false return 840 /// means the target will need to handle MI in EmitInstruction. 841 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 842 // This code handles only the 4-operand target-independent form. 843 if (MI->getNumOperands() != 4) 844 return false; 845 846 SmallString<128> Str; 847 raw_svector_ostream OS(Str); 848 OS << "DEBUG_VALUE: "; 849 850 const DILocalVariable *V = MI->getDebugVariable(); 851 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 852 StringRef Name = SP->getName(); 853 if (!Name.empty()) 854 OS << Name << ":"; 855 } 856 OS << V->getName(); 857 OS << " <- "; 858 859 // The second operand is only an offset if it's an immediate. 860 bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 861 int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0; 862 const DIExpression *Expr = MI->getDebugExpression(); 863 if (Expr->getNumElements()) { 864 OS << '['; 865 bool NeedSep = false; 866 for (auto Op : Expr->expr_ops()) { 867 if (NeedSep) 868 OS << ", "; 869 else 870 NeedSep = true; 871 OS << dwarf::OperationEncodingString(Op.getOp()); 872 for (unsigned I = 0; I < Op.getNumArgs(); ++I) 873 OS << ' ' << Op.getArg(I); 874 } 875 OS << "] "; 876 } 877 878 // Register or immediate value. Register 0 means undef. 879 if (MI->getOperand(0).isFPImm()) { 880 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 881 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 882 OS << (double)APF.convertToFloat(); 883 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 884 OS << APF.convertToDouble(); 885 } else { 886 // There is no good way to print long double. Convert a copy to 887 // double. Ah well, it's only a comment. 888 bool ignored; 889 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 890 &ignored); 891 OS << "(long double) " << APF.convertToDouble(); 892 } 893 } else if (MI->getOperand(0).isImm()) { 894 OS << MI->getOperand(0).getImm(); 895 } else if (MI->getOperand(0).isCImm()) { 896 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 897 } else if (MI->getOperand(0).isTargetIndex()) { 898 auto Op = MI->getOperand(0); 899 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")"; 900 return true; 901 } else { 902 unsigned Reg; 903 if (MI->getOperand(0).isReg()) { 904 Reg = MI->getOperand(0).getReg(); 905 } else { 906 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 907 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 908 Offset += TFI->getFrameIndexReference(*AP.MF, 909 MI->getOperand(0).getIndex(), Reg); 910 MemLoc = true; 911 } 912 if (Reg == 0) { 913 // Suppress offset, it is not meaningful here. 914 OS << "undef"; 915 // NOTE: Want this comment at start of line, don't emit with AddComment. 916 AP.OutStreamer->emitRawComment(OS.str()); 917 return true; 918 } 919 if (MemLoc) 920 OS << '['; 921 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 922 } 923 924 if (MemLoc) 925 OS << '+' << Offset << ']'; 926 927 // NOTE: Want this comment at start of line, don't emit with AddComment. 928 AP.OutStreamer->emitRawComment(OS.str()); 929 return true; 930 } 931 932 /// This method handles the target-independent form of DBG_LABEL, returning 933 /// true if it was able to do so. A false return means the target will need 934 /// to handle MI in EmitInstruction. 935 static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) { 936 if (MI->getNumOperands() != 1) 937 return false; 938 939 SmallString<128> Str; 940 raw_svector_ostream OS(Str); 941 OS << "DEBUG_LABEL: "; 942 943 const DILabel *V = MI->getDebugLabel(); 944 if (auto *SP = dyn_cast<DISubprogram>( 945 V->getScope()->getNonLexicalBlockFileScope())) { 946 StringRef Name = SP->getName(); 947 if (!Name.empty()) 948 OS << Name << ":"; 949 } 950 OS << V->getName(); 951 952 // NOTE: Want this comment at start of line, don't emit with AddComment. 953 AP.OutStreamer->emitRawComment(OS.str()); 954 return true; 955 } 956 957 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const { 958 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 959 MF->getFunction().needsUnwindTableEntry()) 960 return CFI_M_EH; 961 962 if (MMI->hasDebugInfo() || MF->getTarget().Options.ForceDwarfFrameSection) 963 return CFI_M_Debug; 964 965 return CFI_M_None; 966 } 967 968 bool AsmPrinter::needsSEHMoves() { 969 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry(); 970 } 971 972 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 973 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 974 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 975 ExceptionHandlingType != ExceptionHandling::ARM) 976 return; 977 978 if (needsCFIMoves() == CFI_M_None) 979 return; 980 981 // If there is no "real" instruction following this CFI instruction, skip 982 // emitting it; it would be beyond the end of the function's FDE range. 983 auto *MBB = MI.getParent(); 984 auto I = std::next(MI.getIterator()); 985 while (I != MBB->end() && I->isTransient()) 986 ++I; 987 if (I == MBB->instr_end() && 988 MBB->getReverseIterator() == MBB->getParent()->rbegin()) 989 return; 990 991 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions(); 992 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 993 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 994 emitCFIInstruction(CFI); 995 } 996 997 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 998 // The operands are the MCSymbol and the frame offset of the allocation. 999 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 1000 int FrameOffset = MI.getOperand(1).getImm(); 1001 1002 // Emit a symbol assignment. 1003 OutStreamer->EmitAssignment(FrameAllocSym, 1004 MCConstantExpr::create(FrameOffset, OutContext)); 1005 } 1006 1007 void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) { 1008 if (!MF.getTarget().Options.EmitStackSizeSection) 1009 return; 1010 1011 MCSection *StackSizeSection = 1012 getObjFileLowering().getStackSizesSection(*getCurrentSection()); 1013 if (!StackSizeSection) 1014 return; 1015 1016 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 1017 // Don't emit functions with dynamic stack allocations. 1018 if (FrameInfo.hasVarSizedObjects()) 1019 return; 1020 1021 OutStreamer->PushSection(); 1022 OutStreamer->SwitchSection(StackSizeSection); 1023 1024 const MCSymbol *FunctionSymbol = getFunctionBegin(); 1025 uint64_t StackSize = FrameInfo.getStackSize(); 1026 OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize()); 1027 OutStreamer->EmitULEB128IntValue(StackSize); 1028 1029 OutStreamer->PopSection(); 1030 } 1031 1032 static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF, 1033 MachineModuleInfo *MMI) { 1034 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo()) 1035 return true; 1036 1037 // We might emit an EH table that uses function begin and end labels even if 1038 // we don't have any landingpads. 1039 if (!MF.getFunction().hasPersonalityFn()) 1040 return false; 1041 return !isNoOpWithoutInvoke( 1042 classifyEHPersonality(MF.getFunction().getPersonalityFn())); 1043 } 1044 1045 /// EmitFunctionBody - This method emits the body and trailer for a 1046 /// function. 1047 void AsmPrinter::EmitFunctionBody() { 1048 EmitFunctionHeader(); 1049 1050 // Emit target-specific gunk before the function body. 1051 EmitFunctionBodyStart(); 1052 1053 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 1054 1055 if (isVerbose()) { 1056 // Get MachineDominatorTree or compute it on the fly if it's unavailable 1057 MDT = getAnalysisIfAvailable<MachineDominatorTree>(); 1058 if (!MDT) { 1059 OwnedMDT = std::make_unique<MachineDominatorTree>(); 1060 OwnedMDT->getBase().recalculate(*MF); 1061 MDT = OwnedMDT.get(); 1062 } 1063 1064 // Get MachineLoopInfo or compute it on the fly if it's unavailable 1065 MLI = getAnalysisIfAvailable<MachineLoopInfo>(); 1066 if (!MLI) { 1067 OwnedMLI = std::make_unique<MachineLoopInfo>(); 1068 OwnedMLI->getBase().analyze(MDT->getBase()); 1069 MLI = OwnedMLI.get(); 1070 } 1071 } 1072 1073 // Print out code for the function. 1074 bool HasAnyRealCode = false; 1075 int NumInstsInFunction = 0; 1076 for (auto &MBB : *MF) { 1077 // Print a label for the basic block. 1078 EmitBasicBlockStart(MBB); 1079 for (auto &MI : MBB) { 1080 // Print the assembly for the instruction. 1081 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 1082 !MI.isDebugInstr()) { 1083 HasAnyRealCode = true; 1084 ++NumInstsInFunction; 1085 } 1086 1087 // If there is a pre-instruction symbol, emit a label for it here. 1088 if (MCSymbol *S = MI.getPreInstrSymbol()) 1089 OutStreamer->EmitLabel(S); 1090 1091 if (ShouldPrintDebugScopes) { 1092 for (const HandlerInfo &HI : Handlers) { 1093 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1094 HI.TimerGroupName, HI.TimerGroupDescription, 1095 TimePassesIsEnabled); 1096 HI.Handler->beginInstruction(&MI); 1097 } 1098 } 1099 1100 if (isVerbose()) 1101 emitComments(MI, OutStreamer->GetCommentOS()); 1102 1103 switch (MI.getOpcode()) { 1104 case TargetOpcode::CFI_INSTRUCTION: 1105 emitCFIInstruction(MI); 1106 break; 1107 case TargetOpcode::LOCAL_ESCAPE: 1108 emitFrameAlloc(MI); 1109 break; 1110 case TargetOpcode::ANNOTATION_LABEL: 1111 case TargetOpcode::EH_LABEL: 1112 case TargetOpcode::GC_LABEL: 1113 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol()); 1114 break; 1115 case TargetOpcode::INLINEASM: 1116 case TargetOpcode::INLINEASM_BR: 1117 EmitInlineAsm(&MI); 1118 break; 1119 case TargetOpcode::DBG_VALUE: 1120 if (isVerbose()) { 1121 if (!emitDebugValueComment(&MI, *this)) 1122 EmitInstruction(&MI); 1123 } 1124 break; 1125 case TargetOpcode::DBG_LABEL: 1126 if (isVerbose()) { 1127 if (!emitDebugLabelComment(&MI, *this)) 1128 EmitInstruction(&MI); 1129 } 1130 break; 1131 case TargetOpcode::IMPLICIT_DEF: 1132 if (isVerbose()) emitImplicitDef(&MI); 1133 break; 1134 case TargetOpcode::KILL: 1135 if (isVerbose()) emitKill(&MI, *this); 1136 break; 1137 default: 1138 EmitInstruction(&MI); 1139 break; 1140 } 1141 1142 // If there is a post-instruction symbol, emit a label for it here. 1143 if (MCSymbol *S = MI.getPostInstrSymbol()) 1144 OutStreamer->EmitLabel(S); 1145 1146 if (ShouldPrintDebugScopes) { 1147 for (const HandlerInfo &HI : Handlers) { 1148 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1149 HI.TimerGroupName, HI.TimerGroupDescription, 1150 TimePassesIsEnabled); 1151 HI.Handler->endInstruction(); 1152 } 1153 } 1154 } 1155 1156 EmitBasicBlockEnd(MBB); 1157 } 1158 1159 EmittedInsts += NumInstsInFunction; 1160 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount", 1161 MF->getFunction().getSubprogram(), 1162 &MF->front()); 1163 R << ore::NV("NumInstructions", NumInstsInFunction) 1164 << " instructions in function"; 1165 ORE->emit(R); 1166 1167 // If the function is empty and the object file uses .subsections_via_symbols, 1168 // then we need to emit *something* to the function body to prevent the 1169 // labels from collapsing together. Just emit a noop. 1170 // Similarly, don't emit empty functions on Windows either. It can lead to 1171 // duplicate entries (two functions with the same RVA) in the Guard CF Table 1172 // after linking, causing the kernel not to load the binary: 1173 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html 1174 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer. 1175 const Triple &TT = TM.getTargetTriple(); 1176 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() || 1177 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) { 1178 MCInst Noop; 1179 MF->getSubtarget().getInstrInfo()->getNoop(Noop); 1180 1181 // Targets can opt-out of emitting the noop here by leaving the opcode 1182 // unspecified. 1183 if (Noop.getOpcode()) { 1184 OutStreamer->AddComment("avoids zero-length function"); 1185 emitNops(1); 1186 } 1187 } 1188 1189 const Function &F = MF->getFunction(); 1190 for (const auto &BB : F) { 1191 if (!BB.hasAddressTaken()) 1192 continue; 1193 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 1194 if (Sym->isDefined()) 1195 continue; 1196 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 1197 OutStreamer->EmitLabel(Sym); 1198 } 1199 1200 // Emit target-specific gunk after the function body. 1201 EmitFunctionBodyEnd(); 1202 1203 if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) || 1204 MAI->hasDotTypeDotSizeDirective()) { 1205 // Create a symbol for the end of function. 1206 CurrentFnEnd = createTempSymbol("func_end"); 1207 OutStreamer->EmitLabel(CurrentFnEnd); 1208 } 1209 1210 // If the target wants a .size directive for the size of the function, emit 1211 // it. 1212 if (MAI->hasDotTypeDotSizeDirective()) { 1213 // We can get the size as difference between the function label and the 1214 // temp label. 1215 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1216 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 1217 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 1218 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 1219 } 1220 1221 for (const HandlerInfo &HI : Handlers) { 1222 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1223 HI.TimerGroupDescription, TimePassesIsEnabled); 1224 HI.Handler->markFunctionEnd(); 1225 } 1226 1227 // Print out jump tables referenced by the function. 1228 EmitJumpTableInfo(); 1229 1230 // Emit post-function debug and/or EH information. 1231 for (const HandlerInfo &HI : Handlers) { 1232 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1233 HI.TimerGroupDescription, TimePassesIsEnabled); 1234 HI.Handler->endFunction(MF); 1235 } 1236 1237 // Emit section containing stack size metadata. 1238 emitStackSizeSection(*MF); 1239 1240 emitPatchableFunctionEntries(); 1241 1242 if (isVerbose()) 1243 OutStreamer->GetCommentOS() << "-- End function\n"; 1244 1245 OutStreamer->AddBlankLine(); 1246 } 1247 1248 /// Compute the number of Global Variables that uses a Constant. 1249 static unsigned getNumGlobalVariableUses(const Constant *C) { 1250 if (!C) 1251 return 0; 1252 1253 if (isa<GlobalVariable>(C)) 1254 return 1; 1255 1256 unsigned NumUses = 0; 1257 for (auto *CU : C->users()) 1258 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1259 1260 return NumUses; 1261 } 1262 1263 /// Only consider global GOT equivalents if at least one user is a 1264 /// cstexpr inside an initializer of another global variables. Also, don't 1265 /// handle cstexpr inside instructions. During global variable emission, 1266 /// candidates are skipped and are emitted later in case at least one cstexpr 1267 /// isn't replaced by a PC relative GOT entry access. 1268 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1269 unsigned &NumGOTEquivUsers) { 1270 // Global GOT equivalents are unnamed private globals with a constant 1271 // pointer initializer to another global symbol. They must point to a 1272 // GlobalVariable or Function, i.e., as GlobalValue. 1273 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1274 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1275 !isa<GlobalValue>(GV->getOperand(0))) 1276 return false; 1277 1278 // To be a got equivalent, at least one of its users need to be a constant 1279 // expression used by another global variable. 1280 for (auto *U : GV->users()) 1281 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1282 1283 return NumGOTEquivUsers > 0; 1284 } 1285 1286 /// Unnamed constant global variables solely contaning a pointer to 1287 /// another globals variable is equivalent to a GOT table entry; it contains the 1288 /// the address of another symbol. Optimize it and replace accesses to these 1289 /// "GOT equivalents" by using the GOT entry for the final global instead. 1290 /// Compute GOT equivalent candidates among all global variables to avoid 1291 /// emitting them if possible later on, after it use is replaced by a GOT entry 1292 /// access. 1293 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1294 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1295 return; 1296 1297 for (const auto &G : M.globals()) { 1298 unsigned NumGOTEquivUsers = 0; 1299 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1300 continue; 1301 1302 const MCSymbol *GOTEquivSym = getSymbol(&G); 1303 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1304 } 1305 } 1306 1307 /// Constant expressions using GOT equivalent globals may not be eligible 1308 /// for PC relative GOT entry conversion, in such cases we need to emit such 1309 /// globals we previously omitted in EmitGlobalVariable. 1310 void AsmPrinter::emitGlobalGOTEquivs() { 1311 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1312 return; 1313 1314 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1315 for (auto &I : GlobalGOTEquivs) { 1316 const GlobalVariable *GV = I.second.first; 1317 unsigned Cnt = I.second.second; 1318 if (Cnt) 1319 FailedCandidates.push_back(GV); 1320 } 1321 GlobalGOTEquivs.clear(); 1322 1323 for (auto *GV : FailedCandidates) 1324 EmitGlobalVariable(GV); 1325 } 1326 1327 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1328 const GlobalIndirectSymbol& GIS) { 1329 MCSymbol *Name = getSymbol(&GIS); 1330 1331 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1332 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global); 1333 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1334 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference); 1335 else 1336 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1337 1338 bool IsFunction = GIS.getValueType()->isFunctionTy(); 1339 1340 // Treat bitcasts of functions as functions also. This is important at least 1341 // on WebAssembly where object and function addresses can't alias each other. 1342 if (!IsFunction) 1343 if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol())) 1344 if (CE->getOpcode() == Instruction::BitCast) 1345 IsFunction = 1346 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy(); 1347 1348 // Set the symbol type to function if the alias has a function type. 1349 // This affects codegen when the aliasee is not a function. 1350 if (IsFunction) 1351 OutStreamer->EmitSymbolAttribute(Name, isa<GlobalIFunc>(GIS) 1352 ? MCSA_ELF_TypeIndFunction 1353 : MCSA_ELF_TypeFunction); 1354 1355 EmitVisibility(Name, GIS.getVisibility()); 1356 1357 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1358 1359 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1360 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry); 1361 1362 // Emit the directives as assignments aka .set: 1363 OutStreamer->EmitAssignment(Name, Expr); 1364 1365 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1366 // If the aliasee does not correspond to a symbol in the output, i.e. the 1367 // alias is not of an object or the aliased object is private, then set the 1368 // size of the alias symbol from the type of the alias. We don't do this in 1369 // other situations as the alias and aliasee having differing types but same 1370 // size may be intentional. 1371 const GlobalObject *BaseObject = GA->getBaseObject(); 1372 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1373 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1374 const DataLayout &DL = M.getDataLayout(); 1375 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1376 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1377 } 1378 } 1379 } 1380 1381 void AsmPrinter::emitRemarksSection(RemarkStreamer &RS) { 1382 if (!RS.needsSection()) 1383 return; 1384 1385 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer(); 1386 1387 Optional<SmallString<128>> Filename; 1388 if (Optional<StringRef> FilenameRef = RS.getFilename()) { 1389 Filename = *FilenameRef; 1390 sys::fs::make_absolute(*Filename); 1391 assert(!Filename->empty() && "The filename can't be empty."); 1392 } 1393 1394 std::string Buf; 1395 raw_string_ostream OS(Buf); 1396 std::unique_ptr<remarks::MetaSerializer> MetaSerializer = 1397 Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename)) 1398 : RemarkSerializer.metaSerializer(OS); 1399 MetaSerializer->emit(); 1400 1401 // Switch to the remarks section. 1402 MCSection *RemarksSection = 1403 OutContext.getObjectFileInfo()->getRemarksSection(); 1404 OutStreamer->SwitchSection(RemarksSection); 1405 1406 OutStreamer->EmitBinaryData(OS.str()); 1407 } 1408 1409 bool AsmPrinter::doFinalization(Module &M) { 1410 // Set the MachineFunction to nullptr so that we can catch attempted 1411 // accesses to MF specific features at the module level and so that 1412 // we can conditionalize accesses based on whether or not it is nullptr. 1413 MF = nullptr; 1414 1415 // Gather all GOT equivalent globals in the module. We really need two 1416 // passes over the globals: one to compute and another to avoid its emission 1417 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1418 // where the got equivalent shows up before its use. 1419 computeGlobalGOTEquivs(M); 1420 1421 // Emit global variables. 1422 for (const auto &G : M.globals()) 1423 EmitGlobalVariable(&G); 1424 1425 // Emit remaining GOT equivalent globals. 1426 emitGlobalGOTEquivs(); 1427 1428 // Emit visibility info for declarations 1429 for (const Function &F : M) { 1430 if (!F.isDeclarationForLinker()) 1431 continue; 1432 GlobalValue::VisibilityTypes V = F.getVisibility(); 1433 if (V == GlobalValue::DefaultVisibility) 1434 continue; 1435 1436 MCSymbol *Name = getSymbol(&F); 1437 EmitVisibility(Name, V, false); 1438 } 1439 1440 // Emit the remarks section contents. 1441 // FIXME: Figure out when is the safest time to emit this section. It should 1442 // not come after debug info. 1443 if (RemarkStreamer *RS = M.getContext().getRemarkStreamer()) 1444 emitRemarksSection(*RS); 1445 1446 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1447 1448 TLOF.emitModuleMetadata(*OutStreamer, M); 1449 1450 if (TM.getTargetTriple().isOSBinFormatELF()) { 1451 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1452 1453 // Output stubs for external and common global variables. 1454 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1455 if (!Stubs.empty()) { 1456 OutStreamer->SwitchSection(TLOF.getDataSection()); 1457 const DataLayout &DL = M.getDataLayout(); 1458 1459 EmitAlignment(Align(DL.getPointerSize())); 1460 for (const auto &Stub : Stubs) { 1461 OutStreamer->EmitLabel(Stub.first); 1462 OutStreamer->EmitSymbolValue(Stub.second.getPointer(), 1463 DL.getPointerSize()); 1464 } 1465 } 1466 } 1467 1468 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1469 MachineModuleInfoCOFF &MMICOFF = 1470 MMI->getObjFileInfo<MachineModuleInfoCOFF>(); 1471 1472 // Output stubs for external and common global variables. 1473 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList(); 1474 if (!Stubs.empty()) { 1475 const DataLayout &DL = M.getDataLayout(); 1476 1477 for (const auto &Stub : Stubs) { 1478 SmallString<256> SectionName = StringRef(".rdata$"); 1479 SectionName += Stub.first->getName(); 1480 OutStreamer->SwitchSection(OutContext.getCOFFSection( 1481 SectionName, 1482 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | 1483 COFF::IMAGE_SCN_LNK_COMDAT, 1484 SectionKind::getReadOnly(), Stub.first->getName(), 1485 COFF::IMAGE_COMDAT_SELECT_ANY)); 1486 EmitAlignment(Align(DL.getPointerSize())); 1487 OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global); 1488 OutStreamer->EmitLabel(Stub.first); 1489 OutStreamer->EmitSymbolValue(Stub.second.getPointer(), 1490 DL.getPointerSize()); 1491 } 1492 } 1493 } 1494 1495 // Finalize debug and EH information. 1496 for (const HandlerInfo &HI : Handlers) { 1497 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1498 HI.TimerGroupDescription, TimePassesIsEnabled); 1499 HI.Handler->endModule(); 1500 } 1501 Handlers.clear(); 1502 DD = nullptr; 1503 1504 // If the target wants to know about weak references, print them all. 1505 if (MAI->getWeakRefDirective()) { 1506 // FIXME: This is not lazy, it would be nice to only print weak references 1507 // to stuff that is actually used. Note that doing so would require targets 1508 // to notice uses in operands (due to constant exprs etc). This should 1509 // happen with the MC stuff eventually. 1510 1511 // Print out module-level global objects here. 1512 for (const auto &GO : M.global_objects()) { 1513 if (!GO.hasExternalWeakLinkage()) 1514 continue; 1515 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1516 } 1517 } 1518 1519 // Print aliases in topological order, that is, for each alias a = b, 1520 // b must be printed before a. 1521 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1522 // such an order to generate correct TOC information. 1523 SmallVector<const GlobalAlias *, 16> AliasStack; 1524 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1525 for (const auto &Alias : M.aliases()) { 1526 for (const GlobalAlias *Cur = &Alias; Cur; 1527 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1528 if (!AliasVisited.insert(Cur).second) 1529 break; 1530 AliasStack.push_back(Cur); 1531 } 1532 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack)) 1533 emitGlobalIndirectSymbol(M, *AncestorAlias); 1534 AliasStack.clear(); 1535 } 1536 for (const auto &IFunc : M.ifuncs()) 1537 emitGlobalIndirectSymbol(M, IFunc); 1538 1539 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1540 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1541 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1542 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1543 MP->finishAssembly(M, *MI, *this); 1544 1545 // Emit llvm.ident metadata in an '.ident' directive. 1546 EmitModuleIdents(M); 1547 1548 // Emit bytes for llvm.commandline metadata. 1549 EmitModuleCommandLines(M); 1550 1551 // Emit __morestack address if needed for indirect calls. 1552 if (MMI->usesMorestackAddr()) { 1553 unsigned Align = 1; 1554 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1555 getDataLayout(), SectionKind::getReadOnly(), 1556 /*C=*/nullptr, Align); 1557 OutStreamer->SwitchSection(ReadOnlySection); 1558 1559 MCSymbol *AddrSymbol = 1560 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1561 OutStreamer->EmitLabel(AddrSymbol); 1562 1563 unsigned PtrSize = MAI->getCodePointerSize(); 1564 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1565 PtrSize); 1566 } 1567 1568 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if 1569 // split-stack is used. 1570 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) { 1571 OutStreamer->SwitchSection( 1572 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0)); 1573 if (MMI->hasNosplitStack()) 1574 OutStreamer->SwitchSection( 1575 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0)); 1576 } 1577 1578 // If we don't have any trampolines, then we don't require stack memory 1579 // to be executable. Some targets have a directive to declare this. 1580 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1581 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1582 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1583 OutStreamer->SwitchSection(S); 1584 1585 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1586 // Emit /EXPORT: flags for each exported global as necessary. 1587 const auto &TLOF = getObjFileLowering(); 1588 std::string Flags; 1589 1590 for (const GlobalValue &GV : M.global_values()) { 1591 raw_string_ostream OS(Flags); 1592 TLOF.emitLinkerFlagsForGlobal(OS, &GV); 1593 OS.flush(); 1594 if (!Flags.empty()) { 1595 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1596 OutStreamer->EmitBytes(Flags); 1597 } 1598 Flags.clear(); 1599 } 1600 1601 // Emit /INCLUDE: flags for each used global as necessary. 1602 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1603 assert(LU->hasInitializer() && 1604 "expected llvm.used to have an initializer"); 1605 assert(isa<ArrayType>(LU->getValueType()) && 1606 "expected llvm.used to be an array type"); 1607 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1608 for (const Value *Op : A->operands()) { 1609 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1610 // Global symbols with internal or private linkage are not visible to 1611 // the linker, and thus would cause an error when the linker tried to 1612 // preserve the symbol due to the `/include:` directive. 1613 if (GV->hasLocalLinkage()) 1614 continue; 1615 1616 raw_string_ostream OS(Flags); 1617 TLOF.emitLinkerFlagsForUsed(OS, GV); 1618 OS.flush(); 1619 1620 if (!Flags.empty()) { 1621 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1622 OutStreamer->EmitBytes(Flags); 1623 } 1624 Flags.clear(); 1625 } 1626 } 1627 } 1628 } 1629 1630 if (TM.Options.EmitAddrsig) { 1631 // Emit address-significance attributes for all globals. 1632 OutStreamer->EmitAddrsig(); 1633 for (const GlobalValue &GV : M.global_values()) 1634 if (!GV.use_empty() && !GV.isThreadLocal() && 1635 !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") && 1636 !GV.hasAtLeastLocalUnnamedAddr()) 1637 OutStreamer->EmitAddrsigSym(getSymbol(&GV)); 1638 } 1639 1640 // Emit symbol partition specifications (ELF only). 1641 if (TM.getTargetTriple().isOSBinFormatELF()) { 1642 unsigned UniqueID = 0; 1643 for (const GlobalValue &GV : M.global_values()) { 1644 if (!GV.hasPartition() || GV.isDeclarationForLinker() || 1645 GV.getVisibility() != GlobalValue::DefaultVisibility) 1646 continue; 1647 1648 OutStreamer->SwitchSection(OutContext.getELFSection( 1649 ".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, "", ++UniqueID)); 1650 OutStreamer->EmitBytes(GV.getPartition()); 1651 OutStreamer->EmitZeros(1); 1652 OutStreamer->EmitValue( 1653 MCSymbolRefExpr::create(getSymbol(&GV), OutContext), 1654 MAI->getCodePointerSize()); 1655 } 1656 } 1657 1658 // Allow the target to emit any magic that it wants at the end of the file, 1659 // after everything else has gone out. 1660 EmitEndOfAsmFile(M); 1661 1662 MMI = nullptr; 1663 1664 OutStreamer->Finish(); 1665 OutStreamer->reset(); 1666 OwnedMLI.reset(); 1667 OwnedMDT.reset(); 1668 1669 return false; 1670 } 1671 1672 MCSymbol *AsmPrinter::getCurExceptionSym() { 1673 if (!CurExceptionSym) 1674 CurExceptionSym = createTempSymbol("exception"); 1675 return CurExceptionSym; 1676 } 1677 1678 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1679 this->MF = &MF; 1680 const Function &F = MF.getFunction(); 1681 1682 // Get the function symbol. 1683 if (MAI->needsFunctionDescriptors()) { 1684 assert(TM.getTargetTriple().isOSAIX() && "Function descriptor is only" 1685 " supported on AIX."); 1686 assert(CurrentFnDescSym && "The function descriptor symbol needs to be" 1687 " initalized first."); 1688 1689 // Get the function entry point symbol. 1690 CurrentFnSym = 1691 OutContext.getOrCreateSymbol("." + CurrentFnDescSym->getName()); 1692 1693 MCSectionXCOFF *FnEntryPointSec = 1694 cast<MCSectionXCOFF>(getObjFileLowering().SectionForGlobal(&F, TM)); 1695 // Set the containing csect. 1696 cast<MCSymbolXCOFF>(CurrentFnSym)->setContainingCsect(FnEntryPointSec); 1697 } else { 1698 CurrentFnSym = getSymbol(&MF.getFunction()); 1699 } 1700 1701 CurrentFnSymForSize = CurrentFnSym; 1702 CurrentFnBegin = nullptr; 1703 CurExceptionSym = nullptr; 1704 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1705 if (F.hasFnAttribute("patchable-function-entry") || 1706 needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize || 1707 MF.getTarget().Options.EmitStackSizeSection) { 1708 CurrentFnBegin = createTempSymbol("func_begin"); 1709 if (NeedsLocalForSize) 1710 CurrentFnSymForSize = CurrentFnBegin; 1711 } 1712 1713 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 1714 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1715 MBFI = (PSI && PSI->hasProfileSummary()) ? 1716 // ORE conditionally computes MBFI. If available, use it, otherwise 1717 // request it. 1718 (ORE->getBFI() ? ORE->getBFI() : 1719 &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()) : 1720 nullptr; 1721 } 1722 1723 namespace { 1724 1725 // Keep track the alignment, constpool entries per Section. 1726 struct SectionCPs { 1727 MCSection *S; 1728 unsigned Alignment; 1729 SmallVector<unsigned, 4> CPEs; 1730 1731 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {} 1732 }; 1733 1734 } // end anonymous namespace 1735 1736 /// EmitConstantPool - Print to the current output stream assembly 1737 /// representations of the constants in the constant pool MCP. This is 1738 /// used to print out constants which have been "spilled to memory" by 1739 /// the code generator. 1740 void AsmPrinter::EmitConstantPool() { 1741 const MachineConstantPool *MCP = MF->getConstantPool(); 1742 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1743 if (CP.empty()) return; 1744 1745 // Calculate sections for constant pool entries. We collect entries to go into 1746 // the same section together to reduce amount of section switch statements. 1747 SmallVector<SectionCPs, 4> CPSections; 1748 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1749 const MachineConstantPoolEntry &CPE = CP[i]; 1750 unsigned Align = CPE.getAlignment(); 1751 1752 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1753 1754 const Constant *C = nullptr; 1755 if (!CPE.isMachineConstantPoolEntry()) 1756 C = CPE.Val.ConstVal; 1757 1758 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(), 1759 Kind, C, Align); 1760 1761 // The number of sections are small, just do a linear search from the 1762 // last section to the first. 1763 bool Found = false; 1764 unsigned SecIdx = CPSections.size(); 1765 while (SecIdx != 0) { 1766 if (CPSections[--SecIdx].S == S) { 1767 Found = true; 1768 break; 1769 } 1770 } 1771 if (!Found) { 1772 SecIdx = CPSections.size(); 1773 CPSections.push_back(SectionCPs(S, Align)); 1774 } 1775 1776 if (Align > CPSections[SecIdx].Alignment) 1777 CPSections[SecIdx].Alignment = Align; 1778 CPSections[SecIdx].CPEs.push_back(i); 1779 } 1780 1781 // Now print stuff into the calculated sections. 1782 const MCSection *CurSection = nullptr; 1783 unsigned Offset = 0; 1784 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1785 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1786 unsigned CPI = CPSections[i].CPEs[j]; 1787 MCSymbol *Sym = GetCPISymbol(CPI); 1788 if (!Sym->isUndefined()) 1789 continue; 1790 1791 if (TM.getTargetTriple().isOSBinFormatXCOFF()) { 1792 cast<MCSymbolXCOFF>(Sym)->setContainingCsect( 1793 cast<MCSectionXCOFF>(CPSections[i].S)); 1794 } 1795 1796 if (CurSection != CPSections[i].S) { 1797 OutStreamer->SwitchSection(CPSections[i].S); 1798 EmitAlignment(Align(CPSections[i].Alignment)); 1799 CurSection = CPSections[i].S; 1800 Offset = 0; 1801 } 1802 1803 MachineConstantPoolEntry CPE = CP[CPI]; 1804 1805 // Emit inter-object padding for alignment. 1806 unsigned AlignMask = CPE.getAlignment() - 1; 1807 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1808 OutStreamer->EmitZeros(NewOffset - Offset); 1809 1810 Type *Ty = CPE.getType(); 1811 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1812 1813 OutStreamer->EmitLabel(Sym); 1814 if (CPE.isMachineConstantPoolEntry()) 1815 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1816 else 1817 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1818 } 1819 } 1820 } 1821 1822 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 1823 /// by the current function to the current output stream. 1824 void AsmPrinter::EmitJumpTableInfo() { 1825 const DataLayout &DL = MF->getDataLayout(); 1826 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1827 if (!MJTI) return; 1828 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1829 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1830 if (JT.empty()) return; 1831 1832 // Pick the directive to use to print the jump table entries, and switch to 1833 // the appropriate section. 1834 const Function &F = MF->getFunction(); 1835 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1836 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1837 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1838 F); 1839 if (JTInDiffSection) { 1840 // Drop it in the readonly section. 1841 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM); 1842 OutStreamer->SwitchSection(ReadOnlySection); 1843 } 1844 1845 EmitAlignment(Align(MJTI->getEntryAlignment(DL))); 1846 1847 // Jump tables in code sections are marked with a data_region directive 1848 // where that's supported. 1849 if (!JTInDiffSection) 1850 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32); 1851 1852 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1853 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1854 1855 // If this jump table was deleted, ignore it. 1856 if (JTBBs.empty()) continue; 1857 1858 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1859 /// emit a .set directive for each unique entry. 1860 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1861 MAI->doesSetDirectiveSuppressReloc()) { 1862 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1863 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1864 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1865 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1866 const MachineBasicBlock *MBB = JTBBs[ii]; 1867 if (!EmittedSets.insert(MBB).second) 1868 continue; 1869 1870 // .set LJTSet, LBB32-base 1871 const MCExpr *LHS = 1872 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1873 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1874 MCBinaryExpr::createSub(LHS, Base, 1875 OutContext)); 1876 } 1877 } 1878 1879 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1880 // before each jump table. The first label is never referenced, but tells 1881 // the assembler and linker the extents of the jump table object. The 1882 // second label is actually referenced by the code. 1883 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1884 // FIXME: This doesn't have to have any specific name, just any randomly 1885 // named and numbered local label started with 'l' would work. Simplify 1886 // GetJTISymbol. 1887 OutStreamer->EmitLabel(GetJTISymbol(JTI, true)); 1888 1889 MCSymbol* JTISymbol = GetJTISymbol(JTI); 1890 if (TM.getTargetTriple().isOSBinFormatXCOFF()) { 1891 cast<MCSymbolXCOFF>(JTISymbol)->setContainingCsect( 1892 cast<MCSectionXCOFF>(TLOF.getSectionForJumpTable(F, TM))); 1893 } 1894 OutStreamer->EmitLabel(JTISymbol); 1895 1896 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1897 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1898 } 1899 if (!JTInDiffSection) 1900 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 1901 } 1902 1903 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1904 /// current stream. 1905 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1906 const MachineBasicBlock *MBB, 1907 unsigned UID) const { 1908 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1909 const MCExpr *Value = nullptr; 1910 switch (MJTI->getEntryKind()) { 1911 case MachineJumpTableInfo::EK_Inline: 1912 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1913 case MachineJumpTableInfo::EK_Custom32: 1914 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1915 MJTI, MBB, UID, OutContext); 1916 break; 1917 case MachineJumpTableInfo::EK_BlockAddress: 1918 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1919 // .word LBB123 1920 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1921 break; 1922 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1923 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1924 // with a relocation as gp-relative, e.g.: 1925 // .gprel32 LBB123 1926 MCSymbol *MBBSym = MBB->getSymbol(); 1927 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1928 return; 1929 } 1930 1931 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1932 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1933 // with a relocation as gp-relative, e.g.: 1934 // .gpdword LBB123 1935 MCSymbol *MBBSym = MBB->getSymbol(); 1936 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1937 return; 1938 } 1939 1940 case MachineJumpTableInfo::EK_LabelDifference32: { 1941 // Each entry is the address of the block minus the address of the jump 1942 // table. This is used for PIC jump tables where gprel32 is not supported. 1943 // e.g.: 1944 // .word LBB123 - LJTI1_2 1945 // If the .set directive avoids relocations, this is emitted as: 1946 // .set L4_5_set_123, LBB123 - LJTI1_2 1947 // .word L4_5_set_123 1948 if (MAI->doesSetDirectiveSuppressReloc()) { 1949 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 1950 OutContext); 1951 break; 1952 } 1953 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1954 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1955 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 1956 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 1957 break; 1958 } 1959 } 1960 1961 assert(Value && "Unknown entry kind!"); 1962 1963 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 1964 OutStreamer->EmitValue(Value, EntrySize); 1965 } 1966 1967 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1968 /// special global used by LLVM. If so, emit it and return true, otherwise 1969 /// do nothing and return false. 1970 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1971 if (GV->getName() == "llvm.used") { 1972 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1973 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1974 return true; 1975 } 1976 1977 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1978 if (GV->getSection() == "llvm.metadata" || 1979 GV->hasAvailableExternallyLinkage()) 1980 return true; 1981 1982 if (!GV->hasAppendingLinkage()) return false; 1983 1984 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1985 1986 if (GV->getName() == "llvm.global_ctors") { 1987 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1988 /* isCtor */ true); 1989 1990 return true; 1991 } 1992 1993 if (GV->getName() == "llvm.global_dtors") { 1994 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1995 /* isCtor */ false); 1996 1997 return true; 1998 } 1999 2000 report_fatal_error("unknown special variable"); 2001 } 2002 2003 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 2004 /// global in the specified llvm.used list. 2005 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 2006 // Should be an array of 'i8*'. 2007 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 2008 const GlobalValue *GV = 2009 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 2010 if (GV) 2011 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 2012 } 2013 } 2014 2015 namespace { 2016 2017 struct Structor { 2018 int Priority = 0; 2019 Constant *Func = nullptr; 2020 GlobalValue *ComdatKey = nullptr; 2021 2022 Structor() = default; 2023 }; 2024 2025 } // end anonymous namespace 2026 2027 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 2028 /// priority. 2029 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List, 2030 bool isCtor) { 2031 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the 2032 // init priority. 2033 if (!isa<ConstantArray>(List)) return; 2034 2035 // Sanity check the structors list. 2036 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 2037 if (!InitList) return; // Not an array! 2038 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 2039 if (!ETy || ETy->getNumElements() != 3 || 2040 !isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 2041 !isa<PointerType>(ETy->getTypeAtIndex(1U)) || 2042 !isa<PointerType>(ETy->getTypeAtIndex(2U))) 2043 return; // Not (int, ptr, ptr). 2044 2045 // Gather the structors in a form that's convenient for sorting by priority. 2046 SmallVector<Structor, 8> Structors; 2047 for (Value *O : InitList->operands()) { 2048 ConstantStruct *CS = dyn_cast<ConstantStruct>(O); 2049 if (!CS) continue; // Malformed. 2050 if (CS->getOperand(1)->isNullValue()) 2051 break; // Found a null terminator, skip the rest. 2052 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 2053 if (!Priority) continue; // Malformed. 2054 Structors.push_back(Structor()); 2055 Structor &S = Structors.back(); 2056 S.Priority = Priority->getLimitedValue(65535); 2057 S.Func = CS->getOperand(1); 2058 if (!CS->getOperand(2)->isNullValue()) 2059 S.ComdatKey = 2060 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 2061 } 2062 2063 // Emit the function pointers in the target-specific order 2064 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) { 2065 return L.Priority < R.Priority; 2066 }); 2067 const Align Align = DL.getPointerPrefAlignment(); 2068 for (Structor &S : Structors) { 2069 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 2070 const MCSymbol *KeySym = nullptr; 2071 if (GlobalValue *GV = S.ComdatKey) { 2072 if (GV->isDeclarationForLinker()) 2073 // If the associated variable is not defined in this module 2074 // (it might be available_externally, or have been an 2075 // available_externally definition that was dropped by the 2076 // EliminateAvailableExternally pass), some other TU 2077 // will provide its dynamic initializer. 2078 continue; 2079 2080 KeySym = getSymbol(GV); 2081 } 2082 MCSection *OutputSection = 2083 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 2084 : Obj.getStaticDtorSection(S.Priority, KeySym)); 2085 OutStreamer->SwitchSection(OutputSection); 2086 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 2087 EmitAlignment(Align); 2088 EmitXXStructor(DL, S.Func); 2089 } 2090 } 2091 2092 void AsmPrinter::EmitModuleIdents(Module &M) { 2093 if (!MAI->hasIdentDirective()) 2094 return; 2095 2096 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 2097 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2098 const MDNode *N = NMD->getOperand(i); 2099 assert(N->getNumOperands() == 1 && 2100 "llvm.ident metadata entry can have only one operand"); 2101 const MDString *S = cast<MDString>(N->getOperand(0)); 2102 OutStreamer->EmitIdent(S->getString()); 2103 } 2104 } 2105 } 2106 2107 void AsmPrinter::EmitModuleCommandLines(Module &M) { 2108 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines(); 2109 if (!CommandLine) 2110 return; 2111 2112 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline"); 2113 if (!NMD || !NMD->getNumOperands()) 2114 return; 2115 2116 OutStreamer->PushSection(); 2117 OutStreamer->SwitchSection(CommandLine); 2118 OutStreamer->EmitZeros(1); 2119 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2120 const MDNode *N = NMD->getOperand(i); 2121 assert(N->getNumOperands() == 1 && 2122 "llvm.commandline metadata entry can have only one operand"); 2123 const MDString *S = cast<MDString>(N->getOperand(0)); 2124 OutStreamer->EmitBytes(S->getString()); 2125 OutStreamer->EmitZeros(1); 2126 } 2127 OutStreamer->PopSection(); 2128 } 2129 2130 //===--------------------------------------------------------------------===// 2131 // Emission and print routines 2132 // 2133 2134 /// Emit a byte directive and value. 2135 /// 2136 void AsmPrinter::emitInt8(int Value) const { 2137 OutStreamer->EmitIntValue(Value, 1); 2138 } 2139 2140 /// Emit a short directive and value. 2141 void AsmPrinter::emitInt16(int Value) const { 2142 OutStreamer->EmitIntValue(Value, 2); 2143 } 2144 2145 /// Emit a long directive and value. 2146 void AsmPrinter::emitInt32(int Value) const { 2147 OutStreamer->EmitIntValue(Value, 4); 2148 } 2149 2150 /// Emit a long long directive and value. 2151 void AsmPrinter::emitInt64(uint64_t Value) const { 2152 OutStreamer->EmitIntValue(Value, 8); 2153 } 2154 2155 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 2156 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 2157 /// .set if it avoids relocations. 2158 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 2159 unsigned Size) const { 2160 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 2161 } 2162 2163 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 2164 /// where the size in bytes of the directive is specified by Size and Label 2165 /// specifies the label. This implicitly uses .set if it is available. 2166 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 2167 unsigned Size, 2168 bool IsSectionRelative) const { 2169 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 2170 OutStreamer->EmitCOFFSecRel32(Label, Offset); 2171 if (Size > 4) 2172 OutStreamer->EmitZeros(Size - 4); 2173 return; 2174 } 2175 2176 // Emit Label+Offset (or just Label if Offset is zero) 2177 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 2178 if (Offset) 2179 Expr = MCBinaryExpr::createAdd( 2180 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 2181 2182 OutStreamer->EmitValue(Expr, Size); 2183 } 2184 2185 //===----------------------------------------------------------------------===// 2186 2187 // EmitAlignment - Emit an alignment directive to the specified power of 2188 // two boundary. If a global value is specified, and if that global has 2189 // an explicit alignment requested, it will override the alignment request 2190 // if required for correctness. 2191 void AsmPrinter::EmitAlignment(Align Alignment, const GlobalObject *GV) const { 2192 if (GV) 2193 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment); 2194 2195 if (Alignment == Align::None()) 2196 return; // 1-byte aligned: no need to emit alignment. 2197 2198 if (getCurrentSection()->getKind().isText()) 2199 OutStreamer->EmitCodeAlignment(Alignment.value()); 2200 else 2201 OutStreamer->EmitValueToAlignment(Alignment.value()); 2202 } 2203 2204 //===----------------------------------------------------------------------===// 2205 // Constant emission. 2206 //===----------------------------------------------------------------------===// 2207 2208 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 2209 MCContext &Ctx = OutContext; 2210 2211 if (CV->isNullValue() || isa<UndefValue>(CV)) 2212 return MCConstantExpr::create(0, Ctx); 2213 2214 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 2215 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 2216 2217 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 2218 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 2219 2220 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 2221 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 2222 2223 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 2224 if (!CE) { 2225 llvm_unreachable("Unknown constant value to lower!"); 2226 } 2227 2228 switch (CE->getOpcode()) { 2229 default: 2230 // If the code isn't optimized, there may be outstanding folding 2231 // opportunities. Attempt to fold the expression using DataLayout as a 2232 // last resort before giving up. 2233 if (Constant *C = ConstantFoldConstant(CE, getDataLayout())) 2234 if (C != CE) 2235 return lowerConstant(C); 2236 2237 // Otherwise report the problem to the user. 2238 { 2239 std::string S; 2240 raw_string_ostream OS(S); 2241 OS << "Unsupported expression in static initializer: "; 2242 CE->printAsOperand(OS, /*PrintType=*/false, 2243 !MF ? nullptr : MF->getFunction().getParent()); 2244 report_fatal_error(OS.str()); 2245 } 2246 case Instruction::GetElementPtr: { 2247 // Generate a symbolic expression for the byte address 2248 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 2249 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 2250 2251 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 2252 if (!OffsetAI) 2253 return Base; 2254 2255 int64_t Offset = OffsetAI.getSExtValue(); 2256 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 2257 Ctx); 2258 } 2259 2260 case Instruction::Trunc: 2261 // We emit the value and depend on the assembler to truncate the generated 2262 // expression properly. This is important for differences between 2263 // blockaddress labels. Since the two labels are in the same function, it 2264 // is reasonable to treat their delta as a 32-bit value. 2265 LLVM_FALLTHROUGH; 2266 case Instruction::BitCast: 2267 return lowerConstant(CE->getOperand(0)); 2268 2269 case Instruction::IntToPtr: { 2270 const DataLayout &DL = getDataLayout(); 2271 2272 // Handle casts to pointers by changing them into casts to the appropriate 2273 // integer type. This promotes constant folding and simplifies this code. 2274 Constant *Op = CE->getOperand(0); 2275 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 2276 false/*ZExt*/); 2277 return lowerConstant(Op); 2278 } 2279 2280 case Instruction::PtrToInt: { 2281 const DataLayout &DL = getDataLayout(); 2282 2283 // Support only foldable casts to/from pointers that can be eliminated by 2284 // changing the pointer to the appropriately sized integer type. 2285 Constant *Op = CE->getOperand(0); 2286 Type *Ty = CE->getType(); 2287 2288 const MCExpr *OpExpr = lowerConstant(Op); 2289 2290 // We can emit the pointer value into this slot if the slot is an 2291 // integer slot equal to the size of the pointer. 2292 // 2293 // If the pointer is larger than the resultant integer, then 2294 // as with Trunc just depend on the assembler to truncate it. 2295 if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType())) 2296 return OpExpr; 2297 2298 // Otherwise the pointer is smaller than the resultant integer, mask off 2299 // the high bits so we are sure to get a proper truncation if the input is 2300 // a constant expr. 2301 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 2302 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 2303 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 2304 } 2305 2306 case Instruction::Sub: { 2307 GlobalValue *LHSGV; 2308 APInt LHSOffset; 2309 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 2310 getDataLayout())) { 2311 GlobalValue *RHSGV; 2312 APInt RHSOffset; 2313 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 2314 getDataLayout())) { 2315 const MCExpr *RelocExpr = 2316 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 2317 if (!RelocExpr) 2318 RelocExpr = MCBinaryExpr::createSub( 2319 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 2320 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 2321 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 2322 if (Addend != 0) 2323 RelocExpr = MCBinaryExpr::createAdd( 2324 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 2325 return RelocExpr; 2326 } 2327 } 2328 } 2329 // else fallthrough 2330 LLVM_FALLTHROUGH; 2331 2332 // The MC library also has a right-shift operator, but it isn't consistently 2333 // signed or unsigned between different targets. 2334 case Instruction::Add: 2335 case Instruction::Mul: 2336 case Instruction::SDiv: 2337 case Instruction::SRem: 2338 case Instruction::Shl: 2339 case Instruction::And: 2340 case Instruction::Or: 2341 case Instruction::Xor: { 2342 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2343 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2344 switch (CE->getOpcode()) { 2345 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2346 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2347 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2348 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2349 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2350 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2351 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2352 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2353 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2354 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2355 } 2356 } 2357 } 2358 } 2359 2360 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2361 AsmPrinter &AP, 2362 const Constant *BaseCV = nullptr, 2363 uint64_t Offset = 0); 2364 2365 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2366 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP); 2367 2368 /// isRepeatedByteSequence - Determine whether the given value is 2369 /// composed of a repeated sequence of identical bytes and return the 2370 /// byte value. If it is not a repeated sequence, return -1. 2371 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2372 StringRef Data = V->getRawDataValues(); 2373 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2374 char C = Data[0]; 2375 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2376 if (Data[i] != C) return -1; 2377 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2378 } 2379 2380 /// isRepeatedByteSequence - Determine whether the given value is 2381 /// composed of a repeated sequence of identical bytes and return the 2382 /// byte value. If it is not a repeated sequence, return -1. 2383 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2384 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2385 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2386 assert(Size % 8 == 0); 2387 2388 // Extend the element to take zero padding into account. 2389 APInt Value = CI->getValue().zextOrSelf(Size); 2390 if (!Value.isSplat(8)) 2391 return -1; 2392 2393 return Value.zextOrTrunc(8).getZExtValue(); 2394 } 2395 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2396 // Make sure all array elements are sequences of the same repeated 2397 // byte. 2398 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2399 Constant *Op0 = CA->getOperand(0); 2400 int Byte = isRepeatedByteSequence(Op0, DL); 2401 if (Byte == -1) 2402 return -1; 2403 2404 // All array elements must be equal. 2405 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2406 if (CA->getOperand(i) != Op0) 2407 return -1; 2408 return Byte; 2409 } 2410 2411 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2412 return isRepeatedByteSequence(CDS); 2413 2414 return -1; 2415 } 2416 2417 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2418 const ConstantDataSequential *CDS, 2419 AsmPrinter &AP) { 2420 // See if we can aggregate this into a .fill, if so, emit it as such. 2421 int Value = isRepeatedByteSequence(CDS, DL); 2422 if (Value != -1) { 2423 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2424 // Don't emit a 1-byte object as a .fill. 2425 if (Bytes > 1) 2426 return AP.OutStreamer->emitFill(Bytes, Value); 2427 } 2428 2429 // If this can be emitted with .ascii/.asciz, emit it as such. 2430 if (CDS->isString()) 2431 return AP.OutStreamer->EmitBytes(CDS->getAsString()); 2432 2433 // Otherwise, emit the values in successive locations. 2434 unsigned ElementByteSize = CDS->getElementByteSize(); 2435 if (isa<IntegerType>(CDS->getElementType())) { 2436 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2437 if (AP.isVerbose()) 2438 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2439 CDS->getElementAsInteger(i)); 2440 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i), 2441 ElementByteSize); 2442 } 2443 } else { 2444 Type *ET = CDS->getElementType(); 2445 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2446 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP); 2447 } 2448 2449 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2450 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 2451 CDS->getNumElements(); 2452 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!"); 2453 if (unsigned Padding = Size - EmittedSize) 2454 AP.OutStreamer->EmitZeros(Padding); 2455 } 2456 2457 static void emitGlobalConstantArray(const DataLayout &DL, 2458 const ConstantArray *CA, AsmPrinter &AP, 2459 const Constant *BaseCV, uint64_t Offset) { 2460 // See if we can aggregate some values. Make sure it can be 2461 // represented as a series of bytes of the constant value. 2462 int Value = isRepeatedByteSequence(CA, DL); 2463 2464 if (Value != -1) { 2465 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2466 AP.OutStreamer->emitFill(Bytes, Value); 2467 } 2468 else { 2469 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2470 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2471 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2472 } 2473 } 2474 } 2475 2476 static void emitGlobalConstantVector(const DataLayout &DL, 2477 const ConstantVector *CV, AsmPrinter &AP) { 2478 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2479 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2480 2481 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2482 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2483 CV->getType()->getNumElements(); 2484 if (unsigned Padding = Size - EmittedSize) 2485 AP.OutStreamer->EmitZeros(Padding); 2486 } 2487 2488 static void emitGlobalConstantStruct(const DataLayout &DL, 2489 const ConstantStruct *CS, AsmPrinter &AP, 2490 const Constant *BaseCV, uint64_t Offset) { 2491 // Print the fields in successive locations. Pad to align if needed! 2492 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2493 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2494 uint64_t SizeSoFar = 0; 2495 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2496 const Constant *Field = CS->getOperand(i); 2497 2498 // Print the actual field value. 2499 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2500 2501 // Check if padding is needed and insert one or more 0s. 2502 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2503 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2504 - Layout->getElementOffset(i)) - FieldSize; 2505 SizeSoFar += FieldSize + PadSize; 2506 2507 // Insert padding - this may include padding to increase the size of the 2508 // current field up to the ABI size (if the struct is not packed) as well 2509 // as padding to ensure that the next field starts at the right offset. 2510 AP.OutStreamer->EmitZeros(PadSize); 2511 } 2512 assert(SizeSoFar == Layout->getSizeInBytes() && 2513 "Layout of constant struct may be incorrect!"); 2514 } 2515 2516 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) { 2517 assert(ET && "Unknown float type"); 2518 APInt API = APF.bitcastToAPInt(); 2519 2520 // First print a comment with what we think the original floating-point value 2521 // should have been. 2522 if (AP.isVerbose()) { 2523 SmallString<8> StrVal; 2524 APF.toString(StrVal); 2525 ET->print(AP.OutStreamer->GetCommentOS()); 2526 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2527 } 2528 2529 // Now iterate through the APInt chunks, emitting them in endian-correct 2530 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2531 // floats). 2532 unsigned NumBytes = API.getBitWidth() / 8; 2533 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2534 const uint64_t *p = API.getRawData(); 2535 2536 // PPC's long double has odd notions of endianness compared to how LLVM 2537 // handles it: p[0] goes first for *big* endian on PPC. 2538 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) { 2539 int Chunk = API.getNumWords() - 1; 2540 2541 if (TrailingBytes) 2542 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes); 2543 2544 for (; Chunk >= 0; --Chunk) 2545 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2546 } else { 2547 unsigned Chunk; 2548 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2549 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2550 2551 if (TrailingBytes) 2552 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes); 2553 } 2554 2555 // Emit the tail padding for the long double. 2556 const DataLayout &DL = AP.getDataLayout(); 2557 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET)); 2558 } 2559 2560 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2561 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP); 2562 } 2563 2564 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2565 const DataLayout &DL = AP.getDataLayout(); 2566 unsigned BitWidth = CI->getBitWidth(); 2567 2568 // Copy the value as we may massage the layout for constants whose bit width 2569 // is not a multiple of 64-bits. 2570 APInt Realigned(CI->getValue()); 2571 uint64_t ExtraBits = 0; 2572 unsigned ExtraBitsSize = BitWidth & 63; 2573 2574 if (ExtraBitsSize) { 2575 // The bit width of the data is not a multiple of 64-bits. 2576 // The extra bits are expected to be at the end of the chunk of the memory. 2577 // Little endian: 2578 // * Nothing to be done, just record the extra bits to emit. 2579 // Big endian: 2580 // * Record the extra bits to emit. 2581 // * Realign the raw data to emit the chunks of 64-bits. 2582 if (DL.isBigEndian()) { 2583 // Basically the structure of the raw data is a chunk of 64-bits cells: 2584 // 0 1 BitWidth / 64 2585 // [chunk1][chunk2] ... [chunkN]. 2586 // The most significant chunk is chunkN and it should be emitted first. 2587 // However, due to the alignment issue chunkN contains useless bits. 2588 // Realign the chunks so that they contain only useless information: 2589 // ExtraBits 0 1 (BitWidth / 64) - 1 2590 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2591 ExtraBits = Realigned.getRawData()[0] & 2592 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2593 Realigned.lshrInPlace(ExtraBitsSize); 2594 } else 2595 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2596 } 2597 2598 // We don't expect assemblers to support integer data directives 2599 // for more than 64 bits, so we emit the data in at most 64-bit 2600 // quantities at a time. 2601 const uint64_t *RawData = Realigned.getRawData(); 2602 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2603 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2604 AP.OutStreamer->EmitIntValue(Val, 8); 2605 } 2606 2607 if (ExtraBitsSize) { 2608 // Emit the extra bits after the 64-bits chunks. 2609 2610 // Emit a directive that fills the expected size. 2611 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType()); 2612 Size -= (BitWidth / 64) * 8; 2613 assert(Size && Size * 8 >= ExtraBitsSize && 2614 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2615 == ExtraBits && "Directive too small for extra bits."); 2616 AP.OutStreamer->EmitIntValue(ExtraBits, Size); 2617 } 2618 } 2619 2620 /// Transform a not absolute MCExpr containing a reference to a GOT 2621 /// equivalent global, by a target specific GOT pc relative access to the 2622 /// final symbol. 2623 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2624 const Constant *BaseCst, 2625 uint64_t Offset) { 2626 // The global @foo below illustrates a global that uses a got equivalent. 2627 // 2628 // @bar = global i32 42 2629 // @gotequiv = private unnamed_addr constant i32* @bar 2630 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2631 // i64 ptrtoint (i32* @foo to i64)) 2632 // to i32) 2633 // 2634 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2635 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2636 // form: 2637 // 2638 // foo = cstexpr, where 2639 // cstexpr := <gotequiv> - "." + <cst> 2640 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2641 // 2642 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2643 // 2644 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2645 // gotpcrelcst := <offset from @foo base> + <cst> 2646 MCValue MV; 2647 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2648 return; 2649 const MCSymbolRefExpr *SymA = MV.getSymA(); 2650 if (!SymA) 2651 return; 2652 2653 // Check that GOT equivalent symbol is cached. 2654 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2655 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2656 return; 2657 2658 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2659 if (!BaseGV) 2660 return; 2661 2662 // Check for a valid base symbol 2663 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2664 const MCSymbolRefExpr *SymB = MV.getSymB(); 2665 2666 if (!SymB || BaseSym != &SymB->getSymbol()) 2667 return; 2668 2669 // Make sure to match: 2670 // 2671 // gotpcrelcst := <offset from @foo base> + <cst> 2672 // 2673 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2674 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2675 // if the target knows how to encode it. 2676 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2677 if (GOTPCRelCst < 0) 2678 return; 2679 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2680 return; 2681 2682 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2683 // 2684 // bar: 2685 // .long 42 2686 // gotequiv: 2687 // .quad bar 2688 // foo: 2689 // .long gotequiv - "." + <cst> 2690 // 2691 // is replaced by the target specific equivalent to: 2692 // 2693 // bar: 2694 // .long 42 2695 // foo: 2696 // .long bar@GOTPCREL+<gotpcrelcst> 2697 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2698 const GlobalVariable *GV = Result.first; 2699 int NumUses = (int)Result.second; 2700 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2701 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2702 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2703 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2704 2705 // Update GOT equivalent usage information 2706 --NumUses; 2707 if (NumUses >= 0) 2708 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2709 } 2710 2711 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2712 AsmPrinter &AP, const Constant *BaseCV, 2713 uint64_t Offset) { 2714 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2715 2716 // Globals with sub-elements such as combinations of arrays and structs 2717 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2718 // constant symbol base and the current position with BaseCV and Offset. 2719 if (!BaseCV && CV->hasOneUse()) 2720 BaseCV = dyn_cast<Constant>(CV->user_back()); 2721 2722 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2723 return AP.OutStreamer->EmitZeros(Size); 2724 2725 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2726 switch (Size) { 2727 case 1: 2728 case 2: 2729 case 4: 2730 case 8: 2731 if (AP.isVerbose()) 2732 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2733 CI->getZExtValue()); 2734 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size); 2735 return; 2736 default: 2737 emitGlobalConstantLargeInt(CI, AP); 2738 return; 2739 } 2740 } 2741 2742 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2743 return emitGlobalConstantFP(CFP, AP); 2744 2745 if (isa<ConstantPointerNull>(CV)) { 2746 AP.OutStreamer->EmitIntValue(0, Size); 2747 return; 2748 } 2749 2750 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2751 return emitGlobalConstantDataSequential(DL, CDS, AP); 2752 2753 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2754 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2755 2756 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2757 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2758 2759 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2760 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2761 // vectors). 2762 if (CE->getOpcode() == Instruction::BitCast) 2763 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2764 2765 if (Size > 8) { 2766 // If the constant expression's size is greater than 64-bits, then we have 2767 // to emit the value in chunks. Try to constant fold the value and emit it 2768 // that way. 2769 Constant *New = ConstantFoldConstant(CE, DL); 2770 if (New && New != CE) 2771 return emitGlobalConstantImpl(DL, New, AP); 2772 } 2773 } 2774 2775 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2776 return emitGlobalConstantVector(DL, V, AP); 2777 2778 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2779 // thread the streamer with EmitValue. 2780 const MCExpr *ME = AP.lowerConstant(CV); 2781 2782 // Since lowerConstant already folded and got rid of all IR pointer and 2783 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2784 // directly. 2785 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2786 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2787 2788 AP.OutStreamer->EmitValue(ME, Size); 2789 } 2790 2791 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2792 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2793 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2794 if (Size) 2795 emitGlobalConstantImpl(DL, CV, *this); 2796 else if (MAI->hasSubsectionsViaSymbols()) { 2797 // If the global has zero size, emit a single byte so that two labels don't 2798 // look like they are at the same location. 2799 OutStreamer->EmitIntValue(0, 1); 2800 } 2801 } 2802 2803 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2804 // Target doesn't support this yet! 2805 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2806 } 2807 2808 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2809 if (Offset > 0) 2810 OS << '+' << Offset; 2811 else if (Offset < 0) 2812 OS << Offset; 2813 } 2814 2815 void AsmPrinter::emitNops(unsigned N) { 2816 MCInst Nop; 2817 MF->getSubtarget().getInstrInfo()->getNoop(Nop); 2818 for (; N; --N) 2819 EmitToStreamer(*OutStreamer, Nop); 2820 } 2821 2822 //===----------------------------------------------------------------------===// 2823 // Symbol Lowering Routines. 2824 //===----------------------------------------------------------------------===// 2825 2826 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2827 return OutContext.createTempSymbol(Name, true); 2828 } 2829 2830 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2831 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2832 } 2833 2834 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2835 return MMI->getAddrLabelSymbol(BB); 2836 } 2837 2838 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2839 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2840 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) { 2841 const MachineConstantPoolEntry &CPE = 2842 MF->getConstantPool()->getConstants()[CPID]; 2843 if (!CPE.isMachineConstantPoolEntry()) { 2844 const DataLayout &DL = MF->getDataLayout(); 2845 SectionKind Kind = CPE.getSectionKind(&DL); 2846 const Constant *C = CPE.Val.ConstVal; 2847 unsigned Align = CPE.Alignment; 2848 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>( 2849 getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) { 2850 if (MCSymbol *Sym = S->getCOMDATSymbol()) { 2851 if (Sym->isUndefined()) 2852 OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global); 2853 return Sym; 2854 } 2855 } 2856 } 2857 } 2858 2859 const DataLayout &DL = getDataLayout(); 2860 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2861 "CPI" + Twine(getFunctionNumber()) + "_" + 2862 Twine(CPID)); 2863 } 2864 2865 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2866 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2867 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2868 } 2869 2870 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2871 /// FIXME: privatize to AsmPrinter. 2872 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2873 const DataLayout &DL = getDataLayout(); 2874 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2875 Twine(getFunctionNumber()) + "_" + 2876 Twine(UID) + "_set_" + Twine(MBBID)); 2877 } 2878 2879 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2880 StringRef Suffix) const { 2881 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 2882 } 2883 2884 /// Return the MCSymbol for the specified ExternalSymbol. 2885 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2886 SmallString<60> NameStr; 2887 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2888 return OutContext.getOrCreateSymbol(NameStr); 2889 } 2890 2891 /// PrintParentLoopComment - Print comments about parent loops of this one. 2892 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2893 unsigned FunctionNumber) { 2894 if (!Loop) return; 2895 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2896 OS.indent(Loop->getLoopDepth()*2) 2897 << "Parent Loop BB" << FunctionNumber << "_" 2898 << Loop->getHeader()->getNumber() 2899 << " Depth=" << Loop->getLoopDepth() << '\n'; 2900 } 2901 2902 /// PrintChildLoopComment - Print comments about child loops within 2903 /// the loop for this basic block, with nesting. 2904 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2905 unsigned FunctionNumber) { 2906 // Add child loop information 2907 for (const MachineLoop *CL : *Loop) { 2908 OS.indent(CL->getLoopDepth()*2) 2909 << "Child Loop BB" << FunctionNumber << "_" 2910 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2911 << '\n'; 2912 PrintChildLoopComment(OS, CL, FunctionNumber); 2913 } 2914 } 2915 2916 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2917 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2918 const MachineLoopInfo *LI, 2919 const AsmPrinter &AP) { 2920 // Add loop depth information 2921 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2922 if (!Loop) return; 2923 2924 MachineBasicBlock *Header = Loop->getHeader(); 2925 assert(Header && "No header for loop"); 2926 2927 // If this block is not a loop header, just print out what is the loop header 2928 // and return. 2929 if (Header != &MBB) { 2930 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2931 Twine(AP.getFunctionNumber())+"_" + 2932 Twine(Loop->getHeader()->getNumber())+ 2933 " Depth="+Twine(Loop->getLoopDepth())); 2934 return; 2935 } 2936 2937 // Otherwise, it is a loop header. Print out information about child and 2938 // parent loops. 2939 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2940 2941 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2942 2943 OS << "=>"; 2944 OS.indent(Loop->getLoopDepth()*2-2); 2945 2946 OS << "This "; 2947 if (Loop->empty()) 2948 OS << "Inner "; 2949 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2950 2951 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2952 } 2953 2954 /// EmitBasicBlockStart - This method prints the label for the specified 2955 /// MachineBasicBlock, an alignment (if present) and a comment describing 2956 /// it if appropriate. 2957 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) { 2958 // End the previous funclet and start a new one. 2959 if (MBB.isEHFuncletEntry()) { 2960 for (const HandlerInfo &HI : Handlers) { 2961 HI.Handler->endFunclet(); 2962 HI.Handler->beginFunclet(MBB); 2963 } 2964 } 2965 2966 // Emit an alignment directive for this block, if needed. 2967 const Align Alignment = MBB.getAlignment(); 2968 if (Alignment != Align::None()) 2969 EmitAlignment(Alignment); 2970 2971 // If the block has its address taken, emit any labels that were used to 2972 // reference the block. It is possible that there is more than one label 2973 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2974 // the references were generated. 2975 if (MBB.hasAddressTaken()) { 2976 const BasicBlock *BB = MBB.getBasicBlock(); 2977 if (isVerbose()) 2978 OutStreamer->AddComment("Block address taken"); 2979 2980 // MBBs can have their address taken as part of CodeGen without having 2981 // their corresponding BB's address taken in IR 2982 if (BB->hasAddressTaken()) 2983 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 2984 OutStreamer->EmitLabel(Sym); 2985 } 2986 2987 // Print some verbose block comments. 2988 if (isVerbose()) { 2989 if (const BasicBlock *BB = MBB.getBasicBlock()) { 2990 if (BB->hasName()) { 2991 BB->printAsOperand(OutStreamer->GetCommentOS(), 2992 /*PrintType=*/false, BB->getModule()); 2993 OutStreamer->GetCommentOS() << '\n'; 2994 } 2995 } 2996 2997 assert(MLI != nullptr && "MachineLoopInfo should has been computed"); 2998 emitBasicBlockLoopComments(MBB, MLI, *this); 2999 } 3000 3001 // Print the main label for the block. 3002 if (MBB.pred_empty() || 3003 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry() && 3004 !MBB.hasLabelMustBeEmitted())) { 3005 if (isVerbose()) { 3006 // NOTE: Want this comment at start of line, don't emit with AddComment. 3007 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":", 3008 false); 3009 } 3010 } else { 3011 if (isVerbose() && MBB.hasLabelMustBeEmitted()) 3012 OutStreamer->AddComment("Label of block must be emitted"); 3013 OutStreamer->EmitLabel(MBB.getSymbol()); 3014 } 3015 } 3016 3017 void AsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {} 3018 3019 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 3020 bool IsDefinition) const { 3021 MCSymbolAttr Attr = MCSA_Invalid; 3022 3023 switch (Visibility) { 3024 default: break; 3025 case GlobalValue::HiddenVisibility: 3026 if (IsDefinition) 3027 Attr = MAI->getHiddenVisibilityAttr(); 3028 else 3029 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 3030 break; 3031 case GlobalValue::ProtectedVisibility: 3032 Attr = MAI->getProtectedVisibilityAttr(); 3033 break; 3034 } 3035 3036 if (Attr != MCSA_Invalid) 3037 OutStreamer->EmitSymbolAttribute(Sym, Attr); 3038 } 3039 3040 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 3041 /// exactly one predecessor and the control transfer mechanism between 3042 /// the predecessor and this block is a fall-through. 3043 bool AsmPrinter:: 3044 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 3045 // If this is a landing pad, it isn't a fall through. If it has no preds, 3046 // then nothing falls through to it. 3047 if (MBB->isEHPad() || MBB->pred_empty()) 3048 return false; 3049 3050 // If there isn't exactly one predecessor, it can't be a fall through. 3051 if (MBB->pred_size() > 1) 3052 return false; 3053 3054 // The predecessor has to be immediately before this block. 3055 MachineBasicBlock *Pred = *MBB->pred_begin(); 3056 if (!Pred->isLayoutSuccessor(MBB)) 3057 return false; 3058 3059 // If the block is completely empty, then it definitely does fall through. 3060 if (Pred->empty()) 3061 return true; 3062 3063 // Check the terminators in the previous blocks 3064 for (const auto &MI : Pred->terminators()) { 3065 // If it is not a simple branch, we are in a table somewhere. 3066 if (!MI.isBranch() || MI.isIndirectBranch()) 3067 return false; 3068 3069 // If we are the operands of one of the branches, this is not a fall 3070 // through. Note that targets with delay slots will usually bundle 3071 // terminators with the delay slot instruction. 3072 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 3073 if (OP->isJTI()) 3074 return false; 3075 if (OP->isMBB() && OP->getMBB() == MBB) 3076 return false; 3077 } 3078 } 3079 3080 return true; 3081 } 3082 3083 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 3084 if (!S.usesMetadata()) 3085 return nullptr; 3086 3087 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 3088 gcp_map_type::iterator GCPI = GCMap.find(&S); 3089 if (GCPI != GCMap.end()) 3090 return GCPI->second.get(); 3091 3092 auto Name = S.getName(); 3093 3094 for (GCMetadataPrinterRegistry::iterator 3095 I = GCMetadataPrinterRegistry::begin(), 3096 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 3097 if (Name == I->getName()) { 3098 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 3099 GMP->S = &S; 3100 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 3101 return IterBool.first->second.get(); 3102 } 3103 3104 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 3105 } 3106 3107 void AsmPrinter::emitStackMaps(StackMaps &SM) { 3108 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 3109 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 3110 bool NeedsDefault = false; 3111 if (MI->begin() == MI->end()) 3112 // No GC strategy, use the default format. 3113 NeedsDefault = true; 3114 else 3115 for (auto &I : *MI) { 3116 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 3117 if (MP->emitStackMaps(SM, *this)) 3118 continue; 3119 // The strategy doesn't have printer or doesn't emit custom stack maps. 3120 // Use the default format. 3121 NeedsDefault = true; 3122 } 3123 3124 if (NeedsDefault) 3125 SM.serializeToStackMapSection(); 3126 } 3127 3128 /// Pin vtable to this file. 3129 AsmPrinterHandler::~AsmPrinterHandler() = default; 3130 3131 void AsmPrinterHandler::markFunctionEnd() {} 3132 3133 // In the binary's "xray_instr_map" section, an array of these function entries 3134 // describes each instrumentation point. When XRay patches your code, the index 3135 // into this table will be given to your handler as a patch point identifier. 3136 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out, 3137 const MCSymbol *CurrentFnSym) const { 3138 Out->EmitSymbolValue(Sled, Bytes); 3139 Out->EmitSymbolValue(CurrentFnSym, Bytes); 3140 auto Kind8 = static_cast<uint8_t>(Kind); 3141 Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 3142 Out->EmitBinaryData( 3143 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 3144 Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1)); 3145 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3); 3146 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size"); 3147 Out->EmitZeros(Padding); 3148 } 3149 3150 void AsmPrinter::emitXRayTable() { 3151 if (Sleds.empty()) 3152 return; 3153 3154 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 3155 const Function &F = MF->getFunction(); 3156 MCSection *InstMap = nullptr; 3157 MCSection *FnSledIndex = nullptr; 3158 if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) { 3159 auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym); 3160 assert(Associated != nullptr); 3161 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER; 3162 std::string GroupName; 3163 if (F.hasComdat()) { 3164 Flags |= ELF::SHF_GROUP; 3165 GroupName = F.getComdat()->getName(); 3166 } 3167 3168 auto UniqueID = ++XRayFnUniqueID; 3169 InstMap = 3170 OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0, 3171 GroupName, UniqueID, Associated); 3172 FnSledIndex = 3173 OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, 3174 GroupName, UniqueID, Associated); 3175 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 3176 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 3177 SectionKind::getReadOnlyWithRel()); 3178 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0, 3179 SectionKind::getReadOnlyWithRel()); 3180 } else { 3181 llvm_unreachable("Unsupported target"); 3182 } 3183 3184 auto WordSizeBytes = MAI->getCodePointerSize(); 3185 3186 // Now we switch to the instrumentation map section. Because this is done 3187 // per-function, we are able to create an index entry that will represent the 3188 // range of sleds associated with a function. 3189 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true); 3190 OutStreamer->SwitchSection(InstMap); 3191 OutStreamer->EmitLabel(SledsStart); 3192 for (const auto &Sled : Sleds) 3193 Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym); 3194 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true); 3195 OutStreamer->EmitLabel(SledsEnd); 3196 3197 // We then emit a single entry in the index per function. We use the symbols 3198 // that bound the instrumentation map as the range for a specific function. 3199 // Each entry here will be 2 * word size aligned, as we're writing down two 3200 // pointers. This should work for both 32-bit and 64-bit platforms. 3201 OutStreamer->SwitchSection(FnSledIndex); 3202 OutStreamer->EmitCodeAlignment(2 * WordSizeBytes); 3203 OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false); 3204 OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false); 3205 OutStreamer->SwitchSection(PrevSection); 3206 Sleds.clear(); 3207 } 3208 3209 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 3210 SledKind Kind, uint8_t Version) { 3211 const Function &F = MI.getMF()->getFunction(); 3212 auto Attr = F.getFnAttribute("function-instrument"); 3213 bool LogArgs = F.hasFnAttribute("xray-log-args"); 3214 bool AlwaysInstrument = 3215 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 3216 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 3217 Kind = SledKind::LOG_ARGS_ENTER; 3218 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind, 3219 AlwaysInstrument, &F, Version}); 3220 } 3221 3222 void AsmPrinter::emitPatchableFunctionEntries() { 3223 const Function &F = MF->getFunction(); 3224 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0; 3225 (void)F.getFnAttribute("patchable-function-prefix") 3226 .getValueAsString() 3227 .getAsInteger(10, PatchableFunctionPrefix); 3228 (void)F.getFnAttribute("patchable-function-entry") 3229 .getValueAsString() 3230 .getAsInteger(10, PatchableFunctionEntry); 3231 if (!PatchableFunctionPrefix && !PatchableFunctionEntry) 3232 return; 3233 const unsigned PointerSize = getPointerSize(); 3234 if (TM.getTargetTriple().isOSBinFormatELF()) { 3235 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC; 3236 3237 // As of binutils 2.33, GNU as does not support section flag "o" or linkage 3238 // field "unique". Use SHF_LINK_ORDER if we are using the integrated 3239 // assembler. 3240 if (MAI->useIntegratedAssembler()) { 3241 Flags |= ELF::SHF_LINK_ORDER; 3242 std::string GroupName; 3243 if (F.hasComdat()) { 3244 Flags |= ELF::SHF_GROUP; 3245 GroupName = F.getComdat()->getName(); 3246 } 3247 MCSection *Section = getObjFileLowering().SectionForGlobal(&F, TM); 3248 unsigned UniqueID = 3249 PatchableFunctionEntryID 3250 .try_emplace(Section, PatchableFunctionEntryID.size()) 3251 .first->second; 3252 OutStreamer->SwitchSection(OutContext.getELFSection( 3253 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, 3254 GroupName, UniqueID, cast<MCSymbolELF>(CurrentFnSym))); 3255 } else { 3256 OutStreamer->SwitchSection(OutContext.getELFSection( 3257 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags)); 3258 } 3259 EmitAlignment(Align(PointerSize)); 3260 OutStreamer->EmitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize); 3261 } 3262 } 3263 3264 uint16_t AsmPrinter::getDwarfVersion() const { 3265 return OutStreamer->getContext().getDwarfVersion(); 3266 } 3267 3268 void AsmPrinter::setDwarfVersion(uint16_t Version) { 3269 OutStreamer->getContext().setDwarfVersion(Version); 3270 } 3271