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