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