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