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