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) {
49 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
50 Data64bitsDirective = 0; // we can't emit a 64-bit unit
53 /// Unique incrementer for label values for referencing Global values.
57 virtual const char *getPassName() const {
58 return "PPC32 Assembly Printer";
61 PPC32TargetMachine &getTM() {
62 return static_cast<PPC32TargetMachine&>(TM);
65 /// printInstruction - This method is automatically generated by tablegen
66 /// from the instruction set description. This method returns true if the
67 /// machine instruction was sufficiently described to print it, otherwise it
69 bool printInstruction(const MachineInstr *MI);
71 void printMachineInstruction(const MachineInstr *MI);
72 void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
73 void printImmOp(const MachineOperand &MO, unsigned ArgType);
75 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
76 const MachineOperand &MO = MI->getOperand(OpNo);
77 if (MO.getType() == MachineOperand::MO_MachineRegister) {
78 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
79 O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
80 } else if (MO.isImmediate()) {
81 O << MO.getImmedValue();
87 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
89 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
92 void printConstantPool(MachineConstantPool *MCP);
93 bool runOnMachineFunction(MachineFunction &F);
94 bool doFinalization(Module &M);
96 } // end of anonymous namespace
98 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
99 /// assembly code for a MachineFunction to the given output stream,
100 /// using the given target machine description. This should work
101 /// regardless of whether the function is in SSA form or not.
103 FunctionPass *llvm::createPPC32AsmPrinter(std::ostream &o, TargetMachine &tm) {
104 return new PPC32AsmPrinter(o, tm);
107 // Include the auto-generated portion of the assembly writer
108 #include "PowerPCGenAsmWriter.inc"
110 /// printConstantPool - Print to the current output stream assembly
111 /// representations of the constants in the constant pool MCP. This is
112 /// used to print out constants which have been "spilled to memory" by
113 /// the code generator.
115 void PPC32AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
116 const std::vector<Constant*> &CP = MCP->getConstants();
117 const TargetData &TD = TM.getTargetData();
119 if (CP.empty()) return;
121 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
123 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
125 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
127 emitGlobalConstant(CP[i]);
131 /// runOnMachineFunction - This uses the printMachineInstruction()
132 /// method to print assembly for each instruction.
134 bool PPC32AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
135 setupMachineFunction(MF);
138 // Print out constants referenced by the function
139 printConstantPool(MF.getConstantPool());
141 // Print out labels for the function.
143 O << "\t.globl\t" << CurrentFnName << "\n";
145 O << CurrentFnName << ":\n";
147 // Print out code for the function.
148 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
150 // Print a label for the basic block.
151 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
152 << I->getBasicBlock()->getName() << "\n";
153 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
155 // Print the assembly for the instruction.
157 printMachineInstruction(II);
162 // We didn't modify anything.
166 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
167 bool LoadAddrOp /* = false */) {
168 const MRegisterInfo &RI = *TM.getRegisterInfo();
171 switch (MO.getType()) {
172 case MachineOperand::MO_VirtualRegister:
173 if (Value *V = MO.getVRegValueOrNull()) {
174 O << "<" << V->getName() << ">";
178 case MachineOperand::MO_MachineRegister:
179 case MachineOperand::MO_CCRegister:
180 O << LowercaseString(RI.get(MO.getReg()).Name);
183 case MachineOperand::MO_SignExtendedImmed:
184 case MachineOperand::MO_UnextendedImmed:
185 std::cerr << "printOp() does not handle immediate values\n";
189 case MachineOperand::MO_PCRelativeDisp:
190 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
194 case MachineOperand::MO_MachineBasicBlock: {
195 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
196 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
197 << "_" << MBBOp->getNumber() << "\t; "
198 << MBBOp->getBasicBlock()->getName();
202 case MachineOperand::MO_ConstantPoolIndex:
203 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
206 case MachineOperand::MO_ExternalSymbol:
207 O << MO.getSymbolName();
210 case MachineOperand::MO_GlobalAddress: {
211 GlobalValue *GV = MO.getGlobal();
212 std::string Name = Mang->getValueName(GV);
214 // Dynamically-resolved functions need a stub for the function. Be
215 // wary however not to output $stub for external functions whose addresses
216 // are taken. Those should be emitted as $non_lazy_ptr below.
217 Function *F = dyn_cast<Function>(GV);
218 if (F && F->isExternal() && !LoadAddrOp &&
219 getTM().CalledFunctions.count(F)) {
220 FnStubs.insert(Name);
221 O << "L" << Name << "$stub";
225 // External global variables need a non-lazily-resolved stub
226 if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
227 GVStubs.insert(Name);
228 O << "L" << Name << "$non_lazy_ptr";
232 if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
233 LinkOnceStubs.insert(Name);
234 O << "L" << Name << "$non_lazy_ptr";
238 O << Mang->getValueName(GV);
243 O << "<unknown operand type: " << MO.getType() << ">";
248 void PPC32AsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
249 int Imm = MO.getImmedValue();
250 if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
257 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
258 /// the current output stream.
260 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
262 if (printInstruction(MI))
263 return; // Printer was automatically generated
265 unsigned Opcode = MI->getOpcode();
266 const TargetInstrInfo &TII = *TM.getInstrInfo();
267 const TargetInstrDescriptor &Desc = TII.get(Opcode);
270 unsigned ArgCount = MI->getNumOperands();
271 unsigned ArgType[] = {
272 (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
273 (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
274 (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
275 (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
276 (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
278 assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
279 "Instruction requires VMX support");
280 assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
281 "Instruction requires 64 bit support");
283 // CALLpcrel and CALLindirect are handled specially here to print only the
284 // appropriate number of args that the assembler expects. This is because
285 // may have many arguments appended to record the uses of registers that are
286 // holding arguments to the called function.
287 if (Opcode == PPC::COND_BRANCH) {
288 std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
290 } else if (Opcode == PPC::IMPLICIT_DEF) {
291 O << "; IMPLICIT DEF ";
292 printOp(MI->getOperand(0));
295 } else if (Opcode == PPC::CALLpcrel) {
296 O << TII.getName(Opcode) << " ";
297 printOp(MI->getOperand(0));
300 } else if (Opcode == PPC::CALLindirect) {
301 O << TII.getName(Opcode) << " ";
302 printImmOp(MI->getOperand(0), ArgType[0]);
304 printImmOp(MI->getOperand(1), ArgType[0]);
307 } else if (Opcode == PPC::MovePCtoLR) {
308 // FIXME: should probably be converted to cout.width and cout.fill
309 O << "bl \"L0000" << LabelNumber << "$pb\"\n";
310 O << "\"L0000" << LabelNumber << "$pb\":\n";
312 printOp(MI->getOperand(0));
317 O << TII.getName(Opcode) << " ";
318 if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
319 printOp(MI->getOperand(0));
321 printOp(MI->getOperand(2), true /* LoadAddrOp */);
322 O << "-\"L0000" << LabelNumber << "$pb\")";
324 if (MI->getOperand(1).getReg() == PPC::R0)
327 printOp(MI->getOperand(1));
329 } else if (Opcode == PPC::LOADHiAddr) {
330 printOp(MI->getOperand(0));
332 if (MI->getOperand(1).getReg() == PPC::R0)
335 printOp(MI->getOperand(1));
337 printOp(MI->getOperand(2), true /* LoadAddrOp */);
338 O << "-\"L0000" << LabelNumber << "$pb\")\n";
339 } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
340 printOp(MI->getOperand(0));
342 printImmOp(MI->getOperand(1), ArgType[1]);
344 if (MI->getOperand(2).hasAllocatedReg() &&
345 MI->getOperand(2).getReg() == PPC::R0)
348 printOp(MI->getOperand(2));
351 for (i = 0; i < ArgCount; ++i) {
353 if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
354 MI->getOperand(1).hasAllocatedReg() &&
355 MI->getOperand(1).getReg() == PPC::R0) {
357 // for long branch support, bc $+8
358 } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
359 TII.isBranch(MI->getOpcode())) {
361 assert(8 == MI->getOperand(i).getImmedValue()
362 && "branch off PC not to pc+8?");
363 //printOp(MI->getOperand(i));
364 } else if (MI->getOperand(i).isImmediate()) {
365 printImmOp(MI->getOperand(i), ArgType[i]);
367 printOp(MI->getOperand(i));
369 if (ArgCount - 1 == i)
378 // SwitchSection - Switch to the specified section of the executable if we are
379 // not already in it!
381 static void SwitchSection(std::ostream &OS, std::string &CurSection,
382 const char *NewSection) {
383 if (CurSection != NewSection) {
384 CurSection = NewSection;
385 if (!CurSection.empty())
386 OS << "\t" << NewSection << "\n";
390 bool PPC32AsmPrinter::doFinalization(Module &M) {
391 const TargetData &TD = TM.getTargetData();
392 std::string CurSection;
394 // Print out module-level global variables here.
395 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
396 if (I->hasInitializer()) { // External global require no code
398 std::string name = Mang->getValueName(I);
399 Constant *C = I->getInitializer();
400 unsigned Size = TD.getTypeSize(C->getType());
401 unsigned Align = TD.getTypeAlignment(C->getType());
403 if (C->isNullValue() && /* FIXME: Verify correct */
404 (I->hasInternalLinkage() || I->hasWeakLinkage())) {
405 SwitchSection(O, CurSection, ".data");
406 if (I->hasInternalLinkage())
407 O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
408 << "," << (unsigned)TD.getTypeAlignment(C->getType());
410 O << ".comm " << name << "," << TD.getTypeSize(C->getType());
412 WriteAsOperand(O, I, true, true, &M);
415 switch (I->getLinkage()) {
416 case GlobalValue::LinkOnceLinkage:
417 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
418 << ".weak_definition " << name << '\n'
419 << ".private_extern " << name << '\n'
420 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
421 LinkOnceStubs.insert(name);
423 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
424 // Nonnull linkonce -> weak
425 O << "\t.weak " << name << "\n";
426 SwitchSection(O, CurSection, "");
427 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
429 case GlobalValue::AppendingLinkage:
430 // FIXME: appending linkage variables should go into a section of
431 // their name or something. For now, just emit them as external.
432 case GlobalValue::ExternalLinkage:
433 // If external or appending, declare as a global symbol
434 O << "\t.globl " << name << "\n";
436 case GlobalValue::InternalLinkage:
437 SwitchSection(O, CurSection, ".data");
441 O << "\t.align " << Align << "\n";
442 O << name << ":\t\t\t\t; ";
443 WriteAsOperand(O, I, true, true, &M);
445 WriteAsOperand(O, C, false, false, &M);
447 emitGlobalConstant(C);
451 // Output stubs for dynamically-linked functions
452 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
456 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
458 O << "L" << *i << "$stub:\n";
459 O << "\t.indirect_symbol " << *i << "\n";
461 O << "\tbcl 20,31,L0$" << *i << "\n";
462 O << "L0$" << *i << ":\n";
464 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
466 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
467 O << "\tmtctr r12\n";
470 O << ".lazy_symbol_pointer\n";
471 O << "L" << *i << "$lazy_ptr:\n";
472 O << "\t.indirect_symbol " << *i << "\n";
473 O << "\t.long dyld_stub_binding_helper\n";
478 // Output stubs for external global variables
479 if (GVStubs.begin() != GVStubs.end())
480 O << ".data\n.non_lazy_symbol_pointer\n";
481 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
483 O << "L" << *i << "$non_lazy_ptr:\n";
484 O << "\t.indirect_symbol " << *i << "\n";
488 // Output stubs for link-once variables
489 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
490 O << ".data\n.align 2\n";
491 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
492 e = LinkOnceStubs.end(); i != e; ++i) {
493 O << "L" << *i << "$non_lazy_ptr:\n"
494 << "\t.long\t" << *i << '\n';
497 AsmPrinter::doFinalization(M);
498 return false; // success