AsmPrinter.cpp revision 1ab24611a6a82c7d9d70204f51fed10f026b40bc
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 "llvm/Assembly/Writer.h" 16#include "llvm/DerivedTypes.h" 17#include "llvm/Constants.h" 18#include "llvm/Module.h" 19#include "llvm/CodeGen/DwarfWriter.h" 20#include "llvm/CodeGen/GCMetadataPrinter.h" 21#include "llvm/CodeGen/MachineConstantPool.h" 22#include "llvm/CodeGen/MachineFrameInfo.h" 23#include "llvm/CodeGen/MachineFunction.h" 24#include "llvm/CodeGen/MachineJumpTableInfo.h" 25#include "llvm/CodeGen/MachineLoopInfo.h" 26#include "llvm/CodeGen/MachineModuleInfo.h" 27#include "llvm/Analysis/DebugInfo.h" 28#include "llvm/MC/MCContext.h" 29#include "llvm/MC/MCInst.h" 30#include "llvm/MC/MCSection.h" 31#include "llvm/MC/MCStreamer.h" 32#include "llvm/MC/MCSymbol.h" 33#include "llvm/Support/CommandLine.h" 34#include "llvm/Support/ErrorHandling.h" 35#include "llvm/Support/FormattedStream.h" 36#include "llvm/MC/MCAsmInfo.h" 37#include "llvm/Target/Mangler.h" 38#include "llvm/Target/TargetData.h" 39#include "llvm/Target/TargetInstrInfo.h" 40#include "llvm/Target/TargetLowering.h" 41#include "llvm/Target/TargetLoweringObjectFile.h" 42#include "llvm/Target/TargetOptions.h" 43#include "llvm/Target/TargetRegisterInfo.h" 44#include "llvm/ADT/SmallPtrSet.h" 45#include "llvm/ADT/SmallString.h" 46#include <cerrno> 47using namespace llvm; 48 49static cl::opt<cl::boolOrDefault> 50AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 51 cl::init(cl::BOU_UNSET)); 52 53static bool getVerboseAsm(bool VDef) { 54 switch (AsmVerbose) { 55 default: 56 case cl::BOU_UNSET: return VDef; 57 case cl::BOU_TRUE: return true; 58 case cl::BOU_FALSE: return false; 59 } 60} 61 62char AsmPrinter::ID = 0; 63AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm, 64 const MCAsmInfo *T, bool VDef) 65 : MachineFunctionPass(&ID), FunctionNumber(0), O(o), 66 TM(tm), MAI(T), TRI(tm.getRegisterInfo()), 67 68 OutContext(*new MCContext()), 69 // FIXME: Pass instprinter to streamer. 70 OutStreamer(*createAsmStreamer(OutContext, O, *T, 71 TM.getTargetData()->isLittleEndian(), 72 getVerboseAsm(VDef), 0)), 73 74 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) { 75 DW = 0; MMI = 0; 76 VerboseAsm = getVerboseAsm(VDef); 77} 78 79AsmPrinter::~AsmPrinter() { 80 for (gcp_iterator I = GCMetadataPrinters.begin(), 81 E = GCMetadataPrinters.end(); I != E; ++I) 82 delete I->second; 83 84 delete &OutStreamer; 85 delete &OutContext; 86} 87 88TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 89 return TM.getTargetLowering()->getObjFileLowering(); 90} 91 92/// getCurrentSection() - Return the current section we are emitting to. 93const MCSection *AsmPrinter::getCurrentSection() const { 94 return OutStreamer.getCurrentSection(); 95} 96 97 98void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 99 AU.setPreservesAll(); 100 MachineFunctionPass::getAnalysisUsage(AU); 101 AU.addRequired<GCModuleInfo>(); 102 if (VerboseAsm) 103 AU.addRequired<MachineLoopInfo>(); 104} 105 106bool AsmPrinter::doInitialization(Module &M) { 107 // Initialize TargetLoweringObjectFile. 108 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 109 .Initialize(OutContext, TM); 110 111 Mang = new Mangler(*MAI); 112 113 // Allow the target to emit any magic that it wants at the start of the file. 114 EmitStartOfAsmFile(M); 115 116 if (MAI->hasSingleParameterDotFile()) { 117 /* Very minimal debug info. It is ignored if we emit actual 118 debug info. If we don't, this at least helps the user find where 119 a function came from. */ 120 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n"; 121 } 122 123 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 124 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 125 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I) 126 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 127 MP->beginAssembly(O, *this, *MAI); 128 129 if (!M.getModuleInlineAsm().empty()) 130 O << MAI->getCommentString() << " Start of file scope inline assembly\n" 131 << M.getModuleInlineAsm() 132 << '\n' << MAI->getCommentString() 133 << " End of file scope inline assembly\n"; 134 135 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 136 if (MMI) 137 MMI->AnalyzeModule(M); 138 DW = getAnalysisIfAvailable<DwarfWriter>(); 139 if (DW) 140 DW->BeginModule(&M, MMI, O, this, MAI); 141 142 return false; 143} 144 145/// EmitGlobalVariable - Emit the specified global variable to the .s file. 146void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 147 if (!GV->hasInitializer()) // External globals require no code. 148 return; 149 150 // Check to see if this is a special global used by LLVM, if so, emit it. 151 if (EmitSpecialLLVMGlobal(GV)) 152 return; 153 154 MCSymbol *GVSym = GetGlobalValueSymbol(GV); 155 printVisibility(GVSym, GV->getVisibility()); 156 157 if (MAI->hasDotTypeDotSizeDirective()) { 158 O << "\t.type\t" << *GVSym; 159 if (MAI->getCommentString()[0] != '@') 160 O << ",@object\n"; 161 else 162 O << ",%object\n"; 163 } 164 165 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 166 167 const TargetData *TD = TM.getTargetData(); 168 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType()); 169 unsigned AlignLog = TD->getPreferredAlignmentLog(GV); 170 171 // Handle common and BSS local symbols (.lcomm). 172 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 173 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 174 175 if (VerboseAsm) { 176 O.PadToColumn(MAI->getCommentColumn()); 177 O << MAI->getCommentString() << ' '; 178 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent()); 179 O << '\n'; 180 } 181 182 // Handle common symbols. 183 if (GVKind.isCommon()) { 184 // .comm _foo, 42, 4 185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog); 186 return; 187 } 188 189 // Handle local BSS symbols. 190 if (MAI->hasMachoZeroFillDirective()) { 191 const MCSection *TheSection = 192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 193 // .zerofill __DATA, __bss, _foo, 400, 5 194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog); 195 return; 196 } 197 198 if (const char *LComm = MAI->getLCOMMDirective()) { 199 // .lcomm _foo, 42 200 O << LComm << *GVSym << ',' << Size; 201 O << '\n'; 202 return; 203 } 204 205 // .local _foo 206 O << "\t.local\t" << *GVSym << '\n'; 207 // .comm _foo, 42, 4 208 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog); 209 return; 210 } 211 212 const MCSection *TheSection = 213 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 214 215 // Handle the zerofill directive on darwin, which is a special form of BSS 216 // emission. 217 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) { 218 // .globl _foo 219 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global); 220 // .zerofill __DATA, __common, _foo, 400, 5 221 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog); 222 return; 223 } 224 225 OutStreamer.SwitchSection(TheSection); 226 227 // TODO: Factor into an 'emit linkage' thing that is shared with function 228 // bodies. 229 switch (GV->getLinkage()) { 230 case GlobalValue::CommonLinkage: 231 case GlobalValue::LinkOnceAnyLinkage: 232 case GlobalValue::LinkOnceODRLinkage: 233 case GlobalValue::WeakAnyLinkage: 234 case GlobalValue::WeakODRLinkage: 235 case GlobalValue::LinkerPrivateLinkage: 236 if (MAI->getWeakDefDirective() != 0) { 237 // .globl _foo 238 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global); 239 // .weak_definition _foo 240 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition); 241 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) { 242 // .globl _foo 243 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global); 244 // .linkonce same_size 245 O << LinkOnce; 246 } else { 247 // .weak _foo 248 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak); 249 } 250 break; 251 case GlobalValue::DLLExportLinkage: 252 case GlobalValue::AppendingLinkage: 253 // FIXME: appending linkage variables should go into a section of 254 // their name or something. For now, just emit them as external. 255 case GlobalValue::ExternalLinkage: 256 // If external or appending, declare as a global symbol. 257 // .globl _foo 258 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global); 259 break; 260 case GlobalValue::PrivateLinkage: 261 case GlobalValue::InternalLinkage: 262 break; 263 default: 264 llvm_unreachable("Unknown linkage type!"); 265 } 266 267 EmitAlignment(AlignLog, GV); 268 if (VerboseAsm) { 269 O.PadToColumn(MAI->getCommentColumn()); 270 O << MAI->getCommentString() << ' '; 271 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent()); 272 O << '\n'; 273 } 274 OutStreamer.EmitLabel(GVSym); 275 276 EmitGlobalConstant(GV->getInitializer()); 277 278 if (MAI->hasDotTypeDotSizeDirective()) 279 O << "\t.size\t" << *GVSym << ", " << Size << '\n'; 280} 281 282 283bool AsmPrinter::doFinalization(Module &M) { 284 // Emit global variables. 285 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 286 I != E; ++I) 287 EmitGlobalVariable(I); 288 289 // Emit final debug information. 290 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling()) 291 DW->EndModule(); 292 293 // If the target wants to know about weak references, print them all. 294 if (MAI->getWeakRefDirective()) { 295 // FIXME: This is not lazy, it would be nice to only print weak references 296 // to stuff that is actually used. Note that doing so would require targets 297 // to notice uses in operands (due to constant exprs etc). This should 298 // happen with the MC stuff eventually. 299 300 // Print out module-level global variables here. 301 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 302 I != E; ++I) { 303 if (!I->hasExternalWeakLinkage()) continue; 304 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n'; 305 } 306 307 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 308 if (!I->hasExternalWeakLinkage()) continue; 309 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n'; 310 } 311 } 312 313 if (MAI->getSetDirective()) { 314 O << '\n'; 315 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 316 I != E; ++I) { 317 MCSymbol *Name = GetGlobalValueSymbol(I); 318 319 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal()); 320 MCSymbol *Target = GetGlobalValueSymbol(GV); 321 322 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) 323 O << "\t.globl\t" << *Name << '\n'; 324 else if (I->hasWeakLinkage()) 325 O << MAI->getWeakRefDirective() << *Name << '\n'; 326 else 327 assert(I->hasLocalLinkage() && "Invalid alias linkage"); 328 329 printVisibility(Name, I->getVisibility()); 330 331 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n'; 332 } 333 } 334 335 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 336 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 337 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 338 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I)) 339 MP->finishAssembly(O, *this, *MAI); 340 341 // If we don't have any trampolines, then we don't require stack memory 342 // to be executable. Some targets have a directive to declare this. 343 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 344 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 345 if (MAI->getNonexecutableStackDirective()) 346 O << MAI->getNonexecutableStackDirective() << '\n'; 347 348 349 // Allow the target to emit any magic that it wants at the end of the file, 350 // after everything else has gone out. 351 EmitEndOfAsmFile(M); 352 353 delete Mang; Mang = 0; 354 DW = 0; MMI = 0; 355 356 OutStreamer.Finish(); 357 return false; 358} 359 360void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 361 // Get the function symbol. 362 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction()); 363 IncrementFunctionNumber(); 364 365 if (VerboseAsm) 366 LI = &getAnalysis<MachineLoopInfo>(); 367} 368 369namespace { 370 // SectionCPs - Keep track the alignment, constpool entries per Section. 371 struct SectionCPs { 372 const MCSection *S; 373 unsigned Alignment; 374 SmallVector<unsigned, 4> CPEs; 375 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {} 376 }; 377} 378 379/// EmitConstantPool - Print to the current output stream assembly 380/// representations of the constants in the constant pool MCP. This is 381/// used to print out constants which have been "spilled to memory" by 382/// the code generator. 383/// 384void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) { 385 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 386 if (CP.empty()) return; 387 388 // Calculate sections for constant pool entries. We collect entries to go into 389 // the same section together to reduce amount of section switch statements. 390 SmallVector<SectionCPs, 4> CPSections; 391 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 392 const MachineConstantPoolEntry &CPE = CP[i]; 393 unsigned Align = CPE.getAlignment(); 394 395 SectionKind Kind; 396 switch (CPE.getRelocationInfo()) { 397 default: llvm_unreachable("Unknown section kind"); 398 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 399 case 1: 400 Kind = SectionKind::getReadOnlyWithRelLocal(); 401 break; 402 case 0: 403 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) { 404 case 4: Kind = SectionKind::getMergeableConst4(); break; 405 case 8: Kind = SectionKind::getMergeableConst8(); break; 406 case 16: Kind = SectionKind::getMergeableConst16();break; 407 default: Kind = SectionKind::getMergeableConst(); break; 408 } 409 } 410 411 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 412 413 // The number of sections are small, just do a linear search from the 414 // last section to the first. 415 bool Found = false; 416 unsigned SecIdx = CPSections.size(); 417 while (SecIdx != 0) { 418 if (CPSections[--SecIdx].S == S) { 419 Found = true; 420 break; 421 } 422 } 423 if (!Found) { 424 SecIdx = CPSections.size(); 425 CPSections.push_back(SectionCPs(S, Align)); 426 } 427 428 if (Align > CPSections[SecIdx].Alignment) 429 CPSections[SecIdx].Alignment = Align; 430 CPSections[SecIdx].CPEs.push_back(i); 431 } 432 433 // Now print stuff into the calculated sections. 434 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 435 OutStreamer.SwitchSection(CPSections[i].S); 436 EmitAlignment(Log2_32(CPSections[i].Alignment)); 437 438 unsigned Offset = 0; 439 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 440 unsigned CPI = CPSections[i].CPEs[j]; 441 MachineConstantPoolEntry CPE = CP[CPI]; 442 443 // Emit inter-object padding for alignment. 444 unsigned AlignMask = CPE.getAlignment() - 1; 445 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 446 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/); 447 448 const Type *Ty = CPE.getType(); 449 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty); 450 451 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 452 << CPI << ':'; 453 if (VerboseAsm) { 454 O.PadToColumn(MAI->getCommentColumn()); 455 O << MAI->getCommentString() << " constant "; 456 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent()); 457 } 458 O << '\n'; 459 if (CPE.isMachineConstantPoolEntry()) 460 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 461 else 462 EmitGlobalConstant(CPE.Val.ConstVal); 463 } 464 } 465} 466 467/// EmitJumpTableInfo - Print assembly representations of the jump tables used 468/// by the current function to the current output stream. 469/// 470void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI, 471 MachineFunction &MF) { 472 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 473 if (JT.empty()) return; 474 475 bool IsPic = TM.getRelocationModel() == Reloc::PIC_; 476 477 // Pick the directive to use to print the jump table entries, and switch to 478 // the appropriate section. 479 TargetLowering *LoweringInfo = TM.getTargetLowering(); 480 481 const Function *F = MF.getFunction(); 482 bool JTInDiffSection = false; 483 if (F->isWeakForLinker() || 484 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) { 485 // In PIC mode, we need to emit the jump table to the same section as the 486 // function body itself, otherwise the label differences won't make sense. 487 // We should also do if the section name is NULL or function is declared in 488 // discardable section. 489 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, 490 TM)); 491 } else { 492 // Otherwise, drop it in the readonly section. 493 const MCSection *ReadOnlySection = 494 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 495 OutStreamer.SwitchSection(ReadOnlySection); 496 JTInDiffSection = true; 497 } 498 499 EmitAlignment(Log2_32(MJTI->getAlignment())); 500 501 for (unsigned i = 0, e = JT.size(); i != e; ++i) { 502 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs; 503 504 // If this jump table was deleted, ignore it. 505 if (JTBBs.empty()) continue; 506 507 // For PIC codegen, if possible we want to use the SetDirective to reduce 508 // the number of relocations the assembler will generate for the jump table. 509 // Set directives are all printed before the jump table itself. 510 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets; 511 if (MAI->getSetDirective() && IsPic) 512 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 513 if (EmittedSets.insert(JTBBs[ii])) 514 printPICJumpTableSetLabel(i, JTBBs[ii]); 515 516 // On some targets (e.g. Darwin) we want to emit two consequtive labels 517 // before each jump table. The first label is never referenced, but tells 518 // the assembler and linker the extents of the jump table object. The 519 // second label is actually referenced by the code. 520 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) { 521 O << MAI->getLinkerPrivateGlobalPrefix() 522 << "JTI" << getFunctionNumber() << '_' << i << ":\n"; 523 } 524 525 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 526 << '_' << i << ":\n"; 527 528 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 529 printPICJumpTableEntry(MJTI, JTBBs[ii], i); 530 O << '\n'; 531 } 532 } 533} 534 535void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI, 536 const MachineBasicBlock *MBB, 537 unsigned uid) const { 538 bool isPIC = TM.getRelocationModel() == Reloc::PIC_; 539 540 // Use JumpTableDirective otherwise honor the entry size from the jump table 541 // info. 542 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC); 543 bool HadJTEntryDirective = JTEntryDirective != NULL; 544 if (!HadJTEntryDirective) { 545 JTEntryDirective = MJTI->getEntrySize() == 4 ? 546 MAI->getData32bitsDirective() : MAI->getData64bitsDirective(); 547 } 548 549 O << JTEntryDirective << ' '; 550 551 // If we have emitted set directives for the jump table entries, print 552 // them rather than the entries themselves. If we're emitting PIC, then 553 // emit the table entries as differences between two text section labels. 554 // If we're emitting non-PIC code, then emit the entries as direct 555 // references to the target basic blocks. 556 if (!isPIC) { 557 O << *GetMBBSymbol(MBB->getNumber()); 558 } else if (MAI->getSetDirective()) { 559 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber() 560 << '_' << uid << "_set_" << MBB->getNumber(); 561 } else { 562 O << *GetMBBSymbol(MBB->getNumber()); 563 // If the arch uses custom Jump Table directives, don't calc relative to 564 // JT 565 if (!HadJTEntryDirective) 566 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" 567 << getFunctionNumber() << '_' << uid; 568 } 569} 570 571 572/// EmitSpecialLLVMGlobal - Check to see if the specified global is a 573/// special global used by LLVM. If so, emit it and return true, otherwise 574/// do nothing and return false. 575bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 576 if (GV->getName() == "llvm.used") { 577 if (MAI->getUsedDirective() != 0) // No need to emit this at all. 578 EmitLLVMUsedList(GV->getInitializer()); 579 return true; 580 } 581 582 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 583 if (GV->getSection() == "llvm.metadata" || 584 GV->hasAvailableExternallyLinkage()) 585 return true; 586 587 if (!GV->hasAppendingLinkage()) return false; 588 589 assert(GV->hasInitializer() && "Not a special LLVM global!"); 590 591 const TargetData *TD = TM.getTargetData(); 592 unsigned Align = Log2_32(TD->getPointerPrefAlignment()); 593 if (GV->getName() == "llvm.global_ctors") { 594 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection()); 595 EmitAlignment(Align, 0); 596 EmitXXStructorList(GV->getInitializer()); 597 598 if (TM.getRelocationModel() == Reloc::Static && 599 MAI->hasStaticCtorDtorReferenceInStaticMode()) 600 O << ".reference .constructors_used\n"; 601 return true; 602 } 603 604 if (GV->getName() == "llvm.global_dtors") { 605 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection()); 606 EmitAlignment(Align, 0); 607 EmitXXStructorList(GV->getInitializer()); 608 609 if (TM.getRelocationModel() == Reloc::Static && 610 MAI->hasStaticCtorDtorReferenceInStaticMode()) 611 O << ".reference .destructors_used\n"; 612 return true; 613 } 614 615 return false; 616} 617 618/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 619/// global in the specified llvm.used list for which emitUsedDirectiveFor 620/// is true, as being used with this directive. 621void AsmPrinter::EmitLLVMUsedList(Constant *List) { 622 const char *Directive = MAI->getUsedDirective(); 623 624 // Should be an array of 'i8*'. 625 ConstantArray *InitList = dyn_cast<ConstantArray>(List); 626 if (InitList == 0) return; 627 628 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 629 const GlobalValue *GV = 630 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 631 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) { 632 O << Directive; 633 EmitConstantValueOnly(InitList->getOperand(i)); 634 O << '\n'; 635 } 636 } 637} 638 639/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the 640/// function pointers, ignoring the init priority. 641void AsmPrinter::EmitXXStructorList(Constant *List) { 642 // Should be an array of '{ int, void ()* }' structs. The first value is the 643 // init priority, which we ignore. 644 if (!isa<ConstantArray>(List)) return; 645 ConstantArray *InitList = cast<ConstantArray>(List); 646 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 647 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 648 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 649 650 if (CS->getOperand(1)->isNullValue()) 651 return; // Found a null terminator, exit printing. 652 // Emit the function pointer. 653 EmitGlobalConstant(CS->getOperand(1)); 654 } 655} 656 657 658//===----------------------------------------------------------------------===// 659/// LEB 128 number encoding. 660 661/// PrintULEB128 - Print a series of hexadecimal values (separated by commas) 662/// representing an unsigned leb128 value. 663void AsmPrinter::PrintULEB128(unsigned Value) const { 664 do { 665 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 666 Value >>= 7; 667 if (Value) Byte |= 0x80; 668 PrintHex(Byte); 669 if (Value) O << ", "; 670 } while (Value); 671} 672 673/// PrintSLEB128 - Print a series of hexadecimal values (separated by commas) 674/// representing a signed leb128 value. 675void AsmPrinter::PrintSLEB128(int Value) const { 676 int Sign = Value >> (8 * sizeof(Value) - 1); 677 bool IsMore; 678 679 do { 680 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 681 Value >>= 7; 682 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; 683 if (IsMore) Byte |= 0x80; 684 PrintHex(Byte); 685 if (IsMore) O << ", "; 686 } while (IsMore); 687} 688 689//===--------------------------------------------------------------------===// 690// Emission and print routines 691// 692 693/// PrintHex - Print a value as a hexadecimal value. 694/// 695void AsmPrinter::PrintHex(uint64_t Value) const { 696 O << "0x"; 697 O.write_hex(Value); 698} 699 700/// EOL - Print a newline character to asm stream. If a comment is present 701/// then it will be printed first. Comments should not contain '\n'. 702void AsmPrinter::EOL() const { 703 O << '\n'; 704} 705 706void AsmPrinter::EOL(const Twine &Comment) const { 707 if (VerboseAsm && !Comment.isTriviallyEmpty()) { 708 O.PadToColumn(MAI->getCommentColumn()); 709 O << MAI->getCommentString() << ' ' << Comment; 710 } 711 O << '\n'; 712} 713 714static const char *DecodeDWARFEncoding(unsigned Encoding) { 715 switch (Encoding) { 716 case dwarf::DW_EH_PE_absptr: 717 return "absptr"; 718 case dwarf::DW_EH_PE_omit: 719 return "omit"; 720 case dwarf::DW_EH_PE_pcrel: 721 return "pcrel"; 722 case dwarf::DW_EH_PE_udata4: 723 return "udata4"; 724 case dwarf::DW_EH_PE_udata8: 725 return "udata8"; 726 case dwarf::DW_EH_PE_sdata4: 727 return "sdata4"; 728 case dwarf::DW_EH_PE_sdata8: 729 return "sdata8"; 730 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: 731 return "pcrel udata4"; 732 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: 733 return "pcrel sdata4"; 734 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: 735 return "pcrel udata8"; 736 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: 737 return "pcrel sdata8"; 738 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: 739 return "indirect pcrel udata4"; 740 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: 741 return "indirect pcrel sdata4"; 742 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: 743 return "indirect pcrel udata8"; 744 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: 745 return "indirect pcrel sdata8"; 746 } 747 748 return 0; 749} 750 751void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const { 752 if (VerboseAsm && !Comment.isTriviallyEmpty()) { 753 O.PadToColumn(MAI->getCommentColumn()); 754 O << MAI->getCommentString() 755 << ' ' 756 << Comment; 757 758 if (const char *EncStr = DecodeDWARFEncoding(Encoding)) 759 O << " (" << EncStr << ')'; 760 } 761 O << '\n'; 762} 763 764/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an 765/// unsigned leb128 value. 766void AsmPrinter::EmitULEB128Bytes(unsigned Value) const { 767 if (MAI->hasLEB128()) { 768 O << "\t.uleb128\t" 769 << Value; 770 } else { 771 O << MAI->getData8bitsDirective(); 772 PrintULEB128(Value); 773 } 774} 775 776/// EmitSLEB128Bytes - print an assembler byte data directive to compose a 777/// signed leb128 value. 778void AsmPrinter::EmitSLEB128Bytes(int Value) const { 779 if (MAI->hasLEB128()) { 780 O << "\t.sleb128\t" 781 << Value; 782 } else { 783 O << MAI->getData8bitsDirective(); 784 PrintSLEB128(Value); 785 } 786} 787 788/// EmitInt8 - Emit a byte directive and value. 789/// 790void AsmPrinter::EmitInt8(int Value) const { 791 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/); 792} 793 794/// EmitInt16 - Emit a short directive and value. 795/// 796void AsmPrinter::EmitInt16(int Value) const { 797 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/); 798} 799 800/// EmitInt32 - Emit a long directive and value. 801/// 802void AsmPrinter::EmitInt32(int Value) const { 803 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/); 804} 805 806/// EmitInt64 - Emit a long long directive and value. 807/// 808void AsmPrinter::EmitInt64(uint64_t Value) const { 809 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/); 810} 811 812/// toOctal - Convert the low order bits of X into an octal digit. 813/// 814static inline char toOctal(int X) { 815 return (X&7)+'0'; 816} 817 818/// printStringChar - Print a char, escaped if necessary. 819/// 820static void printStringChar(formatted_raw_ostream &O, unsigned char C) { 821 if (C == '"') { 822 O << "\\\""; 823 } else if (C == '\\') { 824 O << "\\\\"; 825 } else if (isprint((unsigned char)C)) { 826 O << C; 827 } else { 828 switch(C) { 829 case '\b': O << "\\b"; break; 830 case '\f': O << "\\f"; break; 831 case '\n': O << "\\n"; break; 832 case '\r': O << "\\r"; break; 833 case '\t': O << "\\t"; break; 834 default: 835 O << '\\'; 836 O << toOctal(C >> 6); 837 O << toOctal(C >> 3); 838 O << toOctal(C >> 0); 839 break; 840 } 841 } 842} 843 844/// EmitString - Emit a string with quotes and a null terminator. 845/// Special characters are emitted properly. 846/// \literal (Eg. '\t') \endliteral 847void AsmPrinter::EmitString(const StringRef String) const { 848 EmitString(String.data(), String.size()); 849} 850 851void AsmPrinter::EmitString(const char *String, unsigned Size) const { 852 const char* AscizDirective = MAI->getAscizDirective(); 853 if (AscizDirective) 854 O << AscizDirective; 855 else 856 O << MAI->getAsciiDirective(); 857 O << '\"'; 858 for (unsigned i = 0; i < Size; ++i) 859 printStringChar(O, String[i]); 860 if (AscizDirective) 861 O << '\"'; 862 else 863 O << "\\0\""; 864} 865 866 867/// EmitFile - Emit a .file directive. 868void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const { 869 O << "\t.file\t" << Number << " \""; 870 for (unsigned i = 0, N = Name.size(); i < N; ++i) 871 printStringChar(O, Name[i]); 872 O << '\"'; 873} 874 875 876//===----------------------------------------------------------------------===// 877 878// EmitAlignment - Emit an alignment directive to the specified power of 879// two boundary. For example, if you pass in 3 here, you will get an 8 880// byte alignment. If a global value is specified, and if that global has 881// an explicit alignment requested, it will unconditionally override the 882// alignment request. However, if ForcedAlignBits is specified, this value 883// has final say: the ultimate alignment will be the max of ForcedAlignBits 884// and the alignment computed with NumBits and the global. 885// 886// The algorithm is: 887// Align = NumBits; 888// if (GV && GV->hasalignment) Align = GV->getalignment(); 889// Align = std::max(Align, ForcedAlignBits); 890// 891void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV, 892 unsigned ForcedAlignBits, 893 bool UseFillExpr) const { 894 if (GV && GV->getAlignment()) 895 NumBits = Log2_32(GV->getAlignment()); 896 NumBits = std::max(NumBits, ForcedAlignBits); 897 898 if (NumBits == 0) return; // No need to emit alignment. 899 900 unsigned FillValue = 0; 901 if (getCurrentSection()->getKind().isText()) 902 FillValue = MAI->getTextAlignFillValue(); 903 904 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0); 905} 906 907// Print out the specified constant, without a storage class. Only the 908// constants valid in constant expressions can occur here. 909void AsmPrinter::EmitConstantValueOnly(const Constant *CV) { 910 if (CV->isNullValue() || isa<UndefValue>(CV)) { 911 O << '0'; 912 return; 913 } 914 915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 916 O << CI->getZExtValue(); 917 return; 918 } 919 920 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) { 921 // This is a constant address for a global variable or function. Use the 922 // name of the variable or function as the address value. 923 O << *GetGlobalValueSymbol(GV); 924 return; 925 } 926 927 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 928 O << *GetBlockAddressSymbol(BA); 929 return; 930 } 931 932 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 933 if (CE == 0) { 934 llvm_unreachable("Unknown constant value!"); 935 O << '0'; 936 return; 937 } 938 939 switch (CE->getOpcode()) { 940 case Instruction::ZExt: 941 case Instruction::SExt: 942 case Instruction::FPTrunc: 943 case Instruction::FPExt: 944 case Instruction::UIToFP: 945 case Instruction::SIToFP: 946 case Instruction::FPToUI: 947 case Instruction::FPToSI: 948 default: 949 llvm_unreachable("FIXME: Don't support this constant cast expr"); 950 case Instruction::GetElementPtr: { 951 // generate a symbolic expression for the byte address 952 const TargetData *TD = TM.getTargetData(); 953 const Constant *ptrVal = CE->getOperand(0); 954 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end()); 955 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], 956 idxVec.size()); 957 if (Offset == 0) 958 return EmitConstantValueOnly(ptrVal); 959 960 // Truncate/sext the offset to the pointer size. 961 if (TD->getPointerSizeInBits() != 64) { 962 int SExtAmount = 64-TD->getPointerSizeInBits(); 963 Offset = (Offset << SExtAmount) >> SExtAmount; 964 } 965 966 if (Offset) 967 O << '('; 968 EmitConstantValueOnly(ptrVal); 969 if (Offset > 0) 970 O << ") + " << Offset; 971 else 972 O << ") - " << -Offset; 973 return; 974 } 975 case Instruction::BitCast: 976 return EmitConstantValueOnly(CE->getOperand(0)); 977 978 case Instruction::IntToPtr: { 979 // Handle casts to pointers by changing them into casts to the appropriate 980 // integer type. This promotes constant folding and simplifies this code. 981 const TargetData *TD = TM.getTargetData(); 982 Constant *Op = CE->getOperand(0); 983 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()), 984 false/*ZExt*/); 985 return EmitConstantValueOnly(Op); 986 } 987 988 case Instruction::PtrToInt: { 989 // Support only foldable casts to/from pointers that can be eliminated by 990 // changing the pointer to the appropriately sized integer type. 991 Constant *Op = CE->getOperand(0); 992 const Type *Ty = CE->getType(); 993 const TargetData *TD = TM.getTargetData(); 994 995 // We can emit the pointer value into this slot if the slot is an 996 // integer slot greater or equal to the size of the pointer. 997 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType())) 998 return EmitConstantValueOnly(Op); 999 1000 O << "(("; 1001 EmitConstantValueOnly(Op); 1002 APInt ptrMask = 1003 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType())); 1004 1005 SmallString<40> S; 1006 ptrMask.toStringUnsigned(S); 1007 O << ") & " << S.str() << ')'; 1008 return; 1009 } 1010 1011 case Instruction::Trunc: 1012 // We emit the value and depend on the assembler to truncate the generated 1013 // expression properly. This is important for differences between 1014 // blockaddress labels. Since the two labels are in the same function, it 1015 // is reasonable to treat their delta as a 32-bit value. 1016 return EmitConstantValueOnly(CE->getOperand(0)); 1017 1018 case Instruction::Add: 1019 case Instruction::Sub: 1020 case Instruction::And: 1021 case Instruction::Or: 1022 case Instruction::Xor: 1023 O << '('; 1024 EmitConstantValueOnly(CE->getOperand(0)); 1025 O << ')'; 1026 switch (CE->getOpcode()) { 1027 case Instruction::Add: 1028 O << " + "; 1029 break; 1030 case Instruction::Sub: 1031 O << " - "; 1032 break; 1033 case Instruction::And: 1034 O << " & "; 1035 break; 1036 case Instruction::Or: 1037 O << " | "; 1038 break; 1039 case Instruction::Xor: 1040 O << " ^ "; 1041 break; 1042 default: 1043 break; 1044 } 1045 O << '('; 1046 EmitConstantValueOnly(CE->getOperand(1)); 1047 O << ')'; 1048 break; 1049 } 1050} 1051 1052/// printAsCString - Print the specified array as a C compatible string, only if 1053/// the predicate isString is true. 1054/// 1055static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA, 1056 unsigned LastElt) { 1057 assert(CVA->isString() && "Array is not string compatible!"); 1058 1059 O << '\"'; 1060 for (unsigned i = 0; i != LastElt; ++i) { 1061 unsigned char C = 1062 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue(); 1063 printStringChar(O, C); 1064 } 1065 O << '\"'; 1066} 1067 1068/// EmitString - Emit a zero-byte-terminated string constant. 1069/// 1070void AsmPrinter::EmitString(const ConstantArray *CVA) const { 1071 unsigned NumElts = CVA->getNumOperands(); 1072 if (MAI->getAscizDirective() && NumElts && 1073 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) { 1074 O << MAI->getAscizDirective(); 1075 printAsCString(O, CVA, NumElts-1); 1076 } else { 1077 O << MAI->getAsciiDirective(); 1078 printAsCString(O, CVA, NumElts); 1079 } 1080 O << '\n'; 1081} 1082 1083static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace, 1084 AsmPrinter &AP) { 1085 if (AddrSpace == 0 && CA->isString()) { 1086 AP.EmitString(CA); 1087 } else { // Not a string. Print the values in successive locations 1088 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 1089 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace); 1090 } 1091} 1092 1093static void EmitGlobalConstantVector(const ConstantVector *CV, 1094 unsigned AddrSpace, AsmPrinter &AP) { 1095 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 1096 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace); 1097} 1098 1099static void EmitGlobalConstantStruct(const ConstantStruct *CS, 1100 unsigned AddrSpace, AsmPrinter &AP) { 1101 // Print the fields in successive locations. Pad to align if needed! 1102 const TargetData *TD = AP.TM.getTargetData(); 1103 unsigned Size = TD->getTypeAllocSize(CS->getType()); 1104 const StructLayout *Layout = TD->getStructLayout(CS->getType()); 1105 uint64_t SizeSoFar = 0; 1106 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 1107 const Constant *Field = CS->getOperand(i); 1108 1109 // Check if padding is needed and insert one or more 0s. 1110 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType()); 1111 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 1112 - Layout->getElementOffset(i)) - FieldSize; 1113 SizeSoFar += FieldSize + PadSize; 1114 1115 // Now print the actual field value. 1116 AP.EmitGlobalConstant(Field, AddrSpace); 1117 1118 // Insert padding - this may include padding to increase the size of the 1119 // current field up to the ABI size (if the struct is not packed) as well 1120 // as padding to ensure that the next field starts at the right offset. 1121 AP.OutStreamer.EmitZeros(PadSize, AddrSpace); 1122 } 1123 assert(SizeSoFar == Layout->getSizeInBytes() && 1124 "Layout of constant struct may be incorrect!"); 1125} 1126 1127static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace, 1128 AsmPrinter &AP) { 1129 // FP Constants are printed as integer constants to avoid losing 1130 // precision. 1131 if (CFP->getType()->isDoubleTy()) { 1132 if (AP.VerboseAsm) { 1133 double Val = CFP->getValueAPF().convertToDouble(); // for comment only 1134 AP.O.PadToColumn(AP.MAI->getCommentColumn()); 1135 AP.O << AP.MAI->getCommentString() << " double " << Val << '\n'; 1136 } 1137 1138 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1139 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1140 return; 1141 } 1142 1143 if (CFP->getType()->isFloatTy()) { 1144 if (AP.VerboseAsm) { 1145 float Val = CFP->getValueAPF().convertToFloat(); // for comment only 1146 AP.O.PadToColumn(AP.MAI->getCommentColumn()); 1147 AP.O << AP.MAI->getCommentString() << " float " << Val << '\n'; 1148 } 1149 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1150 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace); 1151 return; 1152 } 1153 1154 if (CFP->getType()->isX86_FP80Ty()) { 1155 // all long double variants are printed as hex 1156 // api needed to prevent premature destruction 1157 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1158 const uint64_t *p = API.getRawData(); 1159 if (AP.VerboseAsm) { 1160 // Convert to double so we can print the approximate val as a comment. 1161 APFloat DoubleVal = CFP->getValueAPF(); 1162 bool ignored; 1163 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1164 &ignored); 1165 AP.O.PadToColumn(AP.MAI->getCommentColumn()); 1166 AP.O << AP.MAI->getCommentString() << " x86_fp80 ~= " 1167 << DoubleVal.convertToDouble() << '\n'; 1168 } 1169 1170 if (AP.TM.getTargetData()->isBigEndian()) { 1171 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1172 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1173 } else { 1174 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1175 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1176 } 1177 1178 // Emit the tail padding for the long double. 1179 const TargetData &TD = *AP.TM.getTargetData(); 1180 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) - 1181 TD.getTypeStoreSize(CFP->getType()), AddrSpace); 1182 return; 1183 } 1184 1185 assert(CFP->getType()->isPPC_FP128Ty() && 1186 "Floating point constant type not handled"); 1187 // All long double variants are printed as hex api needed to prevent 1188 // premature destruction. 1189 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1190 const uint64_t *p = API.getRawData(); 1191 if (AP.TM.getTargetData()->isBigEndian()) { 1192 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1193 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1194 } else { 1195 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1196 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1197 } 1198} 1199 1200static void EmitGlobalConstantLargeInt(const ConstantInt *CI, 1201 unsigned AddrSpace, AsmPrinter &AP) { 1202 const TargetData *TD = AP.TM.getTargetData(); 1203 unsigned BitWidth = CI->getBitWidth(); 1204 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits"); 1205 1206 // We don't expect assemblers to support integer data directives 1207 // for more than 64 bits, so we emit the data in at most 64-bit 1208 // quantities at a time. 1209 const uint64_t *RawData = CI->getValue().getRawData(); 1210 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1211 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i]; 1212 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1213 } 1214} 1215 1216/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1217void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1218 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) { 1219 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1220 return OutStreamer.EmitZeros(Size, AddrSpace); 1221 } 1222 1223 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1224 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1225 switch (Size) { 1226 case 1: 1227 case 2: 1228 case 4: 1229 case 8: 1230 if (VerboseAsm) { 1231 O.PadToColumn(MAI->getCommentColumn()); 1232 O << MAI->getCommentString() << " 0x"; 1233 O.write_hex(CI->getZExtValue()); 1234 O << '\n'; 1235 } 1236 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace); 1237 return; 1238 default: 1239 EmitGlobalConstantLargeInt(CI, AddrSpace, *this); 1240 return; 1241 } 1242 } 1243 1244 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 1245 return EmitGlobalConstantArray(CVA, AddrSpace, *this); 1246 1247 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 1248 return EmitGlobalConstantStruct(CVS, AddrSpace, *this); 1249 1250 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 1251 return EmitGlobalConstantFP(CFP, AddrSpace, *this); 1252 1253 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 1254 return EmitGlobalConstantVector(V, AddrSpace, *this); 1255 1256 if (isa<ConstantPointerNull>(CV)) { 1257 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1258 OutStreamer.EmitIntValue(0, Size, AddrSpace); 1259 return; 1260 } 1261 1262 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit 1263 // the expression value. 1264 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) { 1265 case 0: return; 1266 case 1: O << MAI->getData8bitsDirective(AddrSpace); break; 1267 case 2: O << MAI->getData16bitsDirective(AddrSpace); break; 1268 case 4: O << MAI->getData32bitsDirective(AddrSpace); break; 1269 case 8: 1270 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) { 1271 O << Dir; 1272 break; 1273 } 1274 // FALL THROUGH. 1275 default: 1276 llvm_unreachable("Target cannot handle given data directive width!"); 1277 return; 1278 } 1279 1280 EmitConstantValueOnly(CV); 1281 O << '\n'; 1282} 1283 1284void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1285 // Target doesn't support this yet! 1286 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1287} 1288 1289/// PrintSpecial - Print information related to the specified machine instr 1290/// that is independent of the operand, and may be independent of the instr 1291/// itself. This can be useful for portably encoding the comment character 1292/// or other bits of target-specific knowledge into the asmstrings. The 1293/// syntax used is ${:comment}. Targets can override this to add support 1294/// for their own strange codes. 1295void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const { 1296 if (!strcmp(Code, "private")) { 1297 O << MAI->getPrivateGlobalPrefix(); 1298 } else if (!strcmp(Code, "comment")) { 1299 if (VerboseAsm) 1300 O << MAI->getCommentString(); 1301 } else if (!strcmp(Code, "uid")) { 1302 // Comparing the address of MI isn't sufficient, because machineinstrs may 1303 // be allocated to the same address across functions. 1304 const Function *ThisF = MI->getParent()->getParent()->getFunction(); 1305 1306 // If this is a new LastFn instruction, bump the counter. 1307 if (LastMI != MI || LastFn != ThisF) { 1308 ++Counter; 1309 LastMI = MI; 1310 LastFn = ThisF; 1311 } 1312 O << Counter; 1313 } else { 1314 std::string msg; 1315 raw_string_ostream Msg(msg); 1316 Msg << "Unknown special formatter '" << Code 1317 << "' for machine instr: " << *MI; 1318 llvm_report_error(Msg.str()); 1319 } 1320} 1321 1322/// processDebugLoc - Processes the debug information of each machine 1323/// instruction's DebugLoc. 1324void AsmPrinter::processDebugLoc(const MachineInstr *MI, 1325 bool BeforePrintingInsn) { 1326 if (!MAI || !DW || !MAI->doesSupportDebugInformation() 1327 || !DW->ShouldEmitDwarfDebug()) 1328 return; 1329 DebugLoc DL = MI->getDebugLoc(); 1330 if (DL.isUnknown()) 1331 return; 1332 DILocation CurDLT = MF->getDILocation(DL); 1333 if (CurDLT.getScope().isNull()) 1334 return; 1335 1336 if (!BeforePrintingInsn) { 1337 // After printing instruction 1338 DW->EndScope(MI); 1339 } else if (CurDLT.getNode() != PrevDLT) { 1340 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 1341 CurDLT.getColumnNumber(), 1342 CurDLT.getScope().getNode()); 1343 printLabel(L); 1344 O << '\n'; 1345 DW->BeginScope(MI, L); 1346 PrevDLT = CurDLT.getNode(); 1347 } 1348} 1349 1350 1351/// printInlineAsm - This method formats and prints the specified machine 1352/// instruction that is an inline asm. 1353void AsmPrinter::printInlineAsm(const MachineInstr *MI) const { 1354 unsigned NumOperands = MI->getNumOperands(); 1355 1356 // Count the number of register definitions. 1357 unsigned NumDefs = 0; 1358 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 1359 ++NumDefs) 1360 assert(NumDefs != NumOperands-1 && "No asm string?"); 1361 1362 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); 1363 1364 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. 1365 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 1366 1367 O << '\t'; 1368 1369 // If this asmstr is empty, just print the #APP/#NOAPP markers. 1370 // These are useful to see where empty asm's wound up. 1371 if (AsmStr[0] == 0) { 1372 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1373 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n'; 1374 return; 1375 } 1376 1377 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1378 1379 // The variant of the current asmprinter. 1380 int AsmPrinterVariant = MAI->getAssemblerDialect(); 1381 1382 int CurVariant = -1; // The number of the {.|.|.} region we are in. 1383 const char *LastEmitted = AsmStr; // One past the last character emitted. 1384 1385 while (*LastEmitted) { 1386 switch (*LastEmitted) { 1387 default: { 1388 // Not a special case, emit the string section literally. 1389 const char *LiteralEnd = LastEmitted+1; 1390 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && 1391 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') 1392 ++LiteralEnd; 1393 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1394 O.write(LastEmitted, LiteralEnd-LastEmitted); 1395 LastEmitted = LiteralEnd; 1396 break; 1397 } 1398 case '\n': 1399 ++LastEmitted; // Consume newline character. 1400 O << '\n'; // Indent code with newline. 1401 break; 1402 case '$': { 1403 ++LastEmitted; // Consume '$' character. 1404 bool Done = true; 1405 1406 // Handle escapes. 1407 switch (*LastEmitted) { 1408 default: Done = false; break; 1409 case '$': // $$ -> $ 1410 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1411 O << '$'; 1412 ++LastEmitted; // Consume second '$' character. 1413 break; 1414 case '(': // $( -> same as GCC's { character. 1415 ++LastEmitted; // Consume '(' character. 1416 if (CurVariant != -1) { 1417 llvm_report_error("Nested variants found in inline asm string: '" 1418 + std::string(AsmStr) + "'"); 1419 } 1420 CurVariant = 0; // We're in the first variant now. 1421 break; 1422 case '|': 1423 ++LastEmitted; // consume '|' character. 1424 if (CurVariant == -1) 1425 O << '|'; // this is gcc's behavior for | outside a variant 1426 else 1427 ++CurVariant; // We're in the next variant. 1428 break; 1429 case ')': // $) -> same as GCC's } char. 1430 ++LastEmitted; // consume ')' character. 1431 if (CurVariant == -1) 1432 O << '}'; // this is gcc's behavior for } outside a variant 1433 else 1434 CurVariant = -1; 1435 break; 1436 } 1437 if (Done) break; 1438 1439 bool HasCurlyBraces = false; 1440 if (*LastEmitted == '{') { // ${variable} 1441 ++LastEmitted; // Consume '{' character. 1442 HasCurlyBraces = true; 1443 } 1444 1445 // If we have ${:foo}, then this is not a real operand reference, it is a 1446 // "magic" string reference, just like in .td files. Arrange to call 1447 // PrintSpecial. 1448 if (HasCurlyBraces && *LastEmitted == ':') { 1449 ++LastEmitted; 1450 const char *StrStart = LastEmitted; 1451 const char *StrEnd = strchr(StrStart, '}'); 1452 if (StrEnd == 0) { 1453 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 1454 + std::string(AsmStr) + "'"); 1455 } 1456 1457 std::string Val(StrStart, StrEnd); 1458 PrintSpecial(MI, Val.c_str()); 1459 LastEmitted = StrEnd+1; 1460 break; 1461 } 1462 1463 const char *IDStart = LastEmitted; 1464 char *IDEnd; 1465 errno = 0; 1466 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs. 1467 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) { 1468 llvm_report_error("Bad $ operand number in inline asm string: '" 1469 + std::string(AsmStr) + "'"); 1470 } 1471 LastEmitted = IDEnd; 1472 1473 char Modifier[2] = { 0, 0 }; 1474 1475 if (HasCurlyBraces) { 1476 // If we have curly braces, check for a modifier character. This 1477 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. 1478 if (*LastEmitted == ':') { 1479 ++LastEmitted; // Consume ':' character. 1480 if (*LastEmitted == 0) { 1481 llvm_report_error("Bad ${:} expression in inline asm string: '" 1482 + std::string(AsmStr) + "'"); 1483 } 1484 1485 Modifier[0] = *LastEmitted; 1486 ++LastEmitted; // Consume modifier character. 1487 } 1488 1489 if (*LastEmitted != '}') { 1490 llvm_report_error("Bad ${} expression in inline asm string: '" 1491 + std::string(AsmStr) + "'"); 1492 } 1493 ++LastEmitted; // Consume '}' character. 1494 } 1495 1496 if ((unsigned)Val >= NumOperands-1) { 1497 llvm_report_error("Invalid $ operand number in inline asm string: '" 1498 + std::string(AsmStr) + "'"); 1499 } 1500 1501 // Okay, we finally have a value number. Ask the target to print this 1502 // operand! 1503 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { 1504 unsigned OpNo = 1; 1505 1506 bool Error = false; 1507 1508 // Scan to find the machine operand number for the operand. 1509 for (; Val; --Val) { 1510 if (OpNo >= MI->getNumOperands()) break; 1511 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1512 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; 1513 } 1514 1515 if (OpNo >= MI->getNumOperands()) { 1516 Error = true; 1517 } else { 1518 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1519 ++OpNo; // Skip over the ID number. 1520 1521 if (Modifier[0] == 'l') // labels are target independent 1522 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber()); 1523 else { 1524 AsmPrinter *AP = const_cast<AsmPrinter*>(this); 1525 if ((OpFlags & 7) == 4) { 1526 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, 1527 Modifier[0] ? Modifier : 0); 1528 } else { 1529 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, 1530 Modifier[0] ? Modifier : 0); 1531 } 1532 } 1533 } 1534 if (Error) { 1535 std::string msg; 1536 raw_string_ostream Msg(msg); 1537 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n"; 1538 MI->print(Msg); 1539 llvm_report_error(Msg.str()); 1540 } 1541 } 1542 break; 1543 } 1544 } 1545 } 1546 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd(); 1547} 1548 1549/// printImplicitDef - This method prints the specified machine instruction 1550/// that is an implicit def. 1551void AsmPrinter::printImplicitDef(const MachineInstr *MI) const { 1552 if (!VerboseAsm) return; 1553 O.PadToColumn(MAI->getCommentColumn()); 1554 O << MAI->getCommentString() << " implicit-def: " 1555 << TRI->getName(MI->getOperand(0).getReg()); 1556} 1557 1558void AsmPrinter::printKill(const MachineInstr *MI) const { 1559 if (!VerboseAsm) return; 1560 O.PadToColumn(MAI->getCommentColumn()); 1561 O << MAI->getCommentString() << " kill:"; 1562 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) { 1563 const MachineOperand &op = MI->getOperand(n); 1564 assert(op.isReg() && "KILL instruction must have only register operands"); 1565 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>"); 1566 } 1567} 1568 1569/// printLabel - This method prints a local label used by debug and 1570/// exception handling tables. 1571void AsmPrinter::printLabel(const MachineInstr *MI) const { 1572 printLabel(MI->getOperand(0).getImm()); 1573} 1574 1575void AsmPrinter::printLabel(unsigned Id) const { 1576 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':'; 1577} 1578 1579/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM 1580/// instruction, using the specified assembler variant. Targets should 1581/// override this to format as appropriate. 1582bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1583 unsigned AsmVariant, const char *ExtraCode) { 1584 // Target doesn't support this yet! 1585 return true; 1586} 1587 1588bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 1589 unsigned AsmVariant, 1590 const char *ExtraCode) { 1591 // Target doesn't support this yet! 1592 return true; 1593} 1594 1595MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA, 1596 const char *Suffix) const { 1597 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix); 1598} 1599 1600MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F, 1601 const BasicBlock *BB, 1602 const char *Suffix) const { 1603 assert(BB->hasName() && 1604 "Address of anonymous basic block not supported yet!"); 1605 1606 // This code must use the function name itself, and not the function number, 1607 // since it must be possible to generate the label name from within other 1608 // functions. 1609 SmallString<60> FnName; 1610 Mang->getNameWithPrefix(FnName, F, false); 1611 1612 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME! 1613 SmallString<60> NameResult; 1614 Mang->getNameWithPrefix(NameResult, 1615 StringRef("BA") + Twine((unsigned)FnName.size()) + 1616 "_" + FnName.str() + "_" + BB->getName() + Suffix, 1617 Mangler::Private); 1618 1619 return OutContext.GetOrCreateSymbol(NameResult.str()); 1620} 1621 1622MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const { 1623 SmallString<60> Name; 1624 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB" 1625 << getFunctionNumber() << '_' << MBBID; 1626 1627 return OutContext.GetOrCreateSymbol(Name.str()); 1628} 1629 1630/// GetGlobalValueSymbol - Return the MCSymbol for the specified global 1631/// value. 1632MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const { 1633 SmallString<60> NameStr; 1634 Mang->getNameWithPrefix(NameStr, GV, false); 1635 return OutContext.GetOrCreateSymbol(NameStr.str()); 1636} 1637 1638/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 1639/// global value name as its base, with the specified suffix, and where the 1640/// symbol is forced to have private linkage if ForcePrivate is true. 1641MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 1642 StringRef Suffix, 1643 bool ForcePrivate) const { 1644 SmallString<60> NameStr; 1645 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 1646 NameStr.append(Suffix.begin(), Suffix.end()); 1647 return OutContext.GetOrCreateSymbol(NameStr.str()); 1648} 1649 1650/// GetExternalSymbolSymbol - Return the MCSymbol for the specified 1651/// ExternalSymbol. 1652MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 1653 SmallString<60> NameStr; 1654 Mang->getNameWithPrefix(NameStr, Sym); 1655 return OutContext.GetOrCreateSymbol(NameStr.str()); 1656} 1657 1658 1659/// EmitBasicBlockStart - This method prints the label for the specified 1660/// MachineBasicBlock, an alignment (if present) and a comment describing 1661/// it if appropriate. 1662void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 1663 // Emit an alignment directive for this block, if needed. 1664 if (unsigned Align = MBB->getAlignment()) 1665 EmitAlignment(Log2_32(Align)); 1666 1667 // If the block has its address taken, emit a special label to satisfy 1668 // references to the block. This is done so that we don't need to 1669 // remember the number of this label, and so that we can make 1670 // forward references to labels without knowing what their numbers 1671 // will be. 1672 if (MBB->hasAddressTaken()) { 1673 const BasicBlock *BB = MBB->getBasicBlock(); 1674 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB)); 1675 if (VerboseAsm) { 1676 O.PadToColumn(MAI->getCommentColumn()); 1677 O << MAI->getCommentString() << " Address Taken" << '\n'; 1678 } 1679 } 1680 1681 // Print the main label for the block. 1682 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) { 1683 if (VerboseAsm) 1684 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':'; 1685 } else { 1686 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber())); 1687 } 1688 1689 // Print some comments to accompany the label. 1690 if (VerboseAsm) { 1691 if (const BasicBlock *BB = MBB->getBasicBlock()) 1692 if (BB->hasName()) { 1693 O.PadToColumn(MAI->getCommentColumn()); 1694 O << MAI->getCommentString() << ' '; 1695 WriteAsOperand(O, BB, /*PrintType=*/false); 1696 } 1697 1698 EmitComments(*MBB); 1699 O << '\n'; 1700 } 1701} 1702 1703/// printPICJumpTableSetLabel - This method prints a set label for the 1704/// specified MachineBasicBlock for a jumptable entry. 1705void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 1706 const MachineBasicBlock *MBB) const { 1707 if (!MAI->getSetDirective()) 1708 return; 1709 1710 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1711 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',' 1712 << *GetMBBSymbol(MBB->getNumber()) 1713 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1714 << '_' << uid << '\n'; 1715} 1716 1717void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2, 1718 const MachineBasicBlock *MBB) const { 1719 if (!MAI->getSetDirective()) 1720 return; 1721 1722 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1723 << getFunctionNumber() << '_' << uid << '_' << uid2 1724 << "_set_" << MBB->getNumber() << ',' 1725 << *GetMBBSymbol(MBB->getNumber()) 1726 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1727 << '_' << uid << '_' << uid2 << '\n'; 1728} 1729 1730void AsmPrinter::printVisibility(const MCSymbol *Sym, 1731 unsigned Visibility) const { 1732 if (Visibility == GlobalValue::HiddenVisibility) { 1733 if (const char *Directive = MAI->getHiddenDirective()) 1734 O << Directive << *Sym << '\n'; 1735 } else if (Visibility == GlobalValue::ProtectedVisibility) { 1736 if (const char *Directive = MAI->getProtectedDirective()) 1737 O << Directive << *Sym << '\n'; 1738 } 1739} 1740 1741void AsmPrinter::printOffset(int64_t Offset) const { 1742 if (Offset > 0) 1743 O << '+' << Offset; 1744 else if (Offset < 0) 1745 O << Offset; 1746} 1747 1748GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 1749 if (!S->usesMetadata()) 1750 return 0; 1751 1752 gcp_iterator GCPI = GCMetadataPrinters.find(S); 1753 if (GCPI != GCMetadataPrinters.end()) 1754 return GCPI->second; 1755 1756 const char *Name = S->getName().c_str(); 1757 1758 for (GCMetadataPrinterRegistry::iterator 1759 I = GCMetadataPrinterRegistry::begin(), 1760 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 1761 if (strcmp(Name, I->getName()) == 0) { 1762 GCMetadataPrinter *GMP = I->instantiate(); 1763 GMP->S = S; 1764 GCMetadataPrinters.insert(std::make_pair(S, GMP)); 1765 return GMP; 1766 } 1767 1768 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n"; 1769 llvm_unreachable(0); 1770} 1771 1772/// EmitComments - Pretty-print comments for instructions 1773void AsmPrinter::EmitComments(const MachineInstr &MI) const { 1774 if (!VerboseAsm) 1775 return; 1776 1777 bool Newline = false; 1778 1779 if (!MI.getDebugLoc().isUnknown()) { 1780 DILocation DLT = MF->getDILocation(MI.getDebugLoc()); 1781 1782 // Print source line info. 1783 O.PadToColumn(MAI->getCommentColumn()); 1784 O << MAI->getCommentString() << ' '; 1785 DIScope Scope = DLT.getScope(); 1786 // Omit the directory, because it's likely to be long and uninteresting. 1787 if (!Scope.isNull()) 1788 O << Scope.getFilename(); 1789 else 1790 O << "<unknown>"; 1791 O << ':' << DLT.getLineNumber(); 1792 if (DLT.getColumnNumber() != 0) 1793 O << ':' << DLT.getColumnNumber(); 1794 Newline = true; 1795 } 1796 1797 // Check for spills and reloads 1798 int FI; 1799 1800 const MachineFrameInfo *FrameInfo = 1801 MI.getParent()->getParent()->getFrameInfo(); 1802 1803 // We assume a single instruction only has a spill or reload, not 1804 // both. 1805 const MachineMemOperand *MMO; 1806 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) { 1807 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1808 MMO = *MI.memoperands_begin(); 1809 if (Newline) O << '\n'; 1810 O.PadToColumn(MAI->getCommentColumn()); 1811 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload"; 1812 Newline = true; 1813 } 1814 } 1815 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) { 1816 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1817 if (Newline) O << '\n'; 1818 O.PadToColumn(MAI->getCommentColumn()); 1819 O << MAI->getCommentString() << ' ' 1820 << MMO->getSize() << "-byte Folded Reload"; 1821 Newline = true; 1822 } 1823 } 1824 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) { 1825 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1826 MMO = *MI.memoperands_begin(); 1827 if (Newline) O << '\n'; 1828 O.PadToColumn(MAI->getCommentColumn()); 1829 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill"; 1830 Newline = true; 1831 } 1832 } 1833 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) { 1834 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1835 if (Newline) O << '\n'; 1836 O.PadToColumn(MAI->getCommentColumn()); 1837 O << MAI->getCommentString() << ' ' 1838 << MMO->getSize() << "-byte Folded Spill"; 1839 Newline = true; 1840 } 1841 } 1842 1843 // Check for spill-induced copies 1844 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 1845 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg, 1846 SrcSubIdx, DstSubIdx)) { 1847 if (MI.getAsmPrinterFlag(ReloadReuse)) { 1848 if (Newline) O << '\n'; 1849 O.PadToColumn(MAI->getCommentColumn()); 1850 O << MAI->getCommentString() << " Reload Reuse"; 1851 } 1852 } 1853} 1854 1855/// PrintChildLoopComment - Print comments about child loops within 1856/// the loop for this basic block, with nesting. 1857/// 1858static void PrintChildLoopComment(formatted_raw_ostream &O, 1859 const MachineLoop *loop, 1860 const MCAsmInfo *MAI, 1861 int FunctionNumber) { 1862 // Add child loop information 1863 for(MachineLoop::iterator cl = loop->begin(), 1864 clend = loop->end(); 1865 cl != clend; 1866 ++cl) { 1867 MachineBasicBlock *Header = (*cl)->getHeader(); 1868 assert(Header && "No header for loop"); 1869 1870 O << '\n'; 1871 O.PadToColumn(MAI->getCommentColumn()); 1872 1873 O << MAI->getCommentString(); 1874 O.indent(((*cl)->getLoopDepth()-1)*2) 1875 << " Child Loop BB" << FunctionNumber << "_" 1876 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth(); 1877 1878 PrintChildLoopComment(O, *cl, MAI, FunctionNumber); 1879 } 1880} 1881 1882/// EmitComments - Pretty-print comments for basic blocks 1883void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const { 1884 if (VerboseAsm) { 1885 // Add loop depth information 1886 const MachineLoop *loop = LI->getLoopFor(&MBB); 1887 1888 if (loop) { 1889 // Print a newline after bb# annotation. 1890 O << "\n"; 1891 O.PadToColumn(MAI->getCommentColumn()); 1892 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth() 1893 << '\n'; 1894 1895 O.PadToColumn(MAI->getCommentColumn()); 1896 1897 MachineBasicBlock *Header = loop->getHeader(); 1898 assert(Header && "No header for loop"); 1899 1900 if (Header == &MBB) { 1901 O << MAI->getCommentString() << " Loop Header"; 1902 PrintChildLoopComment(O, loop, MAI, getFunctionNumber()); 1903 } 1904 else { 1905 O << MAI->getCommentString() << " Loop Header is BB" 1906 << getFunctionNumber() << "_" << loop->getHeader()->getNumber(); 1907 } 1908 1909 if (loop->empty()) { 1910 O << '\n'; 1911 O.PadToColumn(MAI->getCommentColumn()); 1912 O << MAI->getCommentString() << " Inner Loop"; 1913 } 1914 1915 // Add parent loop information 1916 for (const MachineLoop *CurLoop = loop->getParentLoop(); 1917 CurLoop; 1918 CurLoop = CurLoop->getParentLoop()) { 1919 MachineBasicBlock *Header = CurLoop->getHeader(); 1920 assert(Header && "No header for loop"); 1921 1922 O << '\n'; 1923 O.PadToColumn(MAI->getCommentColumn()); 1924 O << MAI->getCommentString(); 1925 O.indent((CurLoop->getLoopDepth()-1)*2) 1926 << " Inside Loop BB" << getFunctionNumber() << "_" 1927 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth(); 1928 } 1929 } 1930 } 1931} 1932