1 //===-- PPC64AsmPrinter.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 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asmprinter"
18 #include "PowerPCInstrInfo.h"
19 #include "PPC64TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "Support/CommandLine.h"
30 #include "Support/Debug.h"
31 #include "Support/MathExtras.h"
32 #include "Support/Statistic.h"
33 #include "Support/StringExtras.h"
39 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
41 struct Printer : public MachineFunctionPass {
42 /// Output stream on which we're printing assembly code.
46 /// Target machine description which we query for reg. names, data
49 PPC64TargetMachine &TM;
51 /// Name-mangler for global names.
55 /// Map for labels corresponding to global variables
57 std::map<const GlobalVariable*,std::string> GVToLabelMap;
59 Printer(std::ostream &o, TargetMachine &tm) : O(o),
60 TM(reinterpret_cast<PPC64TargetMachine&>(tm)), LabelNumber(0) {}
62 /// Cache of mangled name for current function. This is
63 /// recalculated at the beginning of each call to
64 /// runOnMachineFunction().
66 std::string CurrentFnName;
68 /// Unique incrementer for label values for referencing Global values.
72 virtual const char *getPassName() const {
73 return "PPC64 Assembly Printer";
76 void printMachineInstruction(const MachineInstr *MI);
77 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
78 void printImmOp(const MachineOperand &MO, unsigned ArgType);
79 void printConstantPool(MachineConstantPool *MCP);
80 bool runOnMachineFunction(MachineFunction &F);
81 bool doInitialization(Module &M);
82 bool doFinalization(Module &M);
83 void emitGlobalConstant(const Constant* CV);
84 void emitConstantValueOnly(const Constant *CV);
86 } // end of anonymous namespace
88 /// createPPC64AsmPrinterPass - Returns a pass that prints the PPC
89 /// assembly code for a MachineFunction to the given output stream,
90 /// using the given target machine description. This should work
91 /// regardless of whether the function is in SSA form or not.
93 FunctionPass *createPPC64AsmPrinter(std::ostream &o,TargetMachine &tm) {
94 return new Printer(o, tm);
97 /// isStringCompatible - Can we treat the specified array as a string?
98 /// Only if it is an array of ubytes or non-negative sbytes.
100 static bool isStringCompatible(const ConstantArray *CVA) {
101 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
102 if (ETy == Type::UByteTy) return true;
103 if (ETy != Type::SByteTy) return false;
105 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
106 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
112 /// toOctal - Convert the low order bits of X into an octal digit.
114 static inline char toOctal(int X) {
118 // Possible states while outputting ASCII strings
127 /// SwitchStringSection - manage the changes required to output bytes as
128 /// characters in a string vs. numeric decimal values
130 static inline void SwitchStringSection(std::ostream &O, StringSection NewSect,
131 StringSection &Current) {
132 if (Current == None) {
133 if (NewSect == Alpha)
135 else if (NewSect == Numeric)
137 } else if (Current == Alpha) {
140 else if (NewSect == Numeric)
143 } else if (Current == Numeric) {
144 if (NewSect == Alpha)
147 else if (NewSect == Numeric)
154 /// getAsCString - Return the specified array as a C compatible
155 /// string, only if the predicate isStringCompatible is true.
157 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
158 assert(isStringCompatible(CVA) && "Array is not string compatible!");
160 if (CVA->getNumOperands() == 0)
163 StringSection Current = None;
164 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) {
165 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
167 SwitchStringSection(O, Alpha, Current);
169 } else if (isprint(C)) {
170 SwitchStringSection(O, Alpha, Current);
173 SwitchStringSection(O, Numeric, Current);
174 O << utostr((unsigned)C);
177 SwitchStringSection(O, None, Current);
181 // Print out the specified constant, without a storage class. Only the
182 // constants valid in constant expressions can occur here.
183 void Printer::emitConstantValueOnly(const Constant *CV) {
184 if (CV->isNullValue())
186 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
187 assert(CB == ConstantBool::True);
189 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
191 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
193 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
194 // This is a constant address for a global variable or function. Use the
195 // name of the variable or function as the address value.
196 O << Mang->getValueName(GV);
197 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
198 const TargetData &TD = TM.getTargetData();
199 switch (CE->getOpcode()) {
200 case Instruction::GetElementPtr: {
201 // generate a symbolic expression for the byte address
202 const Constant *ptrVal = CE->getOperand(0);
203 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
204 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
206 emitConstantValueOnly(ptrVal);
207 O << ") + " << Offset;
209 emitConstantValueOnly(ptrVal);
213 case Instruction::Cast: {
214 // Support only non-converting or widening casts for now, that is, ones
215 // that do not involve a change in value. This assertion is really gross,
216 // and may not even be a complete check.
217 Constant *Op = CE->getOperand(0);
218 const Type *OpTy = Op->getType(), *Ty = CE->getType();
220 // Remember, kids, pointers on x86 can be losslessly converted back and
221 // forth into 32-bit or wider integers, regardless of signedness. :-P
222 assert(((isa<PointerType>(OpTy)
223 && (Ty == Type::LongTy || Ty == Type::ULongTy
224 || Ty == Type::IntTy || Ty == Type::UIntTy))
225 || (isa<PointerType>(Ty)
226 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
227 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
228 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
229 && OpTy->isLosslesslyConvertibleTo(Ty))))
230 && "FIXME: Don't yet support this kind of constant cast expr");
232 emitConstantValueOnly(Op);
236 case Instruction::Add:
238 emitConstantValueOnly(CE->getOperand(0));
240 emitConstantValueOnly(CE->getOperand(1));
244 assert(0 && "Unsupported operator!");
247 assert(0 && "Unknown constant value!");
251 // Print a constant value or values, with the appropriate storage class as a
253 void Printer::emitGlobalConstant(const Constant *CV) {
254 const TargetData &TD = TM.getTargetData();
256 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
257 if (isStringCompatible(CVA)) {
258 printAsCString(O, CVA);
259 } else { // Not a string. Print the values in successive locations
260 for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
261 emitGlobalConstant(CVA->getOperand(i));
264 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
265 // Print the fields in successive locations. Pad to align if needed!
266 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
267 unsigned sizeSoFar = 0;
268 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
269 const Constant* field = CVS->getOperand(i);
271 // Check if padding is needed and insert one or more 0s.
272 unsigned fieldSize = TD.getTypeSize(field->getType());
273 unsigned padSize = ((i == e-1? cvsLayout->StructSize
274 : cvsLayout->MemberOffsets[i+1])
275 - cvsLayout->MemberOffsets[i]) - fieldSize;
276 sizeSoFar += fieldSize + padSize;
278 // Now print the actual field value
279 emitGlobalConstant(field);
281 // Insert the field padding unless it's zero bytes...
283 O << "\t.space\t " << padSize << "\n";
285 assert(sizeSoFar == cvsLayout->StructSize &&
286 "Layout of constant struct may be incorrect!");
288 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
289 // FP Constants are printed as integer constants to avoid losing
291 double Val = CFP->getValue();
292 switch (CFP->getType()->getTypeID()) {
293 default: assert(0 && "Unknown floating point type!");
294 case Type::FloatTyID: {
295 union FU { // Abide by C TBAA rules
300 O << "\t.long " << U.UVal << "\t# float " << Val << "\n";
303 case Type::DoubleTyID: {
304 union DU { // Abide by C TBAA rules
314 O << ".long " << U.T.MSWord << "\t# double most significant word "
316 O << ".long " << U.T.LSWord << "\t# double least significant word "
321 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
322 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
323 union DU { // Abide by C TBAA rules
330 U.UVal = CI->getRawValue();
332 O << ".long " << U.T.MSWord << "\t# Double-word most significant word "
334 O << ".long " << U.T.LSWord << "\t# Double-word least significant word "
340 const Type *type = CV->getType();
342 switch (type->getTypeID()) {
343 case Type::UByteTyID: case Type::SByteTyID:
346 case Type::UShortTyID: case Type::ShortTyID:
350 case Type::PointerTyID:
351 case Type::UIntTyID: case Type::IntTyID:
354 case Type::ULongTyID: case Type::LongTyID:
355 assert (0 && "Should have already output double-word constant.");
356 case Type::FloatTyID: case Type::DoubleTyID:
357 assert (0 && "Should have already output floating point constant.");
359 if (CV == Constant::getNullValue(type)) { // Zero initializer?
360 O << "\t.space " << TD.getTypeSize(type) << "\n";
363 std::cerr << "Can't handle printing: " << *CV;
368 emitConstantValueOnly(CV);
372 /// printConstantPool - Print to the current output stream assembly
373 /// representations of the constants in the constant pool MCP. This is
374 /// used to print out constants which have been "spilled to memory" by
375 /// the code generator.
377 void Printer::printConstantPool(MachineConstantPool *MCP) {
378 const std::vector<Constant*> &CP = MCP->getConstants();
379 const TargetData &TD = TM.getTargetData();
381 if (CP.empty()) return;
383 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
387 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
389 emitGlobalConstant(CP[i]);
393 /// runOnMachineFunction - This uses the printMachineInstruction()
394 /// method to print assembly for each instruction.
396 bool Printer::runOnMachineFunction(MachineFunction &MF) {
397 CurrentFnName = MF.getFunction()->getName();
399 // Print out constants referenced by the function
400 printConstantPool(MF.getConstantPool());
402 // Print out header for the function.
403 O << "\t.csect .text[PR]\n"
405 << "\t.globl " << CurrentFnName << '\n'
406 << "\t.globl ." << CurrentFnName << '\n'
407 << "\t.csect " << CurrentFnName << "[DS],3\n"
408 << CurrentFnName << ":\n"
409 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
410 << "\t.csect .text[PR]\n"
411 << '.' << CurrentFnName << ":\n";
413 // Print out code for the function.
414 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
416 // Print a label for the basic block.
417 O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
418 << I->getBasicBlock()->getName() << "\n";
419 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
421 // Print the assembly for the instruction.
423 printMachineInstruction(II);
428 O << "LT.." << CurrentFnName << ":\n"
430 << "\t.byte 0,0,32,65,128,0,0,0\n"
431 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
433 << "\t.byte \"" << CurrentFnName << "\"\n"
436 // We didn't modify anything.
440 void Printer::printOp(const MachineOperand &MO,
441 bool elideOffsetKeyword /* = false */) {
442 const MRegisterInfo &RI = *TM.getRegisterInfo();
445 switch (MO.getType()) {
446 case MachineOperand::MO_VirtualRegister:
447 if (Value *V = MO.getVRegValueOrNull()) {
448 O << "<" << V->getName() << ">";
452 case MachineOperand::MO_MachineRegister:
453 case MachineOperand::MO_CCRegister: {
454 // On AIX, do not print out the 'R' (GPR) or 'F' (FPR) in reg names
455 const char *regName = RI.get(MO.getReg()).Name;
456 if (regName[0] == 'R' || regName[0] == 'F')
463 case MachineOperand::MO_SignExtendedImmed:
464 case MachineOperand::MO_UnextendedImmed:
465 std::cerr << "printOp() does not handle immediate values\n";
469 case MachineOperand::MO_PCRelativeDisp:
470 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
474 case MachineOperand::MO_MachineBasicBlock: {
475 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
476 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
477 << "_" << MBBOp->getNumber() << "\t# "
478 << MBBOp->getBasicBlock()->getName();
482 case MachineOperand::MO_ConstantPoolIndex:
483 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
486 case MachineOperand::MO_ExternalSymbol:
487 O << MO.getSymbolName();
490 case MachineOperand::MO_GlobalAddress:
491 if (!elideOffsetKeyword) {
492 GlobalValue *GV = MO.getGlobal();
494 if (Function *F = dyn_cast<Function>(GV)) {
495 O << "." << F->getName();
496 } else if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
497 // output the label name
498 O << GVToLabelMap[GVar];
504 O << "<unknown operand type: " << MO.getType() << ">";
509 void Printer::printImmOp(const MachineOperand &MO, unsigned ArgType) {
510 int Imm = MO.getImmedValue();
511 if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
513 } else if (ArgType == PPCII::Zimm16) {
514 O << (unsigned short)Imm;
520 /// printMachineInstruction -- Print out a single PPC LLVM instruction
521 /// MI in Darwin syntax to the current output stream.
523 void Printer::printMachineInstruction(const MachineInstr *MI) {
524 unsigned Opcode = MI->getOpcode();
525 const TargetInstrInfo &TII = *TM.getInstrInfo();
526 const TargetInstrDescriptor &Desc = TII.get(Opcode);
529 unsigned ArgCount = MI->getNumOperands();
530 unsigned ArgType[] = {
531 (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
532 (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
533 (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
534 (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
535 (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
537 assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
538 "Instruction requires VMX support");
541 // CALLpcrel and CALLindirect are handled specially here to print only the
542 // appropriate number of args that the assembler expects. This is because
543 // may have many arguments appended to record the uses of registers that are
544 // holding arguments to the called function.
545 if (Opcode == PPC::COND_BRANCH) {
546 std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
548 } else if (Opcode == PPC::IMPLICIT_DEF) {
549 O << "# IMPLICIT DEF ";
550 printOp(MI->getOperand(0));
553 } else if (Opcode == PPC::CALLpcrel) {
554 O << TII.getName(Opcode) << " ";
555 printOp(MI->getOperand(0));
558 } else if (Opcode == PPC::CALLindirect) {
559 O << TII.getName(Opcode) << " ";
560 printImmOp(MI->getOperand(0), ArgType[0]);
562 printImmOp(MI->getOperand(1), ArgType[0]);
565 } else if (Opcode == PPC::MovePCtoLR) {
566 // FIXME: should probably be converted to cout.width and cout.fill
567 O << "bl \"L0000" << LabelNumber << "$pb\"\n";
568 O << "\"L0000" << LabelNumber << "$pb\":\n";
570 printOp(MI->getOperand(0));
575 O << TII.getName(Opcode) << " ";
576 if (Opcode == PPC::BLR || Opcode == PPC::NOP) {
578 } else if (ArgCount == 3 &&
579 (ArgType[1] == PPCII::Disimm16 || ArgType[1] == PPCII::Disimm14)) {
580 printOp(MI->getOperand(0));
582 MachineOperand MO = MI->getOperand(1);
583 if (MO.isImmediate())
584 printImmOp(MO, ArgType[1]);
588 printOp(MI->getOperand(2));
591 for (i = 0; i < ArgCount; ++i) {
593 if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
594 MI->getOperand(1).hasAllocatedReg() &&
595 MI->getOperand(1).getReg() == PPC::R0) {
597 // for long branch support, bc $+8
598 } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
599 TII.isBranch(MI->getOpcode())) {
601 assert(8 == MI->getOperand(i).getImmedValue()
602 && "branch off PC not to pc+8?");
603 //printOp(MI->getOperand(i));
604 } else if (MI->getOperand(i).isImmediate()) {
605 printImmOp(MI->getOperand(i), ArgType[i]);
607 printOp(MI->getOperand(i));
609 if (ArgCount - 1 == i)
617 // SwitchSection - Switch to the specified section of the executable if we are
618 // not already in it!
620 static void SwitchSection(std::ostream &OS, std::string &CurSection,
621 const char *NewSection) {
622 if (CurSection != NewSection) {
623 CurSection = NewSection;
624 if (!CurSection.empty())
625 OS << "\t" << NewSection << "\n";
629 bool Printer::doInitialization(Module &M) {
630 const TargetData &TD = TM.getTargetData();
631 std::string CurSection;
633 O << "\t.machine \"ppc64\"\n"
635 << "\t.csect .text[PR]\n";
637 // Print out module-level global variables
638 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
639 if (!I->hasInitializer())
642 std::string Name = I->getName();
643 Constant *C = I->getInitializer();
644 // N.B.: We are defaulting to writable strings
645 if (I->hasExternalLinkage()) {
646 O << "\t.globl " << Name << '\n'
647 << "\t.csect .data[RW],3\n";
649 O << "\t.csect _global.rw_c[RW],3\n";
652 emitGlobalConstant(C);
655 // Output labels for globals
656 if (M.gbegin() != M.gend()) O << "\t.toc\n";
657 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
658 const GlobalVariable *GV = I;
659 // Do not output labels for unused variables
660 if (GV->isExternal() && GV->use_begin() == GV->use_end())
663 std::string Name = GV->getName();
664 std::string Label = "LC.." + utostr(LabelNumber++);
665 GVToLabelMap[GV] = Label;
667 << "\t.tc " << Name << "[TC]," << Name;
668 if (GV->isExternal()) O << "[RW]";
672 Mang = new Mangler(M, true);
673 return false; // success
676 bool Printer::doFinalization(Module &M) {
677 const TargetData &TD = TM.getTargetData();
678 // Print out module-level global variables
679 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
680 if (I->hasInitializer() || I->hasExternalLinkage())
683 std::string Name = I->getName();
684 if (I->hasInternalLinkage()) {
685 O << "\t.lcomm " << Name << ",16,_global.bss_c";
687 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
688 << "," << log2((unsigned)TD.getTypeAlignment(I->getType()));
691 WriteAsOperand(O, I, true, true, &M);
695 O << "_section_.text:\n"
696 << "\t.csect .data[RW],3\n"
697 << "\t.llong _section_.text\n";
700 return false; // success
703 } // End llvm namespace