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/Support/Mangler.h"
28 #include "Support/CommandLine.h"
29 #include "Support/Debug.h"
30 #include "Support/MathExtras.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
38 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
40 struct Printer : public MachineFunctionPass {
41 /// Output stream on which we're printing assembly code.
45 /// Target machine description which we query for reg. names, data
48 PPC64TargetMachine &TM;
50 /// Name-mangler for global names.
54 /// Map for labels corresponding to global variables
56 std::map<const GlobalVariable*,std::string> GVToLabelMap;
58 Printer(std::ostream &o, TargetMachine &tm) : O(o),
59 TM(reinterpret_cast<PPC64TargetMachine&>(tm)), LabelNumber(0) {}
61 /// Cache of mangled name for current function. This is
62 /// recalculated at the beginning of each call to
63 /// runOnMachineFunction().
65 std::string CurrentFnName;
67 /// Unique incrementer for label values for referencing Global values.
71 virtual const char *getPassName() const {
72 return "PPC64 Assembly Printer";
75 void printMachineInstruction(const MachineInstr *MI);
76 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
77 void printImmOp(const MachineOperand &MO, unsigned ArgType);
78 void printConstantPool(MachineConstantPool *MCP);
79 bool runOnMachineFunction(MachineFunction &F);
80 bool doInitialization(Module &M);
81 bool doFinalization(Module &M);
82 void emitGlobalConstant(const Constant* CV);
83 void emitConstantValueOnly(const Constant *CV);
85 } // end of anonymous namespace
87 /// createPPC64AsmPrinterPass - Returns a pass that prints the PPC
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description. This should work
90 /// regardless of whether the function is in SSA form or not.
92 FunctionPass *createPPC64AsmPrinter(std::ostream &o,TargetMachine &tm) {
93 return new Printer(o, tm);
96 /// isStringCompatible - Can we treat the specified array as a string?
97 /// Only if it is an array of ubytes or non-negative sbytes.
99 static bool isStringCompatible(const ConstantArray *CVA) {
100 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
101 if (ETy == Type::UByteTy) return true;
102 if (ETy != Type::SByteTy) return false;
104 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
105 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
111 /// toOctal - Convert the low order bits of X into an octal digit.
113 static inline char toOctal(int X) {
117 // Possible states while outputting ASCII strings
126 /// SwitchStringSection - manage the changes required to output bytes as
127 /// characters in a string vs. numeric decimal values
129 static inline void SwitchStringSection(std::ostream &O, StringSection NewSect,
130 StringSection &Current) {
131 if (Current == None) {
132 if (NewSect == Alpha)
134 else if (NewSect == Numeric)
136 } else if (Current == Alpha) {
139 else if (NewSect == Numeric)
142 } else if (Current == Numeric) {
143 if (NewSect == Alpha)
146 else if (NewSect == Numeric)
153 /// getAsCString - Return the specified array as a C compatible
154 /// string, only if the predicate isStringCompatible is true.
156 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
157 assert(isStringCompatible(CVA) && "Array is not string compatible!");
159 if (CVA->getNumOperands() == 0)
162 StringSection Current = None;
163 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) {
164 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
166 SwitchStringSection(O, Alpha, Current);
168 } else if (isprint(C)) {
169 SwitchStringSection(O, Alpha, Current);
172 SwitchStringSection(O, Numeric, Current);
173 O << utostr((unsigned)C);
176 SwitchStringSection(O, None, Current);
180 // Print out the specified constant, without a storage class. Only the
181 // constants valid in constant expressions can occur here.
182 void Printer::emitConstantValueOnly(const Constant *CV) {
183 if (CV->isNullValue())
185 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
186 assert(CB == ConstantBool::True);
188 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
190 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
192 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
193 // This is a constant address for a global variable or function. Use the
194 // name of the variable or function as the address value.
195 O << Mang->getValueName(GV);
196 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
197 const TargetData &TD = TM.getTargetData();
198 switch (CE->getOpcode()) {
199 case Instruction::GetElementPtr: {
200 // generate a symbolic expression for the byte address
201 const Constant *ptrVal = CE->getOperand(0);
202 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
203 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
205 emitConstantValueOnly(ptrVal);
206 O << ") + " << Offset;
208 emitConstantValueOnly(ptrVal);
212 case Instruction::Cast: {
213 // Support only non-converting or widening casts for now, that is, ones
214 // that do not involve a change in value. This assertion is really gross,
215 // and may not even be a complete check.
216 Constant *Op = CE->getOperand(0);
217 const Type *OpTy = Op->getType(), *Ty = CE->getType();
219 // Remember, kids, pointers on x86 can be losslessly converted back and
220 // forth into 32-bit or wider integers, regardless of signedness. :-P
221 assert(((isa<PointerType>(OpTy)
222 && (Ty == Type::LongTy || Ty == Type::ULongTy
223 || Ty == Type::IntTy || Ty == Type::UIntTy))
224 || (isa<PointerType>(Ty)
225 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
226 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
227 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
228 && OpTy->isLosslesslyConvertibleTo(Ty))))
229 && "FIXME: Don't yet support this kind of constant cast expr");
231 emitConstantValueOnly(Op);
235 case Instruction::Add:
237 emitConstantValueOnly(CE->getOperand(0));
239 emitConstantValueOnly(CE->getOperand(1));
243 assert(0 && "Unsupported operator!");
246 assert(0 && "Unknown constant value!");
250 // Print a constant value or values, with the appropriate storage class as a
252 void Printer::emitGlobalConstant(const Constant *CV) {
253 const TargetData &TD = TM.getTargetData();
255 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
256 if (isStringCompatible(CVA)) {
257 printAsCString(O, CVA);
258 } else { // Not a string. Print the values in successive locations
259 for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
260 emitGlobalConstant(CVA->getOperand(i));
263 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
264 // Print the fields in successive locations. Pad to align if needed!
265 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
266 unsigned sizeSoFar = 0;
267 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
268 const Constant* field = CVS->getOperand(i);
270 // Check if padding is needed and insert one or more 0s.
271 unsigned fieldSize = TD.getTypeSize(field->getType());
272 unsigned padSize = ((i == e-1? cvsLayout->StructSize
273 : cvsLayout->MemberOffsets[i+1])
274 - cvsLayout->MemberOffsets[i]) - fieldSize;
275 sizeSoFar += fieldSize + padSize;
277 // Now print the actual field value
278 emitGlobalConstant(field);
280 // Insert the field padding unless it's zero bytes...
282 O << "\t.space\t " << padSize << "\n";
284 assert(sizeSoFar == cvsLayout->StructSize &&
285 "Layout of constant struct may be incorrect!");
287 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
288 // FP Constants are printed as integer constants to avoid losing
290 double Val = CFP->getValue();
291 switch (CFP->getType()->getTypeID()) {
292 default: assert(0 && "Unknown floating point type!");
293 case Type::FloatTyID: {
294 union FU { // Abide by C TBAA rules
299 O << "\t.long " << U.UVal << "\t# float " << Val << "\n";
302 case Type::DoubleTyID: {
303 union DU { // Abide by C TBAA rules
313 O << ".long " << U.T.MSWord << "\t# double most significant word "
315 O << ".long " << U.T.LSWord << "\t# double least significant word "
320 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
321 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
322 union DU { // Abide by C TBAA rules
329 U.UVal = CI->getRawValue();
331 O << ".long " << U.T.MSWord << "\t# Double-word most significant word "
333 O << ".long " << U.T.LSWord << "\t# Double-word least significant word "
339 const Type *type = CV->getType();
341 switch (type->getTypeID()) {
342 case Type::UByteTyID: case Type::SByteTyID:
345 case Type::UShortTyID: case Type::ShortTyID:
349 case Type::PointerTyID:
350 case Type::UIntTyID: case Type::IntTyID:
353 case Type::ULongTyID: case Type::LongTyID:
354 assert (0 && "Should have already output double-word constant.");
355 case Type::FloatTyID: case Type::DoubleTyID:
356 assert (0 && "Should have already output floating point constant.");
358 if (CV == Constant::getNullValue(type)) { // Zero initializer?
359 O << "\t.space " << TD.getTypeSize(type) << "\n";
362 std::cerr << "Can't handle printing: " << *CV;
367 emitConstantValueOnly(CV);
371 /// printConstantPool - Print to the current output stream assembly
372 /// representations of the constants in the constant pool MCP. This is
373 /// used to print out constants which have been "spilled to memory" by
374 /// the code generator.
376 void Printer::printConstantPool(MachineConstantPool *MCP) {
377 const std::vector<Constant*> &CP = MCP->getConstants();
378 const TargetData &TD = TM.getTargetData();
380 if (CP.empty()) return;
382 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
384 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
386 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
388 emitGlobalConstant(CP[i]);
392 /// runOnMachineFunction - This uses the printMachineInstruction()
393 /// method to print assembly for each instruction.
395 bool Printer::runOnMachineFunction(MachineFunction &MF) {
396 CurrentFnName = MF.getFunction()->getName();
398 // Print out constants referenced by the function
399 printConstantPool(MF.getConstantPool());
401 // Print out header for the function.
402 O << "\t.csect .text[PR]\n"
404 << "\t.globl " << CurrentFnName << '\n'
405 << "\t.globl ." << CurrentFnName << '\n'
406 << "\t.csect " << CurrentFnName << "[DS],3\n"
407 << CurrentFnName << ":\n"
408 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
409 << "\t.csect .text[PR]\n"
410 << '.' << CurrentFnName << ":\n";
412 // Print out code for the function.
413 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
415 // Print a label for the basic block.
416 O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
417 << I->getBasicBlock()->getName() << "\n";
418 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
420 // Print the assembly for the instruction.
422 printMachineInstruction(II);
427 O << "LT.." << CurrentFnName << ":\n"
429 << "\t.byte 0,0,32,65,128,0,0,0\n"
430 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
432 << "\t.byte \"" << CurrentFnName << "\"\n"
435 // We didn't modify anything.
439 void Printer::printOp(const MachineOperand &MO,
440 bool elideOffsetKeyword /* = false */) {
441 const MRegisterInfo &RI = *TM.getRegisterInfo();
444 switch (MO.getType()) {
445 case MachineOperand::MO_VirtualRegister:
446 if (Value *V = MO.getVRegValueOrNull()) {
447 O << "<" << V->getName() << ">";
451 case MachineOperand::MO_MachineRegister:
452 case MachineOperand::MO_CCRegister: {
453 // On AIX, do not print out the 'R' (GPR) or 'F' (FPR) in reg names
454 const char *regName = RI.get(MO.getReg()).Name;
455 if (regName[0] == 'R' || regName[0] == 'F')
462 case MachineOperand::MO_SignExtendedImmed:
463 case MachineOperand::MO_UnextendedImmed:
464 std::cerr << "printOp() does not handle immediate values\n";
468 case MachineOperand::MO_PCRelativeDisp:
469 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
473 case MachineOperand::MO_MachineBasicBlock: {
474 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
475 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
476 << "_" << MBBOp->getNumber() << "\t# "
477 << MBBOp->getBasicBlock()->getName();
481 case MachineOperand::MO_ConstantPoolIndex:
482 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
485 case MachineOperand::MO_ExternalSymbol:
486 O << MO.getSymbolName();
489 case MachineOperand::MO_GlobalAddress:
490 if (!elideOffsetKeyword) {
491 GlobalValue *GV = MO.getGlobal();
493 if (Function *F = dyn_cast<Function>(GV)) {
494 O << Mang->getValueName(F);
495 } else if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
496 // output the label name
497 O << GVToLabelMap[GVar];
503 O << "<unknown operand type: " << MO.getType() << ">";
508 void Printer::printImmOp(const MachineOperand &MO, unsigned ArgType) {
509 int Imm = MO.getImmedValue();
510 if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
517 /// printMachineInstruction -- Print out a single PPC LLVM instruction
518 /// MI in Darwin syntax to the current output stream.
520 void Printer::printMachineInstruction(const MachineInstr *MI) {
521 unsigned Opcode = MI->getOpcode();
522 const TargetInstrInfo &TII = *TM.getInstrInfo();
523 const TargetInstrDescriptor &Desc = TII.get(Opcode);
526 unsigned ArgCount = MI->getNumOperands();
527 unsigned ArgType[] = {
528 (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
529 (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
530 (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
531 (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
532 (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
534 assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
535 "Instruction requires VMX support");
538 // CALLpcrel and CALLindirect are handled specially here to print only the
539 // appropriate number of args that the assembler expects. This is because
540 // may have many arguments appended to record the uses of registers that are
541 // holding arguments to the called function.
542 if (Opcode == PPC::COND_BRANCH) {
543 std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
545 } else if (Opcode == PPC::IMPLICIT_DEF) {
546 O << "# IMPLICIT DEF ";
547 printOp(MI->getOperand(0));
550 } else if (Opcode == PPC::CALLpcrel) {
551 O << TII.getName(Opcode) << " ";
552 printOp(MI->getOperand(0));
555 } else if (Opcode == PPC::CALLindirect) {
556 O << TII.getName(Opcode) << " ";
557 printImmOp(MI->getOperand(0), ArgType[0]);
559 printImmOp(MI->getOperand(1), ArgType[0]);
562 } else if (Opcode == PPC::MovePCtoLR) {
563 // FIXME: should probably be converted to cout.width and cout.fill
564 O << "bl \"L0000" << LabelNumber << "$pb\"\n";
565 O << "\"L0000" << LabelNumber << "$pb\":\n";
567 printOp(MI->getOperand(0));
572 O << LowercaseString(TII.getName(Opcode)) << " ";
573 if (Opcode == PPC::BLR || Opcode == PPC::NOP) {
575 } else if (ArgCount == 3 &&
576 (ArgType[1] == PPCII::Disimm16 || ArgType[1] == PPCII::Disimm14)) {
577 printOp(MI->getOperand(0));
579 MachineOperand MO = MI->getOperand(1);
580 if (MO.isImmediate())
581 printImmOp(MO, ArgType[1]);
585 printOp(MI->getOperand(2));
588 for (i = 0; i < ArgCount; ++i) {
590 if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
591 MI->getOperand(1).hasAllocatedReg() &&
592 MI->getOperand(1).getReg() == PPC::R0) {
594 // for long branch support, bc $+8
595 } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
596 TII.isBranch(MI->getOpcode())) {
598 assert(8 == MI->getOperand(i).getImmedValue()
599 && "branch off PC not to pc+8?");
600 //printOp(MI->getOperand(i));
601 } else if (MI->getOperand(i).isImmediate()) {
602 printImmOp(MI->getOperand(i), ArgType[i]);
604 printOp(MI->getOperand(i));
606 if (ArgCount - 1 == i)
614 // SwitchSection - Switch to the specified section of the executable if we are
615 // not already in it!
617 static void SwitchSection(std::ostream &OS, std::string &CurSection,
618 const char *NewSection) {
619 if (CurSection != NewSection) {
620 CurSection = NewSection;
621 if (!CurSection.empty())
622 OS << "\t" << NewSection << "\n";
626 bool Printer::doInitialization(Module &M) {
627 const TargetData &TD = TM.getTargetData();
628 std::string CurSection;
630 O << "\t.machine \"ppc64\"\n"
632 << "\t.csect .text[PR]\n";
634 // Print out module-level global variables
635 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
636 if (!I->hasInitializer())
639 std::string Name = I->getName();
640 Constant *C = I->getInitializer();
641 // N.B.: We are defaulting to writable strings
642 if (I->hasExternalLinkage()) {
643 O << "\t.globl " << Name << '\n'
644 << "\t.csect .data[RW],3\n";
646 O << "\t.csect _global.rw_c[RW],3\n";
649 emitGlobalConstant(C);
652 // Output labels for globals
653 if (M.gbegin() != M.gend()) O << "\t.toc\n";
654 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
655 const GlobalVariable *GV = I;
656 // Do not output labels for unused variables
657 if (GV->isExternal() && GV->use_begin() == GV->use_end())
660 std::string Name = GV->getName();
661 std::string Label = "LC.." + utostr(LabelNumber++);
662 GVToLabelMap[GV] = Label;
664 << "\t.tc " << Name << "[TC]," << Name;
665 if (GV->isExternal()) O << "[RW]";
669 Mang = new Mangler(M, ".");
670 return false; // success
673 bool Printer::doFinalization(Module &M) {
674 const TargetData &TD = TM.getTargetData();
675 // Print out module-level global variables
676 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
677 if (I->hasInitializer() || I->hasExternalLinkage())
680 std::string Name = I->getName();
681 if (I->hasInternalLinkage()) {
682 O << "\t.lcomm " << Name << ",16,_global.bss_c";
684 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
685 << "," << log2((unsigned)TD.getTypeAlignment(I->getType()));
688 WriteAsOperand(O, I, true, true, &M);
692 O << "_section_.text:\n"
693 << "\t.csect .data[RW],3\n"
694 << "\t.llong _section_.text\n";
697 return false; // success
700 } // End llvm namespace