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