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) {
50 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
51 Data64bitsDirective = 0; // we can't emit a 64-bit unit
54 /// Unique incrementer for label values for referencing Global values.
58 virtual const char *getPassName() const {
59 return "PPC32 Assembly Printer";
62 PPC32TargetMachine &getTM() {
63 return static_cast<PPC32TargetMachine&>(TM);
66 /// printInstruction - This method is automatically generated by tablegen
67 /// from the instruction set description. This method returns true if the
68 /// machine instruction was sufficiently described to print it, otherwise it
70 bool printInstruction(const MachineInstr *MI);
72 void printMachineInstruction(const MachineInstr *MI);
73 void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
74 void printImmOp(const MachineOperand &MO, unsigned ArgType);
76 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
77 const MachineOperand &MO = MI->getOperand(OpNo);
78 if (MO.getType() == MachineOperand::MO_MachineRegister) {
79 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
80 O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
81 } else if (MO.isImmediate()) {
82 O << MO.getImmedValue();
88 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
90 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
93 void printConstantPool(MachineConstantPool *MCP);
94 bool runOnMachineFunction(MachineFunction &F);
95 bool doFinalization(Module &M);
97 } // end of anonymous namespace
99 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
100 /// assembly code for a MachineFunction to the given output stream,
101 /// using the given target machine description. This should work
102 /// regardless of whether the function is in SSA form or not.
104 FunctionPass *llvm::createPPC32AsmPrinter(std::ostream &o, TargetMachine &tm) {
105 return new PPC32AsmPrinter(o, tm);
108 // Include the auto-generated portion of the assembly writer
109 #include "PowerPCGenAsmWriter.inc"
111 /// printConstantPool - Print to the current output stream assembly
112 /// representations of the constants in the constant pool MCP. This is
113 /// used to print out constants which have been "spilled to memory" by
114 /// the code generator.
116 void PPC32AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
117 const std::vector<Constant*> &CP = MCP->getConstants();
118 const TargetData &TD = TM.getTargetData();
120 if (CP.empty()) return;
122 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
124 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
126 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
128 emitGlobalConstant(CP[i]);
132 /// runOnMachineFunction - This uses the printMachineInstruction()
133 /// method to print assembly for each instruction.
135 bool PPC32AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
136 setupMachineFunction(MF);
139 // Print out constants referenced by the function
140 printConstantPool(MF.getConstantPool());
142 // Print out labels for the function.
144 O << "\t.globl\t" << CurrentFnName << "\n";
146 O << CurrentFnName << ":\n";
148 // Print out code for the function.
149 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
151 // Print a label for the basic block.
152 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
153 << I->getBasicBlock()->getName() << "\n";
154 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
156 // Print the assembly for the instruction.
158 printMachineInstruction(II);
163 // We didn't modify anything.
167 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
168 bool LoadAddrOp /* = false */) {
169 const MRegisterInfo &RI = *TM.getRegisterInfo();
172 switch (MO.getType()) {
173 case MachineOperand::MO_VirtualRegister:
174 if (Value *V = MO.getVRegValueOrNull()) {
175 O << "<" << V->getName() << ">";
179 case MachineOperand::MO_MachineRegister:
180 case MachineOperand::MO_CCRegister:
181 O << LowercaseString(RI.get(MO.getReg()).Name);
184 case MachineOperand::MO_SignExtendedImmed:
185 case MachineOperand::MO_UnextendedImmed:
186 std::cerr << "printOp() does not handle immediate values\n";
190 case MachineOperand::MO_PCRelativeDisp:
191 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
195 case MachineOperand::MO_MachineBasicBlock: {
196 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
197 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
198 << "_" << MBBOp->getNumber() << "\t; "
199 << MBBOp->getBasicBlock()->getName();
203 case MachineOperand::MO_ConstantPoolIndex:
204 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
207 case MachineOperand::MO_ExternalSymbol:
208 O << MO.getSymbolName();
211 case MachineOperand::MO_GlobalAddress: {
212 GlobalValue *GV = MO.getGlobal();
213 std::string Name = Mang->getValueName(GV);
215 // Dynamically-resolved functions need a stub for the function. Be
216 // wary however not to output $stub for external functions whose addresses
217 // are taken. Those should be emitted as $non_lazy_ptr below.
218 Function *F = dyn_cast<Function>(GV);
219 if (F && F->isExternal() && !LoadAddrOp &&
220 getTM().CalledFunctions.count(F)) {
221 FnStubs.insert(Name);
222 O << "L" << Name << "$stub";
226 // External global variables need a non-lazily-resolved stub
227 if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
228 GVStubs.insert(Name);
229 O << "L" << Name << "$non_lazy_ptr";
233 if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
234 LinkOnceStubs.insert(Name);
235 O << "L" << Name << "$non_lazy_ptr";
239 O << Mang->getValueName(GV);
244 O << "<unknown operand type: " << MO.getType() << ">";
249 void PPC32AsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
250 int Imm = MO.getImmedValue();
251 if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
258 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
259 /// the current output stream.
261 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
263 if (printInstruction(MI))
264 return; // Printer was automatically generated
266 unsigned Opcode = MI->getOpcode();
267 const TargetInstrInfo &TII = *TM.getInstrInfo();
268 const TargetInstrDescriptor &Desc = TII.get(Opcode);
271 unsigned ArgCount = MI->getNumOperands();
272 unsigned ArgType[] = {
273 (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
274 (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
275 (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
276 (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
277 (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
279 assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
280 "Instruction requires VMX support");
281 assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
282 "Instruction requires 64 bit support");
284 // CALLpcrel and CALLindirect are handled specially here to print only the
285 // appropriate number of args that the assembler expects. This is because
286 // may have many arguments appended to record the uses of registers that are
287 // holding arguments to the called function.
288 if (Opcode == PPC::COND_BRANCH) {
289 std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
291 } else if (Opcode == PPC::IMPLICIT_DEF) {
292 O << "; IMPLICIT DEF ";
293 printOp(MI->getOperand(0));
296 } else if (Opcode == PPC::CALLpcrel) {
297 O << TII.getName(Opcode) << " ";
298 printOp(MI->getOperand(0));
301 } else if (Opcode == PPC::CALLindirect) {
302 O << TII.getName(Opcode) << " ";
303 printImmOp(MI->getOperand(0), ArgType[0]);
305 printImmOp(MI->getOperand(1), ArgType[0]);
308 } else if (Opcode == PPC::MovePCtoLR) {
309 // FIXME: should probably be converted to cout.width and cout.fill
310 O << "bl \"L0000" << LabelNumber << "$pb\"\n";
311 O << "\"L0000" << LabelNumber << "$pb\":\n";
313 printOp(MI->getOperand(0));
318 O << TII.getName(Opcode) << " ";
319 if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
320 printOp(MI->getOperand(0));
322 printOp(MI->getOperand(2), true /* LoadAddrOp */);
323 O << "-\"L0000" << LabelNumber << "$pb\")";
325 if (MI->getOperand(1).getReg() == PPC::R0)
328 printOp(MI->getOperand(1));
330 } else if (Opcode == PPC::LOADHiAddr) {
331 printOp(MI->getOperand(0));
333 if (MI->getOperand(1).getReg() == PPC::R0)
336 printOp(MI->getOperand(1));
338 printOp(MI->getOperand(2), true /* LoadAddrOp */);
339 O << "-\"L0000" << LabelNumber << "$pb\")\n";
340 } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
341 printOp(MI->getOperand(0));
343 printImmOp(MI->getOperand(1), ArgType[1]);
345 if (MI->getOperand(2).hasAllocatedReg() &&
346 MI->getOperand(2).getReg() == PPC::R0)
349 printOp(MI->getOperand(2));
352 for (i = 0; i < ArgCount; ++i) {
354 if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
355 MI->getOperand(1).hasAllocatedReg() &&
356 MI->getOperand(1).getReg() == PPC::R0) {
358 // for long branch support, bc $+8
359 } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
360 TII.isBranch(MI->getOpcode())) {
362 assert(8 == MI->getOperand(i).getImmedValue()
363 && "branch off PC not to pc+8?");
364 //printOp(MI->getOperand(i));
365 } else if (MI->getOperand(i).isImmediate()) {
366 printImmOp(MI->getOperand(i), ArgType[i]);
368 printOp(MI->getOperand(i));
370 if (ArgCount - 1 == i)
379 // SwitchSection - Switch to the specified section of the executable if we are
380 // not already in it!
382 static void SwitchSection(std::ostream &OS, std::string &CurSection,
383 const char *NewSection) {
384 if (CurSection != NewSection) {
385 CurSection = NewSection;
386 if (!CurSection.empty())
387 OS << "\t" << NewSection << "\n";
391 bool PPC32AsmPrinter::doFinalization(Module &M) {
392 const TargetData &TD = TM.getTargetData();
393 std::string CurSection;
395 // Print out module-level global variables here.
396 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
397 if (I->hasInitializer()) { // External global require no code
399 std::string name = Mang->getValueName(I);
400 Constant *C = I->getInitializer();
401 unsigned Size = TD.getTypeSize(C->getType());
402 unsigned Align = TD.getTypeAlignment(C->getType());
404 if (C->isNullValue() && /* FIXME: Verify correct */
405 (I->hasInternalLinkage() || I->hasWeakLinkage())) {
406 SwitchSection(O, CurSection, ".data");
407 if (I->hasInternalLinkage())
408 O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
409 << "," << (unsigned)TD.getTypeAlignment(C->getType());
411 O << ".comm " << name << "," << TD.getTypeSize(C->getType());
413 WriteAsOperand(O, I, true, true, &M);
416 switch (I->getLinkage()) {
417 case GlobalValue::LinkOnceLinkage:
418 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
419 << ".weak_definition " << name << '\n'
420 << ".private_extern " << name << '\n'
421 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
422 LinkOnceStubs.insert(name);
424 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
425 // Nonnull linkonce -> weak
426 O << "\t.weak " << name << "\n";
427 SwitchSection(O, CurSection, "");
428 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
430 case GlobalValue::AppendingLinkage:
431 // FIXME: appending linkage variables should go into a section of
432 // their name or something. For now, just emit them as external.
433 case GlobalValue::ExternalLinkage:
434 // If external or appending, declare as a global symbol
435 O << "\t.globl " << name << "\n";
437 case GlobalValue::InternalLinkage:
438 SwitchSection(O, CurSection, ".data");
442 O << "\t.align " << Align << "\n";
443 O << name << ":\t\t\t\t; ";
444 WriteAsOperand(O, I, true, true, &M);
446 WriteAsOperand(O, C, false, false, &M);
448 emitGlobalConstant(C);
452 // Output stubs for dynamically-linked functions
453 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
457 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
459 O << "L" << *i << "$stub:\n";
460 O << "\t.indirect_symbol " << *i << "\n";
462 O << "\tbcl 20,31,L0$" << *i << "\n";
463 O << "L0$" << *i << ":\n";
465 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
467 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
468 O << "\tmtctr r12\n";
471 O << ".lazy_symbol_pointer\n";
472 O << "L" << *i << "$lazy_ptr:\n";
473 O << "\t.indirect_symbol " << *i << "\n";
474 O << "\t.long dyld_stub_binding_helper\n";
479 // Output stubs for external global variables
480 if (GVStubs.begin() != GVStubs.end())
481 O << ".data\n.non_lazy_symbol_pointer\n";
482 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
484 O << "L" << *i << "$non_lazy_ptr:\n";
485 O << "\t.indirect_symbol " << *i << "\n";
489 // Output stubs for link-once variables
490 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
491 O << ".data\n.align 2\n";
492 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
493 e = LinkOnceStubs.end(); i != e; ++i) {
494 O << "L" << *i << "$non_lazy_ptr:\n"
495 << "\t.long\t" << *i << '\n';
498 AsmPrinter::doFinalization(M);
499 return false; // success