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