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