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