1 //===-- PPC32AsmPrinter.cpp - Print machine instrs to PowerPC assembly ----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPC32TargetMachine.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "Support/CommandLine.h"
33 #include "Support/Debug.h"
34 #include "Support/Statistic.h"
35 #include "Support/StringExtras.h"
40 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
42 struct PPC32AsmPrinter : public AsmPrinter {
43 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
44 std::set<std::string> Strings;
46 PPC32AsmPrinter(std::ostream &O, TargetMachine &TM)
47 : AsmPrinter(O, TM), LabelNumber(0) {
51 /// Unique incrementer for label values for referencing Global values.
55 virtual const char *getPassName() const {
56 return "PPC32 Assembly Printer";
59 PPC32TargetMachine &getTM() {
60 return static_cast<PPC32TargetMachine&>(TM);
63 /// printInstruction - This method is automatically generated by tablegen
64 /// from the instruction set description. This method returns true if the
65 /// machine instruction was sufficiently described to print it, otherwise it
67 bool printInstruction(const MachineInstr *MI);
69 void printMachineInstruction(const MachineInstr *MI);
70 void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
71 void printImmOp(const MachineOperand &MO, unsigned ArgType);
73 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
74 const MachineOperand &MO = MI->getOperand(OpNo);
75 if (MO.getType() == MachineOperand::MO_MachineRegister) {
76 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
77 O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
78 } else if (MO.isImmediate()) {
79 O << MO.getImmedValue();
85 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
87 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
90 void printConstantPool(MachineConstantPool *MCP);
91 bool runOnMachineFunction(MachineFunction &F);
92 bool doFinalization(Module &M);
93 void emitGlobalConstant(const Constant* CV);
95 } // end of anonymous namespace
97 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
98 /// assembly code for a MachineFunction to the given output stream,
99 /// using the given target machine description. This should work
100 /// regardless of whether the function is in SSA form or not.
102 FunctionPass *llvm::createPPC32AsmPrinter(std::ostream &o, TargetMachine &tm) {
103 return new PPC32AsmPrinter(o, tm);
106 // Include the auto-generated portion of the assembly writer
107 #include "PowerPCGenAsmWriter.inc"
109 /// toOctal - Convert the low order bits of X into an octal digit.
111 static inline char toOctal(int X) {
115 /// getAsCString - Return the specified array as a C compatible
116 /// string, only if the predicate isString is true.
118 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
119 assert(CVA->isString() && "Array is not string compatible!");
122 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
123 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
127 } else if (C == '\\') {
129 } else if (isprint(C)) {
133 case '\b': O << "\\b"; break;
134 case '\f': O << "\\f"; break;
135 case '\n': O << "\\n"; break;
136 case '\r': O << "\\r"; break;
137 case '\t': O << "\\t"; break;
140 O << toOctal(C >> 6);
141 O << toOctal(C >> 3);
142 O << toOctal(C >> 0);
150 // Print a constant value or values, with the appropriate storage class as a
152 void PPC32AsmPrinter::emitGlobalConstant(const Constant *CV) {
153 const TargetData &TD = TM.getTargetData();
155 if (CV->isNullValue()) {
156 O << "\t.space\t" << TD.getTypeSize(CV->getType()) << "\n";
158 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
159 if (CVA->isString()) {
161 printAsCString(O, CVA);
163 } else { // Not a string. Print the values in successive locations
164 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
165 emitGlobalConstant(CVA->getOperand(i));
168 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
169 // Print the fields in successive locations. Pad to align if needed!
170 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
171 unsigned sizeSoFar = 0;
172 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
173 const Constant* field = CVS->getOperand(i);
175 // Check if padding is needed and insert one or more 0s.
176 unsigned fieldSize = TD.getTypeSize(field->getType());
177 unsigned padSize = ((i == e-1? cvsLayout->StructSize
178 : cvsLayout->MemberOffsets[i+1])
179 - cvsLayout->MemberOffsets[i]) - fieldSize;
180 sizeSoFar += fieldSize + padSize;
182 // Now print the actual field value
183 emitGlobalConstant(field);
185 // Insert the field padding unless it's zero bytes...
187 O << "\t.space\t " << padSize << "\n";
189 assert(sizeSoFar == cvsLayout->StructSize &&
190 "Layout of constant struct may be incorrect!");
192 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
193 // FP Constants are printed as integer constants to avoid losing
195 double Val = CFP->getValue();
196 if (CFP->getType() == Type::DoubleTy) {
197 union DU { // Abide by C TBAA rules
203 if (TD.isBigEndian()) {
204 O << ".long\t" << unsigned(U.UVal >> 32)
205 << "\t; double most significant word " << Val << "\n";
206 O << ".long\t" << unsigned(U.UVal)
207 << "\t; double least significant word " << Val << "\n";
209 O << ".long\t" << unsigned(U.UVal)
210 << "\t; double least significant word " << Val << "\n";
211 O << ".long\t" << unsigned(U.UVal >> 32)
212 << "\t; double most significant word " << Val << "\n";
216 union FU { // Abide by C TBAA rules
222 O << ".long\t" << U.UVal << "\t; float " << Val << "\n";
225 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
226 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
227 uint64_t Val = CI->getRawValue();
229 if (TD.isBigEndian()) {
230 O << ".long\t" << unsigned(Val >> 32)
231 << "\t; Double-word most significant word " << Val << "\n";
232 O << ".long\t" << unsigned(Val)
233 << "\t; Double-word least significant word " << Val << "\n";
235 O << ".long\t" << unsigned(Val)
236 << "\t; Double-word least significant word " << Val << "\n";
237 O << ".long\t" << unsigned(Val >> 32)
238 << "\t; Double-word most significant word " << Val << "\n";
244 const Type *type = CV->getType();
246 switch (type->getTypeID()) {
247 case Type::UByteTyID: case Type::SByteTyID:
250 case Type::UShortTyID: case Type::ShortTyID:
254 case Type::PointerTyID:
255 case Type::UIntTyID: case Type::IntTyID:
258 case Type::ULongTyID: case Type::LongTyID:
259 assert (0 && "Should have already output double-word constant.");
260 case Type::FloatTyID: case Type::DoubleTyID:
261 assert (0 && "Should have already output floating point constant.");
263 assert (0 && "Can't handle printing this type of thing");
267 emitConstantValueOnly(CV);
271 /// printConstantPool - Print to the current output stream assembly
272 /// representations of the constants in the constant pool MCP. This is
273 /// used to print out constants which have been "spilled to memory" by
274 /// the code generator.
276 void PPC32AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
277 const std::vector<Constant*> &CP = MCP->getConstants();
278 const TargetData &TD = TM.getTargetData();
280 if (CP.empty()) return;
282 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
284 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
286 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
288 emitGlobalConstant(CP[i]);
292 /// runOnMachineFunction - This uses the printMachineInstruction()
293 /// method to print assembly for each instruction.
295 bool PPC32AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
296 setupMachineFunction(MF);
299 // Print out constants referenced by the function
300 printConstantPool(MF.getConstantPool());
302 // Print out labels for the function.
304 O << "\t.globl\t" << CurrentFnName << "\n";
306 O << CurrentFnName << ":\n";
308 // Print out code for the function.
309 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
311 // Print a label for the basic block.
312 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
313 << I->getBasicBlock()->getName() << "\n";
314 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
316 // Print the assembly for the instruction.
318 printMachineInstruction(II);
323 // We didn't modify anything.
327 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
328 bool LoadAddrOp /* = false */) {
329 const MRegisterInfo &RI = *TM.getRegisterInfo();
332 switch (MO.getType()) {
333 case MachineOperand::MO_VirtualRegister:
334 if (Value *V = MO.getVRegValueOrNull()) {
335 O << "<" << V->getName() << ">";
339 case MachineOperand::MO_MachineRegister:
340 case MachineOperand::MO_CCRegister:
341 O << LowercaseString(RI.get(MO.getReg()).Name);
344 case MachineOperand::MO_SignExtendedImmed:
345 case MachineOperand::MO_UnextendedImmed:
346 std::cerr << "printOp() does not handle immediate values\n";
350 case MachineOperand::MO_PCRelativeDisp:
351 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
355 case MachineOperand::MO_MachineBasicBlock: {
356 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
357 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
358 << "_" << MBBOp->getNumber() << "\t; "
359 << MBBOp->getBasicBlock()->getName();
363 case MachineOperand::MO_ConstantPoolIndex:
364 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
367 case MachineOperand::MO_ExternalSymbol:
368 O << MO.getSymbolName();
371 case MachineOperand::MO_GlobalAddress: {
372 GlobalValue *GV = MO.getGlobal();
373 std::string Name = Mang->getValueName(GV);
375 // Dynamically-resolved functions need a stub for the function. Be
376 // wary however not to output $stub for external functions whose addresses
377 // are taken. Those should be emitted as $non_lazy_ptr below.
378 Function *F = dyn_cast<Function>(GV);
379 if (F && F->isExternal() && !LoadAddrOp &&
380 getTM().CalledFunctions.count(F)) {
381 FnStubs.insert(Name);
382 O << "L" << Name << "$stub";
386 // External global variables need a non-lazily-resolved stub
387 if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
388 GVStubs.insert(Name);
389 O << "L" << Name << "$non_lazy_ptr";
393 if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
394 LinkOnceStubs.insert(Name);
395 O << "L" << Name << "$non_lazy_ptr";
399 O << Mang->getValueName(GV);
404 O << "<unknown operand type: " << MO.getType() << ">";
409 void PPC32AsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
410 int Imm = MO.getImmedValue();
411 if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
418 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
419 /// the current output stream.
421 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
423 if (printInstruction(MI))
424 return; // Printer was automatically generated
426 unsigned Opcode = MI->getOpcode();
427 const TargetInstrInfo &TII = *TM.getInstrInfo();
428 const TargetInstrDescriptor &Desc = TII.get(Opcode);
431 unsigned ArgCount = MI->getNumOperands();
432 unsigned ArgType[] = {
433 (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
434 (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
435 (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
436 (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
437 (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
439 assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
440 "Instruction requires VMX support");
441 assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
442 "Instruction requires 64 bit support");
444 // CALLpcrel and CALLindirect are handled specially here to print only the
445 // appropriate number of args that the assembler expects. This is because
446 // may have many arguments appended to record the uses of registers that are
447 // holding arguments to the called function.
448 if (Opcode == PPC::COND_BRANCH) {
449 std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
451 } else if (Opcode == PPC::IMPLICIT_DEF) {
452 O << "; IMPLICIT DEF ";
453 printOp(MI->getOperand(0));
456 } else if (Opcode == PPC::CALLpcrel) {
457 O << TII.getName(Opcode) << " ";
458 printOp(MI->getOperand(0));
461 } else if (Opcode == PPC::CALLindirect) {
462 O << TII.getName(Opcode) << " ";
463 printImmOp(MI->getOperand(0), ArgType[0]);
465 printImmOp(MI->getOperand(1), ArgType[0]);
468 } else if (Opcode == PPC::MovePCtoLR) {
469 // FIXME: should probably be converted to cout.width and cout.fill
470 O << "bl \"L0000" << LabelNumber << "$pb\"\n";
471 O << "\"L0000" << LabelNumber << "$pb\":\n";
473 printOp(MI->getOperand(0));
478 O << TII.getName(Opcode) << " ";
479 if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
480 printOp(MI->getOperand(0));
482 printOp(MI->getOperand(2), true /* LoadAddrOp */);
483 O << "-\"L0000" << LabelNumber << "$pb\")";
485 if (MI->getOperand(1).getReg() == PPC::R0)
488 printOp(MI->getOperand(1));
490 } else if (Opcode == PPC::LOADHiAddr) {
491 printOp(MI->getOperand(0));
493 if (MI->getOperand(1).getReg() == PPC::R0)
496 printOp(MI->getOperand(1));
498 printOp(MI->getOperand(2), true /* LoadAddrOp */);
499 O << "-\"L0000" << LabelNumber << "$pb\")\n";
500 } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
501 printOp(MI->getOperand(0));
503 printImmOp(MI->getOperand(1), ArgType[1]);
505 if (MI->getOperand(2).hasAllocatedReg() &&
506 MI->getOperand(2).getReg() == PPC::R0)
509 printOp(MI->getOperand(2));
512 for (i = 0; i < ArgCount; ++i) {
514 if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
515 MI->getOperand(1).hasAllocatedReg() &&
516 MI->getOperand(1).getReg() == PPC::R0) {
518 // for long branch support, bc $+8
519 } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
520 TII.isBranch(MI->getOpcode())) {
522 assert(8 == MI->getOperand(i).getImmedValue()
523 && "branch off PC not to pc+8?");
524 //printOp(MI->getOperand(i));
525 } else if (MI->getOperand(i).isImmediate()) {
526 printImmOp(MI->getOperand(i), ArgType[i]);
528 printOp(MI->getOperand(i));
530 if (ArgCount - 1 == i)
539 // SwitchSection - Switch to the specified section of the executable if we are
540 // not already in it!
542 static void SwitchSection(std::ostream &OS, std::string &CurSection,
543 const char *NewSection) {
544 if (CurSection != NewSection) {
545 CurSection = NewSection;
546 if (!CurSection.empty())
547 OS << "\t" << NewSection << "\n";
551 bool PPC32AsmPrinter::doFinalization(Module &M) {
552 const TargetData &TD = TM.getTargetData();
553 std::string CurSection;
555 // Print out module-level global variables here.
556 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
557 if (I->hasInitializer()) { // External global require no code
559 std::string name = Mang->getValueName(I);
560 Constant *C = I->getInitializer();
561 unsigned Size = TD.getTypeSize(C->getType());
562 unsigned Align = TD.getTypeAlignment(C->getType());
564 if (C->isNullValue() && /* FIXME: Verify correct */
565 (I->hasInternalLinkage() || I->hasWeakLinkage())) {
566 SwitchSection(O, CurSection, ".data");
567 if (I->hasInternalLinkage())
568 O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
569 << "," << (unsigned)TD.getTypeAlignment(C->getType());
571 O << ".comm " << name << "," << TD.getTypeSize(C->getType());
573 WriteAsOperand(O, I, true, true, &M);
576 switch (I->getLinkage()) {
577 case GlobalValue::LinkOnceLinkage:
578 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
579 << ".weak_definition " << name << '\n'
580 << ".private_extern " << name << '\n'
581 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
582 LinkOnceStubs.insert(name);
584 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
585 // Nonnull linkonce -> weak
586 O << "\t.weak " << name << "\n";
587 SwitchSection(O, CurSection, "");
588 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
590 case GlobalValue::AppendingLinkage:
591 // FIXME: appending linkage variables should go into a section of
592 // their name or something. For now, just emit them as external.
593 case GlobalValue::ExternalLinkage:
594 // If external or appending, declare as a global symbol
595 O << "\t.globl " << name << "\n";
597 case GlobalValue::InternalLinkage:
598 SwitchSection(O, CurSection, ".data");
602 O << "\t.align " << Align << "\n";
603 O << name << ":\t\t\t\t; ";
604 WriteAsOperand(O, I, true, true, &M);
606 WriteAsOperand(O, C, false, false, &M);
608 emitGlobalConstant(C);
612 // Output stubs for dynamically-linked functions
613 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
617 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
619 O << "L" << *i << "$stub:\n";
620 O << "\t.indirect_symbol " << *i << "\n";
622 O << "\tbcl 20,31,L0$" << *i << "\n";
623 O << "L0$" << *i << ":\n";
625 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
627 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
628 O << "\tmtctr r12\n";
631 O << ".lazy_symbol_pointer\n";
632 O << "L" << *i << "$lazy_ptr:\n";
633 O << "\t.indirect_symbol " << *i << "\n";
634 O << "\t.long dyld_stub_binding_helper\n";
639 // Output stubs for external global variables
640 if (GVStubs.begin() != GVStubs.end())
641 O << ".data\n.non_lazy_symbol_pointer\n";
642 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
644 O << "L" << *i << "$non_lazy_ptr:\n";
645 O << "\t.indirect_symbol " << *i << "\n";
649 // Output stubs for link-once variables
650 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
651 O << ".data\n.align 2\n";
652 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
653 e = LinkOnceStubs.end(); i != e; ++i) {
654 O << "L" << *i << "$non_lazy_ptr:\n"
655 << "\t.long\t" << *i << '\n';
658 AsmPrinter::doFinalization(M);
659 return false; // success