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