AsmPrinter.cpp revision d32c7cfa248f685e6e3064c0958dc2f0c31a4df6
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 SmallString<128> TmpBuffer; 1130 1131 // FP Constants are printed as integer constants to avoid losing 1132 // precision. 1133 if (CFP->getType()->isDoubleTy()) { 1134 if (AP.VerboseAsm) { 1135 raw_svector_ostream OS(TmpBuffer); 1136 double Val = CFP->getValueAPF().convertToDouble(); // for comment only 1137 OS << "double " << Val; 1138 AP.OutStreamer.AddComment(OS.str()); 1139 } 1140 1141 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1142 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1143 return; 1144 } 1145 1146 if (CFP->getType()->isFloatTy()) { 1147 if (AP.VerboseAsm) { 1148 float Val = CFP->getValueAPF().convertToFloat(); // for comment only 1149 AP.O.PadToColumn(AP.MAI->getCommentColumn()); 1150 AP.O << AP.MAI->getCommentString() << " float " << Val << '\n'; 1151 } 1152 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1153 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace); 1154 return; 1155 } 1156 1157 if (CFP->getType()->isX86_FP80Ty()) { 1158 // all long double variants are printed as hex 1159 // api needed to prevent premature destruction 1160 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1161 const uint64_t *p = API.getRawData(); 1162 if (AP.VerboseAsm) { 1163 // Convert to double so we can print the approximate val as a comment. 1164 APFloat DoubleVal = CFP->getValueAPF(); 1165 bool ignored; 1166 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1167 &ignored); 1168 AP.O.PadToColumn(AP.MAI->getCommentColumn()); 1169 AP.O << AP.MAI->getCommentString() << " x86_fp80 ~= " 1170 << DoubleVal.convertToDouble() << '\n'; 1171 } 1172 1173 if (AP.TM.getTargetData()->isBigEndian()) { 1174 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1175 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1176 } else { 1177 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1178 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1179 } 1180 1181 // Emit the tail padding for the long double. 1182 const TargetData &TD = *AP.TM.getTargetData(); 1183 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) - 1184 TD.getTypeStoreSize(CFP->getType()), AddrSpace); 1185 return; 1186 } 1187 1188 assert(CFP->getType()->isPPC_FP128Ty() && 1189 "Floating point constant type not handled"); 1190 // All long double variants are printed as hex api needed to prevent 1191 // premature destruction. 1192 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1193 const uint64_t *p = API.getRawData(); 1194 if (AP.TM.getTargetData()->isBigEndian()) { 1195 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1196 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1197 } else { 1198 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1199 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1200 } 1201} 1202 1203static void EmitGlobalConstantLargeInt(const ConstantInt *CI, 1204 unsigned AddrSpace, AsmPrinter &AP) { 1205 const TargetData *TD = AP.TM.getTargetData(); 1206 unsigned BitWidth = CI->getBitWidth(); 1207 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits"); 1208 1209 // We don't expect assemblers to support integer data directives 1210 // for more than 64 bits, so we emit the data in at most 64-bit 1211 // quantities at a time. 1212 const uint64_t *RawData = CI->getValue().getRawData(); 1213 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1214 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i]; 1215 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1216 } 1217} 1218 1219/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1220void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1221 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) { 1222 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1223 return OutStreamer.EmitZeros(Size, AddrSpace); 1224 } 1225 1226 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1227 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1228 switch (Size) { 1229 case 1: 1230 case 2: 1231 case 4: 1232 case 8: 1233 if (VerboseAsm) { 1234 O.PadToColumn(MAI->getCommentColumn()); 1235 O << MAI->getCommentString() << " 0x"; 1236 O.write_hex(CI->getZExtValue()); 1237 O << '\n'; 1238 } 1239 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace); 1240 return; 1241 default: 1242 EmitGlobalConstantLargeInt(CI, AddrSpace, *this); 1243 return; 1244 } 1245 } 1246 1247 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 1248 return EmitGlobalConstantArray(CVA, AddrSpace, *this); 1249 1250 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 1251 return EmitGlobalConstantStruct(CVS, AddrSpace, *this); 1252 1253 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 1254 return EmitGlobalConstantFP(CFP, AddrSpace, *this); 1255 1256 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 1257 return EmitGlobalConstantVector(V, AddrSpace, *this); 1258 1259 if (isa<ConstantPointerNull>(CV)) { 1260 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1261 OutStreamer.EmitIntValue(0, Size, AddrSpace); 1262 return; 1263 } 1264 1265 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit 1266 // the expression value. 1267 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) { 1268 case 0: return; 1269 case 1: O << MAI->getData8bitsDirective(AddrSpace); break; 1270 case 2: O << MAI->getData16bitsDirective(AddrSpace); break; 1271 case 4: O << MAI->getData32bitsDirective(AddrSpace); break; 1272 case 8: 1273 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) { 1274 O << Dir; 1275 break; 1276 } 1277 // FALL THROUGH. 1278 default: 1279 llvm_unreachable("Target cannot handle given data directive width!"); 1280 return; 1281 } 1282 1283 EmitConstantValueOnly(CV); 1284 O << '\n'; 1285} 1286 1287void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1288 // Target doesn't support this yet! 1289 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1290} 1291 1292/// PrintSpecial - Print information related to the specified machine instr 1293/// that is independent of the operand, and may be independent of the instr 1294/// itself. This can be useful for portably encoding the comment character 1295/// or other bits of target-specific knowledge into the asmstrings. The 1296/// syntax used is ${:comment}. Targets can override this to add support 1297/// for their own strange codes. 1298void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const { 1299 if (!strcmp(Code, "private")) { 1300 O << MAI->getPrivateGlobalPrefix(); 1301 } else if (!strcmp(Code, "comment")) { 1302 if (VerboseAsm) 1303 O << MAI->getCommentString(); 1304 } else if (!strcmp(Code, "uid")) { 1305 // Comparing the address of MI isn't sufficient, because machineinstrs may 1306 // be allocated to the same address across functions. 1307 const Function *ThisF = MI->getParent()->getParent()->getFunction(); 1308 1309 // If this is a new LastFn instruction, bump the counter. 1310 if (LastMI != MI || LastFn != ThisF) { 1311 ++Counter; 1312 LastMI = MI; 1313 LastFn = ThisF; 1314 } 1315 O << Counter; 1316 } else { 1317 std::string msg; 1318 raw_string_ostream Msg(msg); 1319 Msg << "Unknown special formatter '" << Code 1320 << "' for machine instr: " << *MI; 1321 llvm_report_error(Msg.str()); 1322 } 1323} 1324 1325/// processDebugLoc - Processes the debug information of each machine 1326/// instruction's DebugLoc. 1327void AsmPrinter::processDebugLoc(const MachineInstr *MI, 1328 bool BeforePrintingInsn) { 1329 if (!MAI || !DW || !MAI->doesSupportDebugInformation() 1330 || !DW->ShouldEmitDwarfDebug()) 1331 return; 1332 DebugLoc DL = MI->getDebugLoc(); 1333 if (DL.isUnknown()) 1334 return; 1335 DILocation CurDLT = MF->getDILocation(DL); 1336 if (CurDLT.getScope().isNull()) 1337 return; 1338 1339 if (!BeforePrintingInsn) { 1340 // After printing instruction 1341 DW->EndScope(MI); 1342 } else if (CurDLT.getNode() != PrevDLT) { 1343 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 1344 CurDLT.getColumnNumber(), 1345 CurDLT.getScope().getNode()); 1346 printLabel(L); 1347 O << '\n'; 1348 DW->BeginScope(MI, L); 1349 PrevDLT = CurDLT.getNode(); 1350 } 1351} 1352 1353 1354/// printInlineAsm - This method formats and prints the specified machine 1355/// instruction that is an inline asm. 1356void AsmPrinter::printInlineAsm(const MachineInstr *MI) const { 1357 unsigned NumOperands = MI->getNumOperands(); 1358 1359 // Count the number of register definitions. 1360 unsigned NumDefs = 0; 1361 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 1362 ++NumDefs) 1363 assert(NumDefs != NumOperands-1 && "No asm string?"); 1364 1365 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); 1366 1367 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. 1368 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 1369 1370 O << '\t'; 1371 1372 // If this asmstr is empty, just print the #APP/#NOAPP markers. 1373 // These are useful to see where empty asm's wound up. 1374 if (AsmStr[0] == 0) { 1375 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1376 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n'; 1377 return; 1378 } 1379 1380 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1381 1382 // The variant of the current asmprinter. 1383 int AsmPrinterVariant = MAI->getAssemblerDialect(); 1384 1385 int CurVariant = -1; // The number of the {.|.|.} region we are in. 1386 const char *LastEmitted = AsmStr; // One past the last character emitted. 1387 1388 while (*LastEmitted) { 1389 switch (*LastEmitted) { 1390 default: { 1391 // Not a special case, emit the string section literally. 1392 const char *LiteralEnd = LastEmitted+1; 1393 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && 1394 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') 1395 ++LiteralEnd; 1396 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1397 O.write(LastEmitted, LiteralEnd-LastEmitted); 1398 LastEmitted = LiteralEnd; 1399 break; 1400 } 1401 case '\n': 1402 ++LastEmitted; // Consume newline character. 1403 O << '\n'; // Indent code with newline. 1404 break; 1405 case '$': { 1406 ++LastEmitted; // Consume '$' character. 1407 bool Done = true; 1408 1409 // Handle escapes. 1410 switch (*LastEmitted) { 1411 default: Done = false; break; 1412 case '$': // $$ -> $ 1413 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1414 O << '$'; 1415 ++LastEmitted; // Consume second '$' character. 1416 break; 1417 case '(': // $( -> same as GCC's { character. 1418 ++LastEmitted; // Consume '(' character. 1419 if (CurVariant != -1) { 1420 llvm_report_error("Nested variants found in inline asm string: '" 1421 + std::string(AsmStr) + "'"); 1422 } 1423 CurVariant = 0; // We're in the first variant now. 1424 break; 1425 case '|': 1426 ++LastEmitted; // consume '|' character. 1427 if (CurVariant == -1) 1428 O << '|'; // this is gcc's behavior for | outside a variant 1429 else 1430 ++CurVariant; // We're in the next variant. 1431 break; 1432 case ')': // $) -> same as GCC's } char. 1433 ++LastEmitted; // consume ')' character. 1434 if (CurVariant == -1) 1435 O << '}'; // this is gcc's behavior for } outside a variant 1436 else 1437 CurVariant = -1; 1438 break; 1439 } 1440 if (Done) break; 1441 1442 bool HasCurlyBraces = false; 1443 if (*LastEmitted == '{') { // ${variable} 1444 ++LastEmitted; // Consume '{' character. 1445 HasCurlyBraces = true; 1446 } 1447 1448 // If we have ${:foo}, then this is not a real operand reference, it is a 1449 // "magic" string reference, just like in .td files. Arrange to call 1450 // PrintSpecial. 1451 if (HasCurlyBraces && *LastEmitted == ':') { 1452 ++LastEmitted; 1453 const char *StrStart = LastEmitted; 1454 const char *StrEnd = strchr(StrStart, '}'); 1455 if (StrEnd == 0) { 1456 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 1457 + std::string(AsmStr) + "'"); 1458 } 1459 1460 std::string Val(StrStart, StrEnd); 1461 PrintSpecial(MI, Val.c_str()); 1462 LastEmitted = StrEnd+1; 1463 break; 1464 } 1465 1466 const char *IDStart = LastEmitted; 1467 char *IDEnd; 1468 errno = 0; 1469 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs. 1470 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) { 1471 llvm_report_error("Bad $ operand number in inline asm string: '" 1472 + std::string(AsmStr) + "'"); 1473 } 1474 LastEmitted = IDEnd; 1475 1476 char Modifier[2] = { 0, 0 }; 1477 1478 if (HasCurlyBraces) { 1479 // If we have curly braces, check for a modifier character. This 1480 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. 1481 if (*LastEmitted == ':') { 1482 ++LastEmitted; // Consume ':' character. 1483 if (*LastEmitted == 0) { 1484 llvm_report_error("Bad ${:} expression in inline asm string: '" 1485 + std::string(AsmStr) + "'"); 1486 } 1487 1488 Modifier[0] = *LastEmitted; 1489 ++LastEmitted; // Consume modifier character. 1490 } 1491 1492 if (*LastEmitted != '}') { 1493 llvm_report_error("Bad ${} expression in inline asm string: '" 1494 + std::string(AsmStr) + "'"); 1495 } 1496 ++LastEmitted; // Consume '}' character. 1497 } 1498 1499 if ((unsigned)Val >= NumOperands-1) { 1500 llvm_report_error("Invalid $ operand number in inline asm string: '" 1501 + std::string(AsmStr) + "'"); 1502 } 1503 1504 // Okay, we finally have a value number. Ask the target to print this 1505 // operand! 1506 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { 1507 unsigned OpNo = 1; 1508 1509 bool Error = false; 1510 1511 // Scan to find the machine operand number for the operand. 1512 for (; Val; --Val) { 1513 if (OpNo >= MI->getNumOperands()) break; 1514 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1515 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; 1516 } 1517 1518 if (OpNo >= MI->getNumOperands()) { 1519 Error = true; 1520 } else { 1521 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1522 ++OpNo; // Skip over the ID number. 1523 1524 if (Modifier[0] == 'l') // labels are target independent 1525 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber()); 1526 else { 1527 AsmPrinter *AP = const_cast<AsmPrinter*>(this); 1528 if ((OpFlags & 7) == 4) { 1529 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, 1530 Modifier[0] ? Modifier : 0); 1531 } else { 1532 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, 1533 Modifier[0] ? Modifier : 0); 1534 } 1535 } 1536 } 1537 if (Error) { 1538 std::string msg; 1539 raw_string_ostream Msg(msg); 1540 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n"; 1541 MI->print(Msg); 1542 llvm_report_error(Msg.str()); 1543 } 1544 } 1545 break; 1546 } 1547 } 1548 } 1549 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd(); 1550} 1551 1552/// printImplicitDef - This method prints the specified machine instruction 1553/// that is an implicit def. 1554void AsmPrinter::printImplicitDef(const MachineInstr *MI) const { 1555 if (!VerboseAsm) return; 1556 O.PadToColumn(MAI->getCommentColumn()); 1557 O << MAI->getCommentString() << " implicit-def: " 1558 << TRI->getName(MI->getOperand(0).getReg()); 1559} 1560 1561void AsmPrinter::printKill(const MachineInstr *MI) const { 1562 if (!VerboseAsm) return; 1563 O.PadToColumn(MAI->getCommentColumn()); 1564 O << MAI->getCommentString() << " kill:"; 1565 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) { 1566 const MachineOperand &op = MI->getOperand(n); 1567 assert(op.isReg() && "KILL instruction must have only register operands"); 1568 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>"); 1569 } 1570} 1571 1572/// printLabel - This method prints a local label used by debug and 1573/// exception handling tables. 1574void AsmPrinter::printLabel(const MachineInstr *MI) const { 1575 printLabel(MI->getOperand(0).getImm()); 1576} 1577 1578void AsmPrinter::printLabel(unsigned Id) const { 1579 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':'; 1580} 1581 1582/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM 1583/// instruction, using the specified assembler variant. Targets should 1584/// override this to format as appropriate. 1585bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1586 unsigned AsmVariant, const char *ExtraCode) { 1587 // Target doesn't support this yet! 1588 return true; 1589} 1590 1591bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 1592 unsigned AsmVariant, 1593 const char *ExtraCode) { 1594 // Target doesn't support this yet! 1595 return true; 1596} 1597 1598MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA, 1599 const char *Suffix) const { 1600 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix); 1601} 1602 1603MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F, 1604 const BasicBlock *BB, 1605 const char *Suffix) const { 1606 assert(BB->hasName() && 1607 "Address of anonymous basic block not supported yet!"); 1608 1609 // This code must use the function name itself, and not the function number, 1610 // since it must be possible to generate the label name from within other 1611 // functions. 1612 SmallString<60> FnName; 1613 Mang->getNameWithPrefix(FnName, F, false); 1614 1615 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME! 1616 SmallString<60> NameResult; 1617 Mang->getNameWithPrefix(NameResult, 1618 StringRef("BA") + Twine((unsigned)FnName.size()) + 1619 "_" + FnName.str() + "_" + BB->getName() + Suffix, 1620 Mangler::Private); 1621 1622 return OutContext.GetOrCreateSymbol(NameResult.str()); 1623} 1624 1625MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const { 1626 SmallString<60> Name; 1627 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB" 1628 << getFunctionNumber() << '_' << MBBID; 1629 1630 return OutContext.GetOrCreateSymbol(Name.str()); 1631} 1632 1633/// GetGlobalValueSymbol - Return the MCSymbol for the specified global 1634/// value. 1635MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const { 1636 SmallString<60> NameStr; 1637 Mang->getNameWithPrefix(NameStr, GV, false); 1638 return OutContext.GetOrCreateSymbol(NameStr.str()); 1639} 1640 1641/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 1642/// global value name as its base, with the specified suffix, and where the 1643/// symbol is forced to have private linkage if ForcePrivate is true. 1644MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 1645 StringRef Suffix, 1646 bool ForcePrivate) const { 1647 SmallString<60> NameStr; 1648 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 1649 NameStr.append(Suffix.begin(), Suffix.end()); 1650 return OutContext.GetOrCreateSymbol(NameStr.str()); 1651} 1652 1653/// GetExternalSymbolSymbol - Return the MCSymbol for the specified 1654/// ExternalSymbol. 1655MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 1656 SmallString<60> NameStr; 1657 Mang->getNameWithPrefix(NameStr, Sym); 1658 return OutContext.GetOrCreateSymbol(NameStr.str()); 1659} 1660 1661 1662/// EmitBasicBlockStart - This method prints the label for the specified 1663/// MachineBasicBlock, an alignment (if present) and a comment describing 1664/// it if appropriate. 1665void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 1666 // Emit an alignment directive for this block, if needed. 1667 if (unsigned Align = MBB->getAlignment()) 1668 EmitAlignment(Log2_32(Align)); 1669 1670 // If the block has its address taken, emit a special label to satisfy 1671 // references to the block. This is done so that we don't need to 1672 // remember the number of this label, and so that we can make 1673 // forward references to labels without knowing what their numbers 1674 // will be. 1675 if (MBB->hasAddressTaken()) { 1676 const BasicBlock *BB = MBB->getBasicBlock(); 1677 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB)); 1678 if (VerboseAsm) { 1679 O.PadToColumn(MAI->getCommentColumn()); 1680 O << MAI->getCommentString() << " Address Taken" << '\n'; 1681 } 1682 } 1683 1684 // Print the main label for the block. 1685 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) { 1686 if (VerboseAsm) 1687 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':'; 1688 } else { 1689 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber())); 1690 } 1691 1692 // Print some comments to accompany the label. 1693 if (VerboseAsm) { 1694 if (const BasicBlock *BB = MBB->getBasicBlock()) 1695 if (BB->hasName()) { 1696 O.PadToColumn(MAI->getCommentColumn()); 1697 O << MAI->getCommentString() << ' '; 1698 WriteAsOperand(O, BB, /*PrintType=*/false); 1699 } 1700 1701 EmitComments(*MBB); 1702 O << '\n'; 1703 } 1704} 1705 1706/// printPICJumpTableSetLabel - This method prints a set label for the 1707/// specified MachineBasicBlock for a jumptable entry. 1708void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 1709 const MachineBasicBlock *MBB) const { 1710 if (!MAI->getSetDirective()) 1711 return; 1712 1713 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1714 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',' 1715 << *GetMBBSymbol(MBB->getNumber()) 1716 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1717 << '_' << uid << '\n'; 1718} 1719 1720void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2, 1721 const MachineBasicBlock *MBB) const { 1722 if (!MAI->getSetDirective()) 1723 return; 1724 1725 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1726 << getFunctionNumber() << '_' << uid << '_' << uid2 1727 << "_set_" << MBB->getNumber() << ',' 1728 << *GetMBBSymbol(MBB->getNumber()) 1729 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1730 << '_' << uid << '_' << uid2 << '\n'; 1731} 1732 1733void AsmPrinter::printVisibility(const MCSymbol *Sym, 1734 unsigned Visibility) const { 1735 if (Visibility == GlobalValue::HiddenVisibility) { 1736 if (const char *Directive = MAI->getHiddenDirective()) 1737 O << Directive << *Sym << '\n'; 1738 } else if (Visibility == GlobalValue::ProtectedVisibility) { 1739 if (const char *Directive = MAI->getProtectedDirective()) 1740 O << Directive << *Sym << '\n'; 1741 } 1742} 1743 1744void AsmPrinter::printOffset(int64_t Offset) const { 1745 if (Offset > 0) 1746 O << '+' << Offset; 1747 else if (Offset < 0) 1748 O << Offset; 1749} 1750 1751GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 1752 if (!S->usesMetadata()) 1753 return 0; 1754 1755 gcp_iterator GCPI = GCMetadataPrinters.find(S); 1756 if (GCPI != GCMetadataPrinters.end()) 1757 return GCPI->second; 1758 1759 const char *Name = S->getName().c_str(); 1760 1761 for (GCMetadataPrinterRegistry::iterator 1762 I = GCMetadataPrinterRegistry::begin(), 1763 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 1764 if (strcmp(Name, I->getName()) == 0) { 1765 GCMetadataPrinter *GMP = I->instantiate(); 1766 GMP->S = S; 1767 GCMetadataPrinters.insert(std::make_pair(S, GMP)); 1768 return GMP; 1769 } 1770 1771 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n"; 1772 llvm_unreachable(0); 1773} 1774 1775/// EmitComments - Pretty-print comments for instructions 1776void AsmPrinter::EmitComments(const MachineInstr &MI) const { 1777 if (!VerboseAsm) 1778 return; 1779 1780 bool Newline = false; 1781 1782 if (!MI.getDebugLoc().isUnknown()) { 1783 DILocation DLT = MF->getDILocation(MI.getDebugLoc()); 1784 1785 // Print source line info. 1786 O.PadToColumn(MAI->getCommentColumn()); 1787 O << MAI->getCommentString() << ' '; 1788 DIScope Scope = DLT.getScope(); 1789 // Omit the directory, because it's likely to be long and uninteresting. 1790 if (!Scope.isNull()) 1791 O << Scope.getFilename(); 1792 else 1793 O << "<unknown>"; 1794 O << ':' << DLT.getLineNumber(); 1795 if (DLT.getColumnNumber() != 0) 1796 O << ':' << DLT.getColumnNumber(); 1797 Newline = true; 1798 } 1799 1800 // Check for spills and reloads 1801 int FI; 1802 1803 const MachineFrameInfo *FrameInfo = 1804 MI.getParent()->getParent()->getFrameInfo(); 1805 1806 // We assume a single instruction only has a spill or reload, not 1807 // both. 1808 const MachineMemOperand *MMO; 1809 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) { 1810 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1811 MMO = *MI.memoperands_begin(); 1812 if (Newline) O << '\n'; 1813 O.PadToColumn(MAI->getCommentColumn()); 1814 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload"; 1815 Newline = true; 1816 } 1817 } 1818 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) { 1819 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1820 if (Newline) O << '\n'; 1821 O.PadToColumn(MAI->getCommentColumn()); 1822 O << MAI->getCommentString() << ' ' 1823 << MMO->getSize() << "-byte Folded Reload"; 1824 Newline = true; 1825 } 1826 } 1827 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) { 1828 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1829 MMO = *MI.memoperands_begin(); 1830 if (Newline) O << '\n'; 1831 O.PadToColumn(MAI->getCommentColumn()); 1832 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill"; 1833 Newline = true; 1834 } 1835 } 1836 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) { 1837 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1838 if (Newline) O << '\n'; 1839 O.PadToColumn(MAI->getCommentColumn()); 1840 O << MAI->getCommentString() << ' ' 1841 << MMO->getSize() << "-byte Folded Spill"; 1842 Newline = true; 1843 } 1844 } 1845 1846 // Check for spill-induced copies 1847 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 1848 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg, 1849 SrcSubIdx, DstSubIdx)) { 1850 if (MI.getAsmPrinterFlag(ReloadReuse)) { 1851 if (Newline) O << '\n'; 1852 O.PadToColumn(MAI->getCommentColumn()); 1853 O << MAI->getCommentString() << " Reload Reuse"; 1854 } 1855 } 1856} 1857 1858/// PrintChildLoopComment - Print comments about child loops within 1859/// the loop for this basic block, with nesting. 1860/// 1861static void PrintChildLoopComment(formatted_raw_ostream &O, 1862 const MachineLoop *loop, 1863 const MCAsmInfo *MAI, 1864 int FunctionNumber) { 1865 // Add child loop information 1866 for(MachineLoop::iterator cl = loop->begin(), 1867 clend = loop->end(); 1868 cl != clend; 1869 ++cl) { 1870 MachineBasicBlock *Header = (*cl)->getHeader(); 1871 assert(Header && "No header for loop"); 1872 1873 O << '\n'; 1874 O.PadToColumn(MAI->getCommentColumn()); 1875 1876 O << MAI->getCommentString(); 1877 O.indent(((*cl)->getLoopDepth()-1)*2) 1878 << " Child Loop BB" << FunctionNumber << "_" 1879 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth(); 1880 1881 PrintChildLoopComment(O, *cl, MAI, FunctionNumber); 1882 } 1883} 1884 1885/// EmitComments - Pretty-print comments for basic blocks 1886void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const { 1887 if (VerboseAsm) { 1888 // Add loop depth information 1889 const MachineLoop *loop = LI->getLoopFor(&MBB); 1890 1891 if (loop) { 1892 // Print a newline after bb# annotation. 1893 O << "\n"; 1894 O.PadToColumn(MAI->getCommentColumn()); 1895 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth() 1896 << '\n'; 1897 1898 O.PadToColumn(MAI->getCommentColumn()); 1899 1900 MachineBasicBlock *Header = loop->getHeader(); 1901 assert(Header && "No header for loop"); 1902 1903 if (Header == &MBB) { 1904 O << MAI->getCommentString() << " Loop Header"; 1905 PrintChildLoopComment(O, loop, MAI, getFunctionNumber()); 1906 } 1907 else { 1908 O << MAI->getCommentString() << " Loop Header is BB" 1909 << getFunctionNumber() << "_" << loop->getHeader()->getNumber(); 1910 } 1911 1912 if (loop->empty()) { 1913 O << '\n'; 1914 O.PadToColumn(MAI->getCommentColumn()); 1915 O << MAI->getCommentString() << " Inner Loop"; 1916 } 1917 1918 // Add parent loop information 1919 for (const MachineLoop *CurLoop = loop->getParentLoop(); 1920 CurLoop; 1921 CurLoop = CurLoop->getParentLoop()) { 1922 MachineBasicBlock *Header = CurLoop->getHeader(); 1923 assert(Header && "No header for loop"); 1924 1925 O << '\n'; 1926 O.PadToColumn(MAI->getCommentColumn()); 1927 O << MAI->getCommentString(); 1928 O.indent((CurLoop->getLoopDepth()-1)*2) 1929 << " Inside Loop BB" << getFunctionNumber() << "_" 1930 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth(); 1931 } 1932 } 1933 } 1934} 1935