PPCAsmPrinter.cpp revision f71cb9b3ed1d7b3e438e9990ce1587ba275e70bf
1//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=// 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 contains a printer that converts from our internal representation 11// of machine-dependent LLVM code to PowerPC assembly language. This printer is 12// the output mechanism used by `llc'. 13// 14// Documentation at http://developer.apple.com/documentation/DeveloperTools/ 15// Reference/Assembler/ASMIntroduction/chapter_1_section_1.html 16// 17//===----------------------------------------------------------------------===// 18 19#define DEBUG_TYPE "asmprinter" 20#include "PPC.h" 21#include "PPCPredicates.h" 22#include "PPCTargetMachine.h" 23#include "PPCSubtarget.h" 24#include "llvm/Constants.h" 25#include "llvm/DerivedTypes.h" 26#include "llvm/Module.h" 27#include "llvm/Assembly/Writer.h" 28#include "llvm/CodeGen/AsmPrinter.h" 29#include "llvm/CodeGen/DwarfWriter.h" 30#include "llvm/CodeGen/MachineModuleInfo.h" 31#include "llvm/CodeGen/MachineFunctionPass.h" 32#include "llvm/CodeGen/MachineInstr.h" 33#include "llvm/CodeGen/MachineInstrBuilder.h" 34#include "llvm/Support/Mangler.h" 35#include "llvm/Support/MathExtras.h" 36#include "llvm/Support/CommandLine.h" 37#include "llvm/Support/Debug.h" 38#include "llvm/Support/Compiler.h" 39#include "llvm/Target/TargetAsmInfo.h" 40#include "llvm/Target/TargetRegisterInfo.h" 41#include "llvm/Target/TargetInstrInfo.h" 42#include "llvm/Target/TargetOptions.h" 43#include "llvm/ADT/Statistic.h" 44#include "llvm/ADT/StringExtras.h" 45#include <set> 46using namespace llvm; 47 48STATISTIC(EmittedInsts, "Number of machine instrs printed"); 49 50namespace { 51 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter { 52 std::set<std::string> FnStubs, GVStubs; 53 const PPCSubtarget &Subtarget; 54 55 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T) 56 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) { 57 } 58 59 virtual const char *getPassName() const { 60 return "PowerPC Assembly Printer"; 61 } 62 63 PPCTargetMachine &getTM() { 64 return static_cast<PPCTargetMachine&>(TM); 65 } 66 67 unsigned enumRegToMachineReg(unsigned enumReg) { 68 switch (enumReg) { 69 default: assert(0 && "Unhandled register!"); break; 70 case PPC::CR0: return 0; 71 case PPC::CR1: return 1; 72 case PPC::CR2: return 2; 73 case PPC::CR3: return 3; 74 case PPC::CR4: return 4; 75 case PPC::CR5: return 5; 76 case PPC::CR6: return 6; 77 case PPC::CR7: return 7; 78 } 79 abort(); 80 } 81 82 /// printInstruction - This method is automatically generated by tablegen 83 /// from the instruction set description. This method returns true if the 84 /// machine instruction was sufficiently described to print it, otherwise it 85 /// returns false. 86 bool printInstruction(const MachineInstr *MI); 87 88 void printMachineInstruction(const MachineInstr *MI); 89 void printOp(const MachineOperand &MO); 90 91 /// stripRegisterPrefix - This method strips the character prefix from a 92 /// register name so that only the number is left. Used by for linux asm. 93 const char *stripRegisterPrefix(const char *RegName) { 94 switch (RegName[0]) { 95 case 'r': 96 case 'f': 97 case 'v': return RegName + 1; 98 case 'c': if (RegName[1] == 'r') return RegName + 2; 99 } 100 101 return RegName; 102 } 103 104 /// printRegister - Print register according to target requirements. 105 /// 106 void printRegister(const MachineOperand &MO, bool R0AsZero) { 107 unsigned RegNo = MO.getReg(); 108 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??"); 109 110 // If we should use 0 for R0. 111 if (R0AsZero && RegNo == PPC::R0) { 112 O << "0"; 113 return; 114 } 115 116 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName; 117 // Linux assembler (Others?) does not take register mnemonics. 118 // FIXME - What about special registers used in mfspr/mtspr? 119 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName); 120 O << RegName; 121 } 122 123 void printOperand(const MachineInstr *MI, unsigned OpNo) { 124 const MachineOperand &MO = MI->getOperand(OpNo); 125 if (MO.isRegister()) { 126 printRegister(MO, false); 127 } else if (MO.isImmediate()) { 128 O << MO.getImm(); 129 } else { 130 printOp(MO); 131 } 132 } 133 134 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 135 unsigned AsmVariant, const char *ExtraCode); 136 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 137 unsigned AsmVariant, const char *ExtraCode); 138 139 140 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) { 141 char value = MI->getOperand(OpNo).getImm(); 142 value = (value << (32-5)) >> (32-5); 143 O << (int)value; 144 } 145 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) { 146 unsigned char value = MI->getOperand(OpNo).getImm(); 147 assert(value <= 31 && "Invalid u5imm argument!"); 148 O << (unsigned int)value; 149 } 150 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) { 151 unsigned char value = MI->getOperand(OpNo).getImm(); 152 assert(value <= 63 && "Invalid u6imm argument!"); 153 O << (unsigned int)value; 154 } 155 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) { 156 O << (short)MI->getOperand(OpNo).getImm(); 157 } 158 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) { 159 O << (unsigned short)MI->getOperand(OpNo).getImm(); 160 } 161 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) { 162 if (MI->getOperand(OpNo).isImmediate()) { 163 O << (short)(MI->getOperand(OpNo).getImm()*4); 164 } else { 165 O << "lo16("; 166 printOp(MI->getOperand(OpNo)); 167 if (TM.getRelocationModel() == Reloc::PIC_) 168 O << "-\"L" << getFunctionNumber() << "$pb\")"; 169 else 170 O << ')'; 171 } 172 } 173 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) { 174 // Branches can take an immediate operand. This is used by the branch 175 // selection pass to print $+8, an eight byte displacement from the PC. 176 if (MI->getOperand(OpNo).isImmediate()) { 177 O << "$+" << MI->getOperand(OpNo).getImm()*4; 178 } else { 179 printOp(MI->getOperand(OpNo)); 180 } 181 } 182 void printCallOperand(const MachineInstr *MI, unsigned OpNo) { 183 const MachineOperand &MO = MI->getOperand(OpNo); 184 if (TM.getRelocationModel() != Reloc::Static) { 185 if (MO.getType() == MachineOperand::MO_GlobalAddress) { 186 GlobalValue *GV = MO.getGlobal(); 187 if (((GV->isDeclaration() || GV->hasWeakLinkage() || 188 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) { 189 // Dynamically-resolved functions need a stub for the function. 190 std::string Name = Mang->getValueName(GV); 191 FnStubs.insert(Name); 192 printSuffixedName(Name, "$stub"); 193 if (GV->hasExternalWeakLinkage()) 194 ExtWeakSymbols.insert(GV); 195 return; 196 } 197 } 198 if (MO.getType() == MachineOperand::MO_ExternalSymbol) { 199 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName(); 200 FnStubs.insert(Name); 201 printSuffixedName(Name, "$stub"); 202 return; 203 } 204 } 205 206 printOp(MI->getOperand(OpNo)); 207 } 208 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) { 209 O << (int)MI->getOperand(OpNo).getImm()*4; 210 } 211 void printPICLabel(const MachineInstr *MI, unsigned OpNo) { 212 O << "\"L" << getFunctionNumber() << "$pb\"\n"; 213 O << "\"L" << getFunctionNumber() << "$pb\":"; 214 } 215 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) { 216 if (MI->getOperand(OpNo).isImmediate()) { 217 printS16ImmOperand(MI, OpNo); 218 } else { 219 if (Subtarget.isDarwin()) O << "ha16("; 220 printOp(MI->getOperand(OpNo)); 221 if (TM.getRelocationModel() == Reloc::PIC_) 222 O << "-\"L" << getFunctionNumber() << "$pb\""; 223 if (Subtarget.isDarwin()) 224 O << ')'; 225 else 226 O << "@ha"; 227 } 228 } 229 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) { 230 if (MI->getOperand(OpNo).isImmediate()) { 231 printS16ImmOperand(MI, OpNo); 232 } else { 233 if (Subtarget.isDarwin()) O << "lo16("; 234 printOp(MI->getOperand(OpNo)); 235 if (TM.getRelocationModel() == Reloc::PIC_) 236 O << "-\"L" << getFunctionNumber() << "$pb\""; 237 if (Subtarget.isDarwin()) 238 O << ')'; 239 else 240 O << "@l"; 241 } 242 } 243 void printcrbitm(const MachineInstr *MI, unsigned OpNo) { 244 unsigned CCReg = MI->getOperand(OpNo).getReg(); 245 unsigned RegNo = enumRegToMachineReg(CCReg); 246 O << (0x80 >> RegNo); 247 } 248 // The new addressing mode printers. 249 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) { 250 printSymbolLo(MI, OpNo); 251 O << '('; 252 if (MI->getOperand(OpNo+1).isRegister() && 253 MI->getOperand(OpNo+1).getReg() == PPC::R0) 254 O << "0"; 255 else 256 printOperand(MI, OpNo+1); 257 O << ')'; 258 } 259 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) { 260 if (MI->getOperand(OpNo).isImmediate()) 261 printS16X4ImmOperand(MI, OpNo); 262 else 263 printSymbolLo(MI, OpNo); 264 O << '('; 265 if (MI->getOperand(OpNo+1).isRegister() && 266 MI->getOperand(OpNo+1).getReg() == PPC::R0) 267 O << "0"; 268 else 269 printOperand(MI, OpNo+1); 270 O << ')'; 271 } 272 273 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) { 274 // When used as the base register, r0 reads constant zero rather than 275 // the value contained in the register. For this reason, the darwin 276 // assembler requires that we print r0 as 0 (no r) when used as the base. 277 const MachineOperand &MO = MI->getOperand(OpNo); 278 printRegister(MO, true); 279 O << ", "; 280 printOperand(MI, OpNo+1); 281 } 282 283 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 284 const char *Modifier); 285 286 virtual bool runOnMachineFunction(MachineFunction &F) = 0; 287 virtual bool doFinalization(Module &M) = 0; 288 289 virtual void EmitExternalGlobal(const GlobalVariable *GV); 290 }; 291 292 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux 293 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter { 294 295 DwarfWriter DW; 296 297 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM, 298 const TargetAsmInfo *T) 299 : PPCAsmPrinter(O, TM, T), DW(O, this, T) { 300 } 301 302 virtual const char *getPassName() const { 303 return "Linux PPC Assembly Printer"; 304 } 305 306 bool runOnMachineFunction(MachineFunction &F); 307 bool doInitialization(Module &M); 308 bool doFinalization(Module &M); 309 310 void getAnalysisUsage(AnalysisUsage &AU) const { 311 AU.setPreservesAll(); 312 AU.addRequired<MachineModuleInfo>(); 313 PPCAsmPrinter::getAnalysisUsage(AU); 314 } 315 316 /// getSectionForFunction - Return the section that we should emit the 317 /// specified function body into. 318 virtual std::string getSectionForFunction(const Function &F) const; 319 }; 320 321 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS 322 /// X 323 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter { 324 325 DwarfWriter DW; 326 MachineModuleInfo *MMI; 327 328 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM, 329 const TargetAsmInfo *T) 330 : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) { 331 } 332 333 virtual const char *getPassName() const { 334 return "Darwin PPC Assembly Printer"; 335 } 336 337 bool runOnMachineFunction(MachineFunction &F); 338 bool doInitialization(Module &M); 339 bool doFinalization(Module &M); 340 341 void getAnalysisUsage(AnalysisUsage &AU) const { 342 AU.setPreservesAll(); 343 AU.addRequired<MachineModuleInfo>(); 344 PPCAsmPrinter::getAnalysisUsage(AU); 345 } 346 347 /// getSectionForFunction - Return the section that we should emit the 348 /// specified function body into. 349 virtual std::string getSectionForFunction(const Function &F) const; 350 }; 351} // end of anonymous namespace 352 353// Include the auto-generated portion of the assembly writer 354#include "PPCGenAsmWriter.inc" 355 356void PPCAsmPrinter::printOp(const MachineOperand &MO) { 357 switch (MO.getType()) { 358 case MachineOperand::MO_Immediate: 359 cerr << "printOp() does not handle immediate values\n"; 360 abort(); 361 return; 362 363 case MachineOperand::MO_MachineBasicBlock: 364 printBasicBlockLabel(MO.getMBB()); 365 return; 366 case MachineOperand::MO_JumpTableIndex: 367 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 368 << '_' << MO.getIndex(); 369 // FIXME: PIC relocation model 370 return; 371 case MachineOperand::MO_ConstantPoolIndex: 372 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() 373 << '_' << MO.getIndex(); 374 return; 375 case MachineOperand::MO_ExternalSymbol: 376 // Computing the address of an external symbol, not calling it. 377 if (TM.getRelocationModel() != Reloc::Static) { 378 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName(); 379 GVStubs.insert(Name); 380 printSuffixedName(Name, "$non_lazy_ptr"); 381 return; 382 } 383 O << TAI->getGlobalPrefix() << MO.getSymbolName(); 384 return; 385 case MachineOperand::MO_GlobalAddress: { 386 // Computing the address of a global symbol, not calling it. 387 GlobalValue *GV = MO.getGlobal(); 388 std::string Name = Mang->getValueName(GV); 389 390 // External or weakly linked global variables need non-lazily-resolved stubs 391 if (TM.getRelocationModel() != Reloc::Static) { 392 if (((GV->isDeclaration() || GV->hasWeakLinkage() || 393 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) { 394 GVStubs.insert(Name); 395 printSuffixedName(Name, "$non_lazy_ptr"); 396 if (GV->hasExternalWeakLinkage()) 397 ExtWeakSymbols.insert(GV); 398 return; 399 } 400 } 401 O << Name; 402 403 if (MO.getOffset() > 0) 404 O << "+" << MO.getOffset(); 405 else if (MO.getOffset() < 0) 406 O << MO.getOffset(); 407 408 if (GV->hasExternalWeakLinkage()) 409 ExtWeakSymbols.insert(GV); 410 return; 411 } 412 413 default: 414 O << "<unknown operand type: " << MO.getType() << ">"; 415 return; 416 } 417} 418 419/// EmitExternalGlobal - In this case we need to use the indirect symbol. 420/// 421void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) { 422 std::string Name = getGlobalLinkName(GV); 423 if (TM.getRelocationModel() != Reloc::Static) { 424 GVStubs.insert(Name); 425 printSuffixedName(Name, "$non_lazy_ptr"); 426 return; 427 } 428 O << Name; 429} 430 431/// PrintAsmOperand - Print out an operand for an inline asm expression. 432/// 433bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 434 unsigned AsmVariant, 435 const char *ExtraCode) { 436 // Does this asm operand have a single letter operand modifier? 437 if (ExtraCode && ExtraCode[0]) { 438 if (ExtraCode[1] != 0) return true; // Unknown modifier. 439 440 switch (ExtraCode[0]) { 441 default: return true; // Unknown modifier. 442 case 'c': // Don't print "$" before a global var name or constant. 443 // PPC never has a prefix. 444 printOperand(MI, OpNo); 445 return false; 446 case 'L': // Write second word of DImode reference. 447 // Verify that this operand has two consecutive registers. 448 if (!MI->getOperand(OpNo).isRegister() || 449 OpNo+1 == MI->getNumOperands() || 450 !MI->getOperand(OpNo+1).isRegister()) 451 return true; 452 ++OpNo; // Return the high-part. 453 break; 454 case 'I': 455 // Write 'i' if an integer constant, otherwise nothing. Used to print 456 // addi vs add, etc. 457 if (MI->getOperand(OpNo).isImmediate()) 458 O << "i"; 459 return false; 460 } 461 } 462 463 printOperand(MI, OpNo); 464 return false; 465} 466 467bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 468 unsigned AsmVariant, 469 const char *ExtraCode) { 470 if (ExtraCode && ExtraCode[0]) 471 return true; // Unknown modifier. 472 if (MI->getOperand(OpNo).isRegister()) 473 printMemRegReg(MI, OpNo); 474 else 475 printMemRegImm(MI, OpNo); 476 return false; 477} 478 479void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 480 const char *Modifier) { 481 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!"); 482 unsigned Code = MI->getOperand(OpNo).getImm(); 483 if (!strcmp(Modifier, "cc")) { 484 switch ((PPC::Predicate)Code) { 485 case PPC::PRED_ALWAYS: return; // Don't print anything for always. 486 case PPC::PRED_LT: O << "lt"; return; 487 case PPC::PRED_LE: O << "le"; return; 488 case PPC::PRED_EQ: O << "eq"; return; 489 case PPC::PRED_GE: O << "ge"; return; 490 case PPC::PRED_GT: O << "gt"; return; 491 case PPC::PRED_NE: O << "ne"; return; 492 case PPC::PRED_UN: O << "un"; return; 493 case PPC::PRED_NU: O << "nu"; return; 494 } 495 496 } else { 497 assert(!strcmp(Modifier, "reg") && 498 "Need to specify 'cc' or 'reg' as predicate op modifier!"); 499 // Don't print the register for 'always'. 500 if (Code == PPC::PRED_ALWAYS) return; 501 printOperand(MI, OpNo+1); 502 } 503} 504 505 506/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to 507/// the current output stream. 508/// 509void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) { 510 ++EmittedInsts; 511 512 // Check for slwi/srwi mnemonics. 513 if (MI->getOpcode() == PPC::RLWINM) { 514 bool FoundMnemonic = false; 515 unsigned char SH = MI->getOperand(2).getImm(); 516 unsigned char MB = MI->getOperand(3).getImm(); 517 unsigned char ME = MI->getOperand(4).getImm(); 518 if (SH <= 31 && MB == 0 && ME == (31-SH)) { 519 O << "\tslwi "; FoundMnemonic = true; 520 } 521 if (SH <= 31 && MB == (32-SH) && ME == 31) { 522 O << "\tsrwi "; FoundMnemonic = true; 523 SH = 32-SH; 524 } 525 if (FoundMnemonic) { 526 printOperand(MI, 0); 527 O << ", "; 528 printOperand(MI, 1); 529 O << ", " << (unsigned int)SH << "\n"; 530 return; 531 } 532 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) { 533 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) { 534 O << "\tmr "; 535 printOperand(MI, 0); 536 O << ", "; 537 printOperand(MI, 1); 538 O << "\n"; 539 return; 540 } 541 } else if (MI->getOpcode() == PPC::RLDICR) { 542 unsigned char SH = MI->getOperand(2).getImm(); 543 unsigned char ME = MI->getOperand(3).getImm(); 544 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH 545 if (63-SH == ME) { 546 O << "\tsldi "; 547 printOperand(MI, 0); 548 O << ", "; 549 printOperand(MI, 1); 550 O << ", " << (unsigned int)SH << "\n"; 551 return; 552 } 553 } 554 555 if (printInstruction(MI)) 556 return; // Printer was automatically generated 557 558 assert(0 && "Unhandled instruction in asm writer!"); 559 abort(); 560 return; 561} 562 563/// runOnMachineFunction - This uses the printMachineInstruction() 564/// method to print assembly for each instruction. 565/// 566bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 567 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>()); 568 569 SetupMachineFunction(MF); 570 O << "\n\n"; 571 572 // Print out constants referenced by the function 573 EmitConstantPool(MF.getConstantPool()); 574 575 // Print out labels for the function. 576 const Function *F = MF.getFunction(); 577 SwitchToTextSection(getSectionForFunction(*F).c_str(), F); 578 579 switch (F->getLinkage()) { 580 default: assert(0 && "Unknown linkage type!"); 581 case Function::InternalLinkage: // Symbols default to internal. 582 break; 583 case Function::ExternalLinkage: 584 O << "\t.global\t" << CurrentFnName << '\n' 585 << "\t.type\t" << CurrentFnName << ", @function\n"; 586 break; 587 case Function::WeakLinkage: 588 case Function::LinkOnceLinkage: 589 O << "\t.global\t" << CurrentFnName << '\n'; 590 O << "\t.weak\t" << CurrentFnName << '\n'; 591 break; 592 } 593 594 if (F->hasHiddenVisibility()) 595 if (const char *Directive = TAI->getHiddenDirective()) 596 O << Directive << CurrentFnName << "\n"; 597 598 EmitAlignment(2, F); 599 O << CurrentFnName << ":\n"; 600 601 // Emit pre-function debug information. 602 DW.BeginFunction(&MF); 603 604 // Print out code for the function. 605 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); 606 I != E; ++I) { 607 // Print a label for the basic block. 608 if (I != MF.begin()) { 609 printBasicBlockLabel(I, true, true); 610 O << '\n'; 611 } 612 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end(); 613 II != E; ++II) { 614 // Print the assembly for the instruction. 615 printMachineInstruction(II); 616 } 617 } 618 619 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n"; 620 621 // Print out jump tables referenced by the function. 622 EmitJumpTableInfo(MF.getJumpTableInfo(), MF); 623 624 // Emit post-function debug information. 625 DW.EndFunction(); 626 627 // We didn't modify anything. 628 return false; 629} 630 631bool LinuxAsmPrinter::doInitialization(Module &M) { 632 bool Result = AsmPrinter::doInitialization(M); 633 634 // GNU as handles section names wrapped in quotes 635 Mang->setUseQuotes(true); 636 637 SwitchToTextSection(TAI->getTextSection()); 638 639 // Emit initial debug information. 640 DW.BeginModule(&M); 641 return Result; 642} 643 644/// PrintUnmangledNameSafely - Print out the printable characters in the name. 645/// Don't print things like \n or \0. 646static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) { 647 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen(); 648 Name != E; ++Name) 649 if (isprint(*Name)) 650 OS << *Name; 651} 652 653bool LinuxAsmPrinter::doFinalization(Module &M) { 654 const TargetData *TD = TM.getTargetData(); 655 656 // Print out module-level global variables here. 657 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 658 I != E; ++I) { 659 if (!I->hasInitializer()) continue; // External global require no code 660 661 // Check to see if this is a special global used by LLVM, if so, emit it. 662 if (EmitSpecialLLVMGlobal(I)) 663 continue; 664 665 std::string name = Mang->getValueName(I); 666 667 if (I->hasHiddenVisibility()) 668 if (const char *Directive = TAI->getHiddenDirective()) 669 O << Directive << name << "\n"; 670 671 Constant *C = I->getInitializer(); 672 unsigned Size = TD->getABITypeSize(C->getType()); 673 unsigned Align = TD->getPreferredAlignmentLog(I); 674 675 if (C->isNullValue() && /* FIXME: Verify correct */ 676 !I->hasSection() && (I->hasCommonLinkage() || 677 I->hasInternalLinkage() || I->hasWeakLinkage() || 678 I->hasLinkOnceLinkage() || I->hasExternalLinkage())) { 679 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 680 if (I->hasExternalLinkage()) { 681 O << "\t.global " << name << '\n'; 682 O << "\t.type " << name << ", @object\n"; 683 if (TAI->getBSSSection()) 684 SwitchToDataSection(TAI->getBSSSection(), I); 685 O << name << ":\n"; 686 O << "\t.zero " << Size << "\n"; 687 } else if (I->hasInternalLinkage()) { 688 SwitchToDataSection("\t.data", I); 689 O << TAI->getLCOMMDirective() << name << "," << Size; 690 } else { 691 SwitchToDataSection("\t.data", I); 692 O << ".comm " << name << "," << Size; 693 } 694 O << "\t\t" << TAI->getCommentString() << " '"; 695 PrintUnmangledNameSafely(I, O); 696 O << "'\n"; 697 } else { 698 switch (I->getLinkage()) { 699 case GlobalValue::LinkOnceLinkage: 700 case GlobalValue::WeakLinkage: 701 case GlobalValue::CommonLinkage: 702 O << "\t.global " << name << '\n' 703 << "\t.type " << name << ", @object\n" 704 << "\t.weak " << name << '\n'; 705 SwitchToDataSection("\t.data", I); 706 break; 707 case GlobalValue::AppendingLinkage: 708 // FIXME: appending linkage variables should go into a section of 709 // their name or something. For now, just emit them as external. 710 case GlobalValue::ExternalLinkage: 711 // If external or appending, declare as a global symbol 712 O << "\t.global " << name << "\n" 713 << "\t.type " << name << ", @object\n"; 714 // FALL THROUGH 715 case GlobalValue::InternalLinkage: 716 if (I->isConstant()) { 717 const ConstantArray *CVA = dyn_cast<ConstantArray>(C); 718 if (TAI->getCStringSection() && CVA && CVA->isCString()) { 719 SwitchToDataSection(TAI->getCStringSection(), I); 720 break; 721 } 722 } 723 724 // FIXME: special handling for ".ctors" & ".dtors" sections 725 if (I->hasSection() && 726 (I->getSection() == ".ctors" || 727 I->getSection() == ".dtors")) { 728 std::string SectionName = ".section " + I->getSection() 729 + ",\"aw\",@progbits"; 730 SwitchToDataSection(SectionName.c_str()); 731 } else { 732 if (I->isConstant() && TAI->getReadOnlySection()) 733 SwitchToDataSection(TAI->getReadOnlySection(), I); 734 else 735 SwitchToDataSection(TAI->getDataSection(), I); 736 } 737 break; 738 default: 739 cerr << "Unknown linkage type!"; 740 abort(); 741 } 742 743 EmitAlignment(Align, I); 744 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"; 745 PrintUnmangledNameSafely(I, O); 746 O << "'\n"; 747 748 // If the initializer is a extern weak symbol, remember to emit the weak 749 // reference! 750 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 751 if (GV->hasExternalWeakLinkage()) 752 ExtWeakSymbols.insert(GV); 753 754 EmitGlobalConstant(C); 755 O << '\n'; 756 } 757 } 758 759 // TODO 760 761 // Emit initial debug information. 762 DW.EndModule(); 763 764 return AsmPrinter::doFinalization(M); 765} 766 767std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const { 768 switch (F.getLinkage()) { 769 default: assert(0 && "Unknown linkage type!"); 770 case Function::ExternalLinkage: 771 case Function::InternalLinkage: return TAI->getTextSection(); 772 case Function::WeakLinkage: 773 case Function::LinkOnceLinkage: 774 return ".text"; 775 } 776} 777 778std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const { 779 switch (F.getLinkage()) { 780 default: assert(0 && "Unknown linkage type!"); 781 case Function::ExternalLinkage: 782 case Function::InternalLinkage: return TAI->getTextSection(); 783 case Function::WeakLinkage: 784 case Function::LinkOnceLinkage: 785 return "\t.section __TEXT,__textcoal_nt,coalesced,pure_instructions"; 786 } 787} 788 789/// runOnMachineFunction - This uses the printMachineInstruction() 790/// method to print assembly for each instruction. 791/// 792bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 793 794 SetupMachineFunction(MF); 795 O << "\n\n"; 796 797 // Print out constants referenced by the function 798 EmitConstantPool(MF.getConstantPool()); 799 800 // Print out labels for the function. 801 const Function *F = MF.getFunction(); 802 SwitchToTextSection(getSectionForFunction(*F).c_str(), F); 803 804 switch (F->getLinkage()) { 805 default: assert(0 && "Unknown linkage type!"); 806 case Function::InternalLinkage: // Symbols default to internal. 807 break; 808 case Function::ExternalLinkage: 809 O << "\t.globl\t" << CurrentFnName << "\n"; 810 break; 811 case Function::WeakLinkage: 812 case Function::LinkOnceLinkage: 813 O << "\t.globl\t" << CurrentFnName << "\n"; 814 O << "\t.weak_definition\t" << CurrentFnName << "\n"; 815 break; 816 } 817 818 if (F->hasHiddenVisibility()) 819 if (const char *Directive = TAI->getHiddenDirective()) 820 O << Directive << CurrentFnName << "\n"; 821 822 EmitAlignment(OptimizeForSize ? 2 : 4, F); 823 O << CurrentFnName << ":\n"; 824 825 // Emit pre-function debug information. 826 DW.BeginFunction(&MF); 827 828 // If the function is empty, then we need to emit *something*. Otherwise, the 829 // function's label might be associated with something that it wasn't meant to 830 // be associated with. We emit a noop in this situation. 831 MachineFunction::iterator I = MF.begin(); 832 833 if (++I == MF.end() && MF.front().empty()) 834 O << "\tnop\n"; 835 836 // Print out code for the function. 837 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); 838 I != E; ++I) { 839 // Print a label for the basic block. 840 if (I != MF.begin()) { 841 printBasicBlockLabel(I, true, true); 842 O << '\n'; 843 } 844 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 845 II != IE; ++II) { 846 // Print the assembly for the instruction. 847 printMachineInstruction(II); 848 } 849 } 850 851 // Print out jump tables referenced by the function. 852 EmitJumpTableInfo(MF.getJumpTableInfo(), MF); 853 854 // Emit post-function debug information. 855 DW.EndFunction(); 856 857 // We didn't modify anything. 858 return false; 859} 860 861 862bool DarwinAsmPrinter::doInitialization(Module &M) { 863 static const char *const CPUDirectives[] = { 864 "", 865 "ppc", 866 "ppc601", 867 "ppc602", 868 "ppc603", 869 "ppc7400", 870 "ppc750", 871 "ppc970", 872 "ppc64" 873 }; 874 875 unsigned Directive = Subtarget.getDarwinDirective(); 876 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970) 877 Directive = PPC::DIR_970; 878 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400) 879 Directive = PPC::DIR_7400; 880 if (Subtarget.isPPC64() && Directive < PPC::DIR_970) 881 Directive = PPC::DIR_64; 882 assert(Directive <= PPC::DIR_64 && "Directive out of range."); 883 O << "\t.machine " << CPUDirectives[Directive] << "\n"; 884 885 bool Result = AsmPrinter::doInitialization(M); 886 887 // We need this for Personality functions. 888 // AsmPrinter::doInitialization should have done this analysis. 889 MMI = getAnalysisToUpdate<MachineModuleInfo>(); 890 assert(MMI); 891 DW.SetModuleInfo(MMI); 892 893 // Darwin wants symbols to be quoted if they have complex names. 894 Mang->setUseQuotes(true); 895 896 // Prime text sections so they are adjacent. This reduces the likelihood a 897 // large data or debug section causes a branch to exceed 16M limit. 898 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced," 899 "pure_instructions"); 900 if (TM.getRelocationModel() == Reloc::PIC_) { 901 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs," 902 "pure_instructions,32"); 903 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) { 904 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs," 905 "pure_instructions,16"); 906 } 907 SwitchToTextSection(TAI->getTextSection()); 908 909 // Emit initial debug information. 910 DW.BeginModule(&M); 911 return Result; 912} 913 914bool DarwinAsmPrinter::doFinalization(Module &M) { 915 const TargetData *TD = TM.getTargetData(); 916 917 // Print out module-level global variables here. 918 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 919 I != E; ++I) { 920 if (!I->hasInitializer()) continue; // External global require no code 921 922 // Check to see if this is a special global used by LLVM, if so, emit it. 923 if (EmitSpecialLLVMGlobal(I)) { 924 if (TM.getRelocationModel() == Reloc::Static) { 925 if (I->getName() == "llvm.global_ctors") 926 O << ".reference .constructors_used\n"; 927 else if (I->getName() == "llvm.global_dtors") 928 O << ".reference .destructors_used\n"; 929 } 930 continue; 931 } 932 933 std::string name = Mang->getValueName(I); 934 935 if (I->hasHiddenVisibility()) 936 if (const char *Directive = TAI->getHiddenDirective()) 937 O << Directive << name << "\n"; 938 939 Constant *C = I->getInitializer(); 940 const Type *Type = C->getType(); 941 unsigned Size = TD->getABITypeSize(Type); 942 unsigned Align = TD->getPreferredAlignmentLog(I); 943 944 if (C->isNullValue() && /* FIXME: Verify correct */ 945 !I->hasSection() && (I->hasCommonLinkage() || 946 I->hasInternalLinkage() || I->hasWeakLinkage() || 947 I->hasLinkOnceLinkage() || I->hasExternalLinkage())) { 948 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 949 if (I->hasExternalLinkage()) { 950 O << "\t.globl " << name << '\n'; 951 O << "\t.zerofill __DATA, __common, " << name << ", " 952 << Size << ", " << Align; 953 } else if (I->hasInternalLinkage()) { 954 SwitchToDataSection("\t.data", I); 955 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align; 956 } else if (!I->hasCommonLinkage()) { 957 O << "\t.globl " << name << "\n" 958 << TAI->getWeakDefDirective() << name << "\n"; 959 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I); 960 EmitAlignment(Align, I); 961 O << name << ":\t\t\t\t" << TAI->getCommentString() << " "; 962 PrintUnmangledNameSafely(I, O); 963 O << "\n"; 964 EmitGlobalConstant(C); 965 continue; 966 } else { 967 SwitchToDataSection("\t.data", I); 968 O << ".comm " << name << "," << Size; 969 // Darwin 9 and above support aligned common data. 970 if (Subtarget.isDarwin9()) 971 O << "," << Align; 972 } 973 O << "\t\t" << TAI->getCommentString() << " '"; 974 PrintUnmangledNameSafely(I, O); 975 O << "'\n"; 976 } else { 977 switch (I->getLinkage()) { 978 case GlobalValue::LinkOnceLinkage: 979 case GlobalValue::WeakLinkage: 980 case GlobalValue::CommonLinkage: 981 O << "\t.globl " << name << '\n' 982 << "\t.weak_definition " << name << '\n'; 983 if (!I->isConstant()) 984 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I); 985 else { 986 const ArrayType *AT = dyn_cast<ArrayType>(Type); 987 if (AT && AT->getElementType()==Type::Int8Ty) 988 SwitchToDataSection("\t.section __TEXT,__const_coal,coalesced", I); 989 else 990 SwitchToDataSection("\t.section __DATA,__const_coal,coalesced", I); 991 } 992 break; 993 case GlobalValue::AppendingLinkage: 994 // FIXME: appending linkage variables should go into a section of 995 // their name or something. For now, just emit them as external. 996 case GlobalValue::ExternalLinkage: 997 // If external or appending, declare as a global symbol 998 O << "\t.globl " << name << "\n"; 999 // FALL THROUGH 1000 case GlobalValue::InternalLinkage: 1001 if (I->isConstant()) { 1002 const ConstantArray *CVA = dyn_cast<ConstantArray>(C); 1003 if (TAI->getCStringSection() && CVA && CVA->isCString()) { 1004 SwitchToDataSection(TAI->getCStringSection(), I); 1005 break; 1006 } 1007 } 1008 if (I->hasSection()) { 1009 // Honor all section names on Darwin; ObjC uses this 1010 std::string SectionName = ".section " + I->getSection(); 1011 SwitchToDataSection(SectionName.c_str()); 1012 } else if (!I->isConstant()) 1013 SwitchToDataSection(TAI->getDataSection(), I); 1014 else { 1015 // Read-only data. 1016 bool HasReloc = C->ContainsRelocations(); 1017 if (HasReloc && 1018 TM.getRelocationModel() != Reloc::Static) 1019 SwitchToDataSection("\t.const_data\n"); 1020 else if (!HasReloc && Size == 4 && 1021 TAI->getFourByteConstantSection()) 1022 SwitchToDataSection(TAI->getFourByteConstantSection(), I); 1023 else if (!HasReloc && Size == 8 && 1024 TAI->getEightByteConstantSection()) 1025 SwitchToDataSection(TAI->getEightByteConstantSection(), I); 1026 else if (!HasReloc && Size == 16 && 1027 TAI->getSixteenByteConstantSection()) 1028 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I); 1029 else if (TAI->getReadOnlySection()) 1030 SwitchToDataSection(TAI->getReadOnlySection(), I); 1031 else 1032 SwitchToDataSection(TAI->getDataSection(), I); 1033 } 1034 break; 1035 default: 1036 cerr << "Unknown linkage type!"; 1037 abort(); 1038 } 1039 1040 EmitAlignment(Align, I); 1041 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"; 1042 PrintUnmangledNameSafely(I, O); 1043 O << "'\n"; 1044 1045 // If the initializer is a extern weak symbol, remember to emit the weak 1046 // reference! 1047 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1048 if (GV->hasExternalWeakLinkage()) 1049 ExtWeakSymbols.insert(GV); 1050 1051 EmitGlobalConstant(C); 1052 O << '\n'; 1053 } 1054 } 1055 1056 bool isPPC64 = TD->getPointerSizeInBits() == 64; 1057 1058 // Output stubs for dynamically-linked functions 1059 if (TM.getRelocationModel() == Reloc::PIC_) { 1060 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 1061 i != e; ++i) { 1062 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs," 1063 "pure_instructions,32"); 1064 EmitAlignment(4); 1065 std::string p = *i; 1066 std::string L0p = (p[0]=='\"') ? "\"L0$" + p.substr(1) : "L0$" + p ; 1067 printSuffixedName(p, "$stub"); 1068 O << ":\n"; 1069 O << "\t.indirect_symbol " << *i << "\n"; 1070 O << "\tmflr r0\n"; 1071 O << "\tbcl 20,31," << L0p << "\n"; 1072 O << L0p << ":\n"; 1073 O << "\tmflr r11\n"; 1074 O << "\taddis r11,r11,ha16("; 1075 printSuffixedName(p, "$lazy_ptr"); 1076 O << "-" << L0p << ")\n"; 1077 O << "\tmtlr r0\n"; 1078 if (isPPC64) 1079 O << "\tldu r12,lo16("; 1080 else 1081 O << "\tlwzu r12,lo16("; 1082 printSuffixedName(p, "$lazy_ptr"); 1083 O << "-" << L0p << ")(r11)\n"; 1084 O << "\tmtctr r12\n"; 1085 O << "\tbctr\n"; 1086 SwitchToDataSection(".lazy_symbol_pointer"); 1087 printSuffixedName(p, "$lazy_ptr"); 1088 O << ":\n"; 1089 O << "\t.indirect_symbol " << *i << "\n"; 1090 if (isPPC64) 1091 O << "\t.quad dyld_stub_binding_helper\n"; 1092 else 1093 O << "\t.long dyld_stub_binding_helper\n"; 1094 } 1095 } else { 1096 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 1097 i != e; ++i) { 1098 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs," 1099 "pure_instructions,16"); 1100 EmitAlignment(4); 1101 std::string p = *i; 1102 printSuffixedName(p, "$stub"); 1103 O << ":\n"; 1104 O << "\t.indirect_symbol " << *i << "\n"; 1105 O << "\tlis r11,ha16("; 1106 printSuffixedName(p, "$lazy_ptr"); 1107 O << ")\n"; 1108 if (isPPC64) 1109 O << "\tldu r12,lo16("; 1110 else 1111 O << "\tlwzu r12,lo16("; 1112 printSuffixedName(p, "$lazy_ptr"); 1113 O << ")(r11)\n"; 1114 O << "\tmtctr r12\n"; 1115 O << "\tbctr\n"; 1116 SwitchToDataSection(".lazy_symbol_pointer"); 1117 printSuffixedName(p, "$lazy_ptr"); 1118 O << ":\n"; 1119 O << "\t.indirect_symbol " << *i << "\n"; 1120 if (isPPC64) 1121 O << "\t.quad dyld_stub_binding_helper\n"; 1122 else 1123 O << "\t.long dyld_stub_binding_helper\n"; 1124 } 1125 } 1126 1127 O << "\n"; 1128 1129 if (TAI->doesSupportExceptionHandling() && MMI) { 1130 // Add the (possibly multiple) personalities to the set of global values. 1131 // Only referenced functions get into the Personalities list. 1132 const std::vector<Function *>& Personalities = MMI->getPersonalities(); 1133 1134 for (std::vector<Function *>::const_iterator I = Personalities.begin(), 1135 E = Personalities.end(); I != E; ++I) 1136 if (*I) GVStubs.insert("_" + (*I)->getName()); 1137 } 1138 1139 // Output stubs for external and common global variables. 1140 if (!GVStubs.empty()) { 1141 SwitchToDataSection(".non_lazy_symbol_pointer"); 1142 for (std::set<std::string>::iterator I = GVStubs.begin(), 1143 E = GVStubs.end(); I != E; ++I) { 1144 std::string p = *I; 1145 printSuffixedName(p, "$non_lazy_ptr"); 1146 O << ":\n"; 1147 O << "\t.indirect_symbol " << *I << "\n"; 1148 if (isPPC64) 1149 O << "\t.quad\t0\n"; 1150 else 1151 O << "\t.long\t0\n"; 1152 1153 } 1154 } 1155 1156 // Emit initial debug information. 1157 DW.EndModule(); 1158 1159 // Funny Darwin hack: This flag tells the linker that no global symbols 1160 // contain code that falls through to other global symbols (e.g. the obvious 1161 // implementation of multiple entry points). If this doesn't occur, the 1162 // linker can safely perform dead code stripping. Since LLVM never generates 1163 // code that does this, it is always safe to set. 1164 O << "\t.subsections_via_symbols\n"; 1165 1166 return AsmPrinter::doFinalization(M); 1167} 1168 1169 1170 1171/// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code 1172/// for a MachineFunction to the given output stream, in a format that the 1173/// Darwin assembler can deal with. 1174/// 1175FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o, 1176 PPCTargetMachine &tm) { 1177 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>(); 1178 1179 if (Subtarget->isDarwin()) { 1180 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo()); 1181 } else { 1182 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo()); 1183 } 1184} 1185 1186