1 //===-- X86/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===//
3 // This file contains a printer that converts from our internal
4 // representation of machine-dependent LLVM code to Intel-format
5 // assembly language. This printer is the output mechanism used
6 // by `llc' and `lli -printmachineinstrs' on X86.
8 //===----------------------------------------------------------------------===//
11 #include "X86InstrInfo.h"
12 #include "llvm/Function.h"
13 #include "llvm/Constant.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineConstantPool.h"
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/Type.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/DerivedTypes.h"
22 #include "Support/StringExtras.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/Mangler.h"
27 struct Printer : public MachineFunctionPass {
28 /// Output stream on which we're printing assembly code.
32 /// Target machine description which we query for reg. names, data
37 /// Name-mangler for global names.
41 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
43 /// We name each basic block in a Function with a unique number, so
44 /// that we can consistently refer to them later. This is cleared
45 /// at the beginning of each call to runOnMachineFunction().
47 typedef std::map<const Value *, unsigned> ValueMapTy;
48 ValueMapTy NumberForBB;
50 /// Cache of mangled name for current function. This is
51 /// recalculated at the beginning of each call to
52 /// runOnMachineFunction().
54 std::string CurrentFnName;
56 virtual const char *getPassName() const {
57 return "X86 Assembly Printer";
60 void printMachineInstruction(const MachineInstr *MI);
61 void printOp(const MachineOperand &MO,
62 bool elideOffsetKeyword = false);
63 void printMemReference(const MachineInstr *MI, unsigned Op);
64 void printConstantPool(MachineConstantPool *MCP);
65 bool runOnMachineFunction(MachineFunction &F);
66 std::string ConstantExprToString(const ConstantExpr* CE);
67 std::string valToExprString(const Value* V);
68 bool doInitialization(Module &M);
69 bool doFinalization(Module &M);
70 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
71 void printSingleConstantValue(const Constant* CV);
73 } // end of anonymous namespace
75 /// createX86CodePrinterPass - Returns a pass that prints the X86
76 /// assembly code for a MachineFunction to the given output stream,
77 /// using the given target machine description. This should work
78 /// regardless of whether the function is in SSA form.
80 Pass *createX86CodePrinterPass(std::ostream &o, TargetMachine &tm) {
81 return new Printer(o, tm);
84 /// valToExprString - Helper function for ConstantExprToString().
85 /// Appends result to argument string S.
87 std::string Printer::valToExprString(const Value* V) {
90 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
91 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
92 S += std::string(CB == ConstantBool::True ? "1" : "0");
93 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
94 S += itostr(CI->getValue());
95 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
96 S += utostr(CI->getValue());
97 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
98 S += ftostr(CFP->getValue());
99 else if (isa<ConstantPointerNull>(CV))
101 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
102 S += valToExprString(CPR->getValue());
103 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
104 S += ConstantExprToString(CE);
107 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
108 S += Mang->getValueName(GV);
114 assert(0 && "Cannot convert value to string");
115 S += "<illegal-value>";
120 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
121 /// and return this as a string.
123 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
125 const TargetData &TD = TM.getTargetData();
126 switch(CE->getOpcode()) {
127 case Instruction::GetElementPtr:
128 { // generate a symbolic expression for the byte address
129 const Value* ptrVal = CE->getOperand(0);
130 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
131 S += "(" + valToExprString(ptrVal) + ") + ("
132 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
136 case Instruction::Cast:
137 // Support only non-converting or widening casts for now, that is,
138 // ones that do not involve a change in value. This assertion is
139 // not a complete check.
141 Constant *Op = CE->getOperand(0);
142 const Type *OpTy = Op->getType(), *Ty = CE->getType();
143 assert(((isa<PointerType>(OpTy)
144 && (Ty == Type::LongTy || Ty == Type::ULongTy))
145 || (isa<PointerType>(Ty)
146 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
147 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
148 && (OpTy-> isLosslesslyConvertibleTo(Ty))))
149 && "FIXME: Don't yet support this kind of constant cast expr");
150 S += "(" + valToExprString(Op) + ")";
154 case Instruction::Add:
155 S += "(" + valToExprString(CE->getOperand(0)) + ") + ("
156 + valToExprString(CE->getOperand(1)) + ")";
160 assert(0 && "Unsupported operator in ConstantExprToString()");
167 /// printSingleConstantValue - Print a single constant value.
170 Printer::printSingleConstantValue(const Constant* CV)
172 assert(CV->getType() != Type::VoidTy &&
173 CV->getType() != Type::TypeTy &&
174 CV->getType() != Type::LabelTy &&
175 "Unexpected type for Constant");
177 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
178 && "Aggregate types should be handled outside this function");
180 const Type *type = CV->getType();
182 switch(type->getPrimitiveID())
184 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
187 case Type::UShortTyID: case Type::ShortTyID:
190 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
193 case Type::ULongTyID: case Type::LongTyID:
196 case Type::FloatTyID:
199 case Type::DoubleTyID:
202 case Type::ArrayTyID:
203 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
204 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
207 assert (0 && "Can't handle printing this type of array");
210 assert (0 && "Can't handle printing this type of thing");
215 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
217 // Constant expression built from operators, constants, and
219 O << ConstantExprToString(CE) << "\n";
221 else if (type->isPrimitiveType())
223 if (type->isFloatingPoint()) {
224 // FP Constants are printed as integer constants to avoid losing
226 double Val = cast<ConstantFP>(CV)->getValue();
227 if (type == Type::FloatTy) {
228 float FVal = (float)Val;
229 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
230 O << *(unsigned int*)ProxyPtr;
231 } else if (type == Type::DoubleTy) {
232 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
233 O << *(uint64_t*)ProxyPtr;
235 assert(0 && "Unknown floating point type!");
238 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
240 WriteAsOperand(O, CV, false, false) << "\n";
243 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
245 // This is a constant address for a global variable or method.
246 // Use the name of the variable or method as the address value.
247 O << Mang->getValueName(CPR->getValue()) << "\n";
249 else if (isa<ConstantPointerNull>(CV))
251 // Null pointer value
256 assert(0 && "Unknown elementary type for constant");
260 /// isStringCompatible - Can we treat the specified array as a string?
261 /// Only if it is an array of ubytes or non-negative sbytes.
263 static bool isStringCompatible(const ConstantArray *CVA) {
264 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
265 if (ETy == Type::UByteTy) return true;
266 if (ETy != Type::SByteTy) return false;
268 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
269 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
275 /// toOctal - Convert the low order bits of X into an octal digit.
277 static inline char toOctal(int X) {
281 /// getAsCString - Return the specified array as a C compatible
282 /// string, only if the predicate isStringCompatible is true.
284 static std::string getAsCString(const ConstantArray *CVA) {
285 assert(isStringCompatible(CVA) && "Array is not string compatible!");
288 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
290 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
291 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
295 } else if (C == '\\') {
297 } else if (isprint(C)) {
301 case '\a': Result += "\\a"; break;
302 case '\b': Result += "\\b"; break;
303 case '\f': Result += "\\f"; break;
304 case '\n': Result += "\\n"; break;
305 case '\r': Result += "\\r"; break;
306 case '\t': Result += "\\t"; break;
307 case '\v': Result += "\\v"; break;
310 Result += toOctal(C >> 6);
311 Result += toOctal(C >> 3);
312 Result += toOctal(C >> 0);
321 // Print a constant value or values (it may be an aggregate).
322 // Uses printSingleConstantValue() to print each individual value.
324 Printer::printConstantValueOnly(const Constant* CV,
325 int numPadBytesAfter /* = 0 */)
327 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
328 const TargetData &TD = TM.getTargetData();
330 if (CVA && isStringCompatible(CVA))
331 { // print the string alone and return
332 O << "\t" << ".string" << "\t" << getAsCString(CVA) << "\n";
335 { // Not a string. Print the values in successive locations
336 const std::vector<Use> &constValues = CVA->getValues();
337 for (unsigned i=0; i < constValues.size(); i++)
338 printConstantValueOnly(cast<Constant>(constValues[i].get()));
340 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
341 { // Print the fields in successive locations. Pad to align if needed!
342 const StructLayout *cvsLayout =
343 TD.getStructLayout(CVS->getType());
344 const std::vector<Use>& constValues = CVS->getValues();
345 unsigned sizeSoFar = 0;
346 for (unsigned i=0, N = constValues.size(); i < N; i++)
348 const Constant* field = cast<Constant>(constValues[i].get());
350 // Check if padding is needed and insert one or more 0s.
351 unsigned fieldSize = TD.getTypeSize(field->getType());
352 int padSize = ((i == N-1? cvsLayout->StructSize
353 : cvsLayout->MemberOffsets[i+1])
354 - cvsLayout->MemberOffsets[i]) - fieldSize;
355 sizeSoFar += (fieldSize + padSize);
357 // Now print the actual field value
358 printConstantValueOnly(field, padSize);
360 assert(sizeSoFar == cvsLayout->StructSize &&
361 "Layout of constant struct may be incorrect!");
364 printSingleConstantValue(CV);
366 if (numPadBytesAfter) {
367 unsigned numBytes = numPadBytesAfter;
368 for ( ; numBytes >= 8; numBytes -= 8)
369 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
372 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
376 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
380 /// printConstantPool - Print to the current output stream assembly
381 /// representations of the constants in the constant pool MCP. This is
382 /// used to print out constants which have been "spilled to memory" by
383 /// the code generator.
385 void Printer::printConstantPool(MachineConstantPool *MCP) {
386 const std::vector<Constant*> &CP = MCP->getConstants();
387 const TargetData &TD = TM.getTargetData();
389 if (CP.empty()) return;
391 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
392 O << "\t.section .rodata\n";
393 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
395 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
397 printConstantValueOnly (CP[i]);
401 /// runOnMachineFunction - This uses the printMachineInstruction()
402 /// method to print assembly for each instruction.
404 bool Printer::runOnMachineFunction(MachineFunction &MF) {
405 // BBNumber is used here so that a given Printer will never give two
406 // BBs the same name. (If you have a better way, please let me know!)
407 static unsigned BBNumber = 0;
409 // What's my mangled name?
410 CurrentFnName = Mang->getValueName(MF.getFunction());
412 // Print out constants referenced by the function
413 printConstantPool(MF.getConstantPool());
415 // Print out labels for the function.
417 O << "\t.align 16\n";
418 O << "\t.globl\t" << CurrentFnName << "\n";
419 O << "\t.type\t" << CurrentFnName << ", @function\n";
420 O << CurrentFnName << ":\n";
422 // Number each basic block so that we can consistently refer to them
423 // in PC-relative references.
425 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
427 NumberForBB[I->getBasicBlock()] = BBNumber++;
430 // Print out code for the function.
431 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
433 // Print a label for the basic block.
434 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
435 << I->getBasicBlock()->getName() << "\n";
436 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
438 // Print the assembly for the instruction.
440 printMachineInstruction(*II);
444 // We didn't modify anything.
448 static bool isScale(const MachineOperand &MO) {
449 return MO.isImmediate() &&
450 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
451 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
454 static bool isMem(const MachineInstr *MI, unsigned Op) {
455 if (MI->getOperand(Op).isFrameIndex()) return true;
456 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
457 return Op+4 <= MI->getNumOperands() &&
458 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
459 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
462 void Printer::printOp(const MachineOperand &MO,
463 bool elideOffsetKeyword /* = false */) {
464 const MRegisterInfo &RI = *TM.getRegisterInfo();
465 switch (MO.getType()) {
466 case MachineOperand::MO_VirtualRegister:
467 if (Value *V = MO.getVRegValueOrNull()) {
468 O << "<" << V->getName() << ">";
472 case MachineOperand::MO_MachineRegister:
473 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
474 O << RI.get(MO.getReg()).Name;
476 O << "%reg" << MO.getReg();
479 case MachineOperand::MO_SignExtendedImmed:
480 case MachineOperand::MO_UnextendedImmed:
481 O << (int)MO.getImmedValue();
483 case MachineOperand::MO_PCRelativeDisp:
485 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
486 assert (i != NumberForBB.end()
487 && "Could not find a BB I previously put in the NumberForBB map!");
488 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
491 case MachineOperand::MO_GlobalAddress:
492 if (!elideOffsetKeyword)
494 O << Mang->getValueName(MO.getGlobal());
496 case MachineOperand::MO_ExternalSymbol:
497 O << MO.getSymbolName();
500 O << "<unknown operand type>"; return;
504 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
505 switch (Desc.TSFlags & X86II::ArgMask) {
506 default: assert(0 && "Unknown arg size!");
507 case X86II::Arg8: return "BYTE PTR";
508 case X86II::Arg16: return "WORD PTR";
509 case X86II::Arg32: return "DWORD PTR";
510 case X86II::Arg64: return "QWORD PTR";
511 case X86II::ArgF32: return "DWORD PTR";
512 case X86II::ArgF64: return "QWORD PTR";
513 case X86II::ArgF80: return "XWORD PTR";
517 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
518 const MRegisterInfo &RI = *TM.getRegisterInfo();
519 assert(isMem(MI, Op) && "Invalid memory reference!");
521 if (MI->getOperand(Op).isFrameIndex()) {
522 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
523 if (MI->getOperand(Op+3).getImmedValue())
524 O << " + " << MI->getOperand(Op+3).getImmedValue();
527 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
528 O << "[.CPI" << CurrentFnName << "_"
529 << MI->getOperand(Op).getConstantPoolIndex();
530 if (MI->getOperand(Op+3).getImmedValue())
531 O << " + " << MI->getOperand(Op+3).getImmedValue();
536 const MachineOperand &BaseReg = MI->getOperand(Op);
537 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
538 const MachineOperand &IndexReg = MI->getOperand(Op+2);
539 int DispVal = MI->getOperand(Op+3).getImmedValue();
542 bool NeedPlus = false;
543 if (BaseReg.getReg()) {
548 if (IndexReg.getReg()) {
549 if (NeedPlus) O << " + ";
551 O << ScaleVal << "*";
569 /// printMachineInstruction -- Print out a single X86 LLVM instruction
570 /// MI in Intel syntax to the current output stream.
572 void Printer::printMachineInstruction(const MachineInstr *MI) {
573 unsigned Opcode = MI->getOpcode();
574 const TargetInstrInfo &TII = TM.getInstrInfo();
575 const TargetInstrDescriptor &Desc = TII.get(Opcode);
576 const MRegisterInfo &RI = *TM.getRegisterInfo();
578 switch (Desc.TSFlags & X86II::FormMask) {
580 // Print pseudo-instructions as comments; either they should have been
581 // turned into real instructions by now, or they don't need to be
582 // seen by the assembler (e.g., IMPLICIT_USEs.)
584 if (Opcode == X86::PHI) {
585 printOp(MI->getOperand(0));
587 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
588 if (i != 1) O << ", ";
590 printOp(MI->getOperand(i));
592 printOp(MI->getOperand(i+1));
597 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
598 MI->getOperand(0).opIsDefAndUse())) {
599 printOp(MI->getOperand(0));
603 O << TII.getName(MI->getOpcode());
605 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
607 if (MI->getOperand(i).opIsDefOnly() ||
608 MI->getOperand(i).opIsDefAndUse()) O << "*";
609 printOp(MI->getOperand(i));
610 if (MI->getOperand(i).opIsDefOnly() ||
611 MI->getOperand(i).opIsDefAndUse()) O << "*";
618 // The accepted forms of Raw instructions are:
619 // 1. nop - No operand required
620 // 2. jmp foo - PC relative displacement operand
621 // 3. call bar - GlobalAddress Operand or External Symbol Operand
623 assert(MI->getNumOperands() == 0 ||
624 (MI->getNumOperands() == 1 &&
625 (MI->getOperand(0).isPCRelativeDisp() ||
626 MI->getOperand(0).isGlobalAddress() ||
627 MI->getOperand(0).isExternalSymbol())) &&
628 "Illegal raw instruction!");
629 O << TII.getName(MI->getOpcode()) << " ";
631 if (MI->getNumOperands() == 1) {
632 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
637 case X86II::AddRegFrm: {
638 // There are currently two forms of acceptable AddRegFrm instructions.
639 // Either the instruction JUST takes a single register (like inc, dec, etc),
640 // or it takes a register and an immediate of the same size as the register
641 // (move immediate f.e.). Note that this immediate value might be stored as
642 // an LLVM value, to represent, for example, loading the address of a global
643 // into a register. The initial register might be duplicated if this is a
644 // M_2_ADDR_REG instruction
646 assert(MI->getOperand(0).isRegister() &&
647 (MI->getNumOperands() == 1 ||
648 (MI->getNumOperands() == 2 &&
649 (MI->getOperand(1).getVRegValueOrNull() ||
650 MI->getOperand(1).isImmediate() ||
651 MI->getOperand(1).isRegister() ||
652 MI->getOperand(1).isGlobalAddress() ||
653 MI->getOperand(1).isExternalSymbol()))) &&
654 "Illegal form for AddRegFrm instruction!");
656 unsigned Reg = MI->getOperand(0).getReg();
658 O << TII.getName(MI->getOpCode()) << " ";
659 printOp(MI->getOperand(0));
660 if (MI->getNumOperands() == 2 &&
661 (!MI->getOperand(1).isRegister() ||
662 MI->getOperand(1).getVRegValueOrNull() ||
663 MI->getOperand(1).isGlobalAddress() ||
664 MI->getOperand(1).isExternalSymbol())) {
666 printOp(MI->getOperand(1));
668 if (Desc.TSFlags & X86II::PrintImplUses) {
669 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
670 O << ", " << RI.get(*p).Name;
676 case X86II::MRMDestReg: {
677 // There are two acceptable forms of MRMDestReg instructions, those with 2,
680 // 2 Operands: this is for things like mov that do not read a second input
682 // 3 Operands: in this form, the first two registers (the destination, and
683 // the first operand) should be the same, post register allocation. The 3rd
684 // operand is an additional input. This should be for things like add
687 // 4 Operands: This form is for instructions which are 3 operands forms, but
688 // have a constant argument as well.
690 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
691 assert(MI->getOperand(0).isRegister() &&
692 (MI->getNumOperands() == 2 ||
693 (isTwoAddr && MI->getOperand(1).isRegister() &&
694 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
695 (MI->getNumOperands() == 3 ||
696 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
697 && "Bad format for MRMDestReg!");
699 O << TII.getName(MI->getOpCode()) << " ";
700 printOp(MI->getOperand(0));
702 printOp(MI->getOperand(1+isTwoAddr));
703 if (MI->getNumOperands() == 4) {
705 printOp(MI->getOperand(3));
711 case X86II::MRMDestMem: {
712 // These instructions are the same as MRMDestReg, but instead of having a
713 // register reference for the mod/rm field, it's a memory reference.
715 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
716 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
718 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
719 printMemReference(MI, 0);
721 printOp(MI->getOperand(4));
726 case X86II::MRMSrcReg: {
727 // There is a two forms that are acceptable for MRMSrcReg instructions,
728 // those with 3 and 2 operands:
730 // 3 Operands: in this form, the last register (the second input) is the
731 // ModR/M input. The first two operands should be the same, post register
732 // allocation. This is for things like: add r32, r/m32
734 // 2 Operands: this is for things like mov that do not read a second input
736 assert(MI->getOperand(0).isRegister() &&
737 MI->getOperand(1).isRegister() &&
738 (MI->getNumOperands() == 2 ||
739 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
740 && "Bad format for MRMSrcReg!");
741 if (MI->getNumOperands() == 3 &&
742 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
745 O << TII.getName(MI->getOpCode()) << " ";
746 printOp(MI->getOperand(0));
748 printOp(MI->getOperand(MI->getNumOperands()-1));
753 case X86II::MRMSrcMem: {
754 // These instructions are the same as MRMSrcReg, but instead of having a
755 // register reference for the mod/rm field, it's a memory reference.
757 assert(MI->getOperand(0).isRegister() &&
758 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
759 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
761 && "Bad format for MRMDestReg!");
762 if (MI->getNumOperands() == 2+4 &&
763 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
766 O << TII.getName(MI->getOpCode()) << " ";
767 printOp(MI->getOperand(0));
768 O << ", " << sizePtr(Desc) << " ";
769 printMemReference(MI, MI->getNumOperands()-4);
774 case X86II::MRMS0r: case X86II::MRMS1r:
775 case X86II::MRMS2r: case X86II::MRMS3r:
776 case X86II::MRMS4r: case X86II::MRMS5r:
777 case X86II::MRMS6r: case X86II::MRMS7r: {
778 // In this form, the following are valid formats:
780 // 2. cmp reg, immediate
781 // 2. shl rdest, rinput <implicit CL or 1>
782 // 3. sbb rdest, rinput, immediate [rdest = rinput]
784 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
785 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
786 assert((MI->getNumOperands() != 2 ||
787 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
788 "Bad MRMSxR format!");
789 assert((MI->getNumOperands() < 3 ||
790 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
791 "Bad MRMSxR format!");
793 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
794 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
797 O << TII.getName(MI->getOpCode()) << " ";
798 printOp(MI->getOperand(0));
799 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
801 printOp(MI->getOperand(MI->getNumOperands()-1));
803 if (Desc.TSFlags & X86II::PrintImplUses) {
804 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
805 O << ", " << RI.get(*p).Name;
813 case X86II::MRMS0m: case X86II::MRMS1m:
814 case X86II::MRMS2m: case X86II::MRMS3m:
815 case X86II::MRMS4m: case X86II::MRMS5m:
816 case X86II::MRMS6m: case X86II::MRMS7m: {
817 // In this form, the following are valid formats:
819 // 2. cmp [m], immediate
820 // 2. shl [m], rinput <implicit CL or 1>
821 // 3. sbb [m], immediate
823 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
824 isMem(MI, 0) && "Bad MRMSxM format!");
825 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
826 "Bad MRMSxM format!");
827 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
828 // is misassembled by gas in intel_syntax mode as its 32-bit
829 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
830 // opcode bytes instead of the instruction.
831 if (MI->getOpCode() == X86::FSTPr80) {
832 if ((MI->getOperand(0).getReg() == X86::ESP)
833 && (MI->getOperand(1).getImmedValue() == 1)) {
834 int DispVal = MI->getOperand(3).getImmedValue();
835 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
836 unsigned int val = (unsigned int) DispVal;
837 O << ".byte 0xdb, 0xbc, 0x24\n\t";
838 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
839 } else { // 1 byte disp.
840 unsigned char val = (unsigned char) DispVal;
841 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
842 << std::dec << "\t# ";
846 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
847 // misassembled by gas in intel_syntax mode as its 32-bit
848 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
849 // opcode bytes instead of the instruction.
850 if (MI->getOpCode() == X86::FLDr80) {
851 if ((MI->getOperand(0).getReg() == X86::ESP)
852 && (MI->getOperand(1).getImmedValue() == 1)) {
853 int DispVal = MI->getOperand(3).getImmedValue();
854 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
855 unsigned int val = (unsigned int) DispVal;
856 O << ".byte 0xdb, 0xac, 0x24\n\t";
857 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
858 } else { // 1 byte disp.
859 unsigned char val = (unsigned char) DispVal;
860 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
861 << std::dec << "\t# ";
865 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
866 // invalid opcode, saying "64 bit operations are only supported in
867 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
868 // [...]", which is wrong. Workaround: Output the raw opcode bytes
869 // instead of the instruction.
870 if (MI->getOpCode() == X86::FILDr64) {
871 if ((MI->getOperand(0).getReg() == X86::ESP)
872 && (MI->getOperand(1).getImmedValue() == 1)) {
873 int DispVal = MI->getOperand(3).getImmedValue();
874 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
875 unsigned int val = (unsigned int) DispVal;
876 O << ".byte 0xdf, 0xac, 0x24\n\t";
877 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
878 } else { // 1 byte disp.
879 unsigned char val = (unsigned char) DispVal;
880 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
881 << std::dec << "\t# ";
885 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
886 // an invalid opcode, saying "64 bit operations are only
887 // supported in 64 bit modes." libopcodes disassembles it as
888 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
889 // "fistpll DWORD PTR " instead, which is what libopcodes is
891 if (MI->getOpCode() == X86::FISTPr64) {
892 O << "fistpll DWORD PTR ";
893 printMemReference(MI, 0);
894 if (MI->getNumOperands() == 5) {
896 printOp(MI->getOperand(4));
901 O << TII.getName(MI->getOpCode()) << " ";
902 O << sizePtr(Desc) << " ";
903 printMemReference(MI, 0);
904 if (MI->getNumOperands() == 5) {
906 printOp(MI->getOperand(4));
913 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
917 bool Printer::doInitialization(Module &M)
919 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
920 // with no % decorations on register names.
921 O << "\t.intel_syntax noprefix\n";
922 Mang = new Mangler(M);
923 return false; // success
926 static const Function *isConstantFunctionPointerRef(const Constant *C) {
927 if (const ConstantPointerRef *R = dyn_cast<ConstantPointerRef>(C))
928 if (const Function *F = dyn_cast<Function>(R->getValue()))
933 bool Printer::doFinalization(Module &M)
935 const TargetData &TD = TM.getTargetData();
936 // Print out module-level global variables here.
937 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
938 std::string name(Mang->getValueName(I));
939 if (I->hasInitializer()) {
940 Constant *C = I->getInitializer();
942 O << "\t.globl " << name << "\n";
943 O << "\t.type " << name << ",@object\n";
944 O << "\t.size " << name << ","
945 << (unsigned)TD.getTypeSize(I->getType()) << "\n";
946 O << "\t.align " << (unsigned)TD.getTypeAlignment(C->getType()) << "\n";
947 O << name << ":\t\t\t\t\t#";
948 // If this is a constant function pointer, we only print out the
949 // name of the function in the comment (because printing the
950 // function means calling AsmWriter to print the whole LLVM
951 // assembly, which would corrupt the X86 assembly output.)
952 // Otherwise we print out the whole llvm value as a comment.
953 if (const Function *F = isConstantFunctionPointerRef (C)) {
954 O << " %" << F->getName() << "()\n";
958 printConstantValueOnly (C);
960 O << "\t.globl " << name << "\n";
961 O << "\t.comm " << name << ", "
962 << (unsigned)TD.getTypeSize(I->getType()) << ", "
963 << (unsigned)TD.getTypeAlignment(I->getType()) << "\n";
967 return false; // success