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/Module.h"
13 #include "llvm/Type.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/Mangler.h"
22 #include "Support/StringExtras.h"
25 struct Printer : public MachineFunctionPass {
26 /// Output stream on which we're printing assembly code.
30 /// Target machine description which we query for reg. names, data
35 /// Name-mangler for global names.
39 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
41 /// We name each basic block in a Function with a unique number, so
42 /// that we can consistently refer to them later. This is cleared
43 /// at the beginning of each call to runOnMachineFunction().
45 typedef std::map<const Value *, unsigned> ValueMapTy;
46 ValueMapTy NumberForBB;
48 /// Cache of mangled name for current function. This is
49 /// recalculated at the beginning of each call to
50 /// runOnMachineFunction().
52 std::string CurrentFnName;
54 virtual const char *getPassName() const {
55 return "X86 Assembly Printer";
58 void checkImplUses (const TargetInstrDescriptor &Desc);
59 void printMachineInstruction(const MachineInstr *MI);
60 void printOp(const MachineOperand &MO,
61 bool elideOffsetKeyword = false);
62 void printMemReference(const MachineInstr *MI, unsigned Op);
63 void printConstantPool(MachineConstantPool *MCP);
64 bool runOnMachineFunction(MachineFunction &F);
65 std::string ConstantExprToString(const ConstantExpr* CE);
66 std::string valToExprString(const Value* V);
67 bool doInitialization(Module &M);
68 bool doFinalization(Module &M);
69 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
70 void printSingleConstantValue(const Constant* CV);
72 } // end of anonymous namespace
74 /// createX86CodePrinterPass - Returns a pass that prints the X86
75 /// assembly code for a MachineFunction to the given output stream,
76 /// using the given target machine description. This should work
77 /// regardless of whether the function is in SSA form.
79 Pass *createX86CodePrinterPass(std::ostream &o, TargetMachine &tm) {
80 return new Printer(o, tm);
83 /// valToExprString - Helper function for ConstantExprToString().
84 /// Appends result to argument string S.
86 std::string Printer::valToExprString(const Value* V) {
89 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
90 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
91 S += std::string(CB == ConstantBool::True ? "1" : "0");
92 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
93 S += itostr(CI->getValue());
94 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
95 S += utostr(CI->getValue());
96 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
97 S += ftostr(CFP->getValue());
98 else if (isa<ConstantPointerNull>(CV))
100 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
101 S += valToExprString(CPR->getValue());
102 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
103 S += ConstantExprToString(CE);
106 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
107 S += Mang->getValueName(GV);
113 assert(0 && "Cannot convert value to string");
114 S += "<illegal-value>";
119 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
120 /// and return this as a string.
122 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
123 const TargetData &TD = TM.getTargetData();
124 switch(CE->getOpcode()) {
125 case Instruction::GetElementPtr:
126 { // generate a symbolic expression for the byte address
127 const Value* ptrVal = CE->getOperand(0);
128 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
129 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
130 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
132 return valToExprString(ptrVal);
135 case Instruction::Cast:
136 // Support only non-converting or widening casts for now, that is,
137 // ones that do not involve a change in value. This assertion is
138 // not a complete check.
140 Constant *Op = CE->getOperand(0);
141 const Type *OpTy = Op->getType(), *Ty = CE->getType();
142 assert(((isa<PointerType>(OpTy)
143 && (Ty == Type::LongTy || Ty == Type::ULongTy))
144 || (isa<PointerType>(Ty)
145 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
146 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
147 && (OpTy->isLosslesslyConvertibleTo(Ty))))
148 && "FIXME: Don't yet support this kind of constant cast expr");
149 return "(" + valToExprString(Op) + ")";
152 case Instruction::Add:
153 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
154 + valToExprString(CE->getOperand(1)) + ")";
157 assert(0 && "Unsupported operator in ConstantExprToString()");
162 /// printSingleConstantValue - Print a single constant value.
165 Printer::printSingleConstantValue(const Constant* CV)
167 assert(CV->getType() != Type::VoidTy &&
168 CV->getType() != Type::TypeTy &&
169 CV->getType() != Type::LabelTy &&
170 "Unexpected type for Constant");
172 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
173 && "Aggregate types should be handled outside this function");
175 const Type *type = CV->getType();
177 switch(type->getPrimitiveID())
179 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
182 case Type::UShortTyID: case Type::ShortTyID:
185 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
188 case Type::ULongTyID: case Type::LongTyID:
191 case Type::FloatTyID:
194 case Type::DoubleTyID:
197 case Type::ArrayTyID:
198 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
199 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
202 assert (0 && "Can't handle printing this type of array");
205 assert (0 && "Can't handle printing this type of thing");
210 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
212 // Constant expression built from operators, constants, and
214 O << ConstantExprToString(CE) << "\n";
216 else if (type->isPrimitiveType())
218 if (type->isFloatingPoint()) {
219 // FP Constants are printed as integer constants to avoid losing
221 double Val = cast<ConstantFP>(CV)->getValue();
222 if (type == Type::FloatTy) {
223 float FVal = (float)Val;
224 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
225 O << *(unsigned int*)ProxyPtr;
226 } else if (type == Type::DoubleTy) {
227 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
228 O << *(uint64_t*)ProxyPtr;
230 assert(0 && "Unknown floating point type!");
233 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
235 WriteAsOperand(O, CV, false, false) << "\n";
238 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
240 // This is a constant address for a global variable or method.
241 // Use the name of the variable or method as the address value.
242 O << Mang->getValueName(CPR->getValue()) << "\n";
244 else if (isa<ConstantPointerNull>(CV))
246 // Null pointer value
251 assert(0 && "Unknown elementary type for constant");
255 /// isStringCompatible - Can we treat the specified array as a string?
256 /// Only if it is an array of ubytes or non-negative sbytes.
258 static bool isStringCompatible(const ConstantArray *CVA) {
259 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
260 if (ETy == Type::UByteTy) return true;
261 if (ETy != Type::SByteTy) return false;
263 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
264 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
270 /// toOctal - Convert the low order bits of X into an octal digit.
272 static inline char toOctal(int X) {
276 /// getAsCString - Return the specified array as a C compatible
277 /// string, only if the predicate isStringCompatible is true.
279 static std::string getAsCString(const ConstantArray *CVA) {
280 assert(isStringCompatible(CVA) && "Array is not string compatible!");
283 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
285 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
286 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
290 } else if (C == '\\') {
292 } else if (isprint(C)) {
296 case '\b': Result += "\\b"; break;
297 case '\f': Result += "\\f"; break;
298 case '\n': Result += "\\n"; break;
299 case '\r': Result += "\\r"; break;
300 case '\t': Result += "\\t"; break;
303 Result += toOctal(C >> 6);
304 Result += toOctal(C >> 3);
305 Result += toOctal(C >> 0);
314 // Print a constant value or values (it may be an aggregate).
315 // Uses printSingleConstantValue() to print each individual value.
317 Printer::printConstantValueOnly(const Constant* CV,
318 int numPadBytesAfter /* = 0 */)
320 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
321 const TargetData &TD = TM.getTargetData();
323 if (CVA && isStringCompatible(CVA))
324 { // print the string alone and return
325 O << "\t.string\t" << getAsCString(CVA) << "\n";
328 { // Not a string. Print the values in successive locations
329 const std::vector<Use> &constValues = CVA->getValues();
330 for (unsigned i=0; i < constValues.size(); i++)
331 printConstantValueOnly(cast<Constant>(constValues[i].get()));
333 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
334 { // Print the fields in successive locations. Pad to align if needed!
335 const StructLayout *cvsLayout =
336 TD.getStructLayout(CVS->getType());
337 const std::vector<Use>& constValues = CVS->getValues();
338 unsigned sizeSoFar = 0;
339 for (unsigned i=0, N = constValues.size(); i < N; i++)
341 const Constant* field = cast<Constant>(constValues[i].get());
343 // Check if padding is needed and insert one or more 0s.
344 unsigned fieldSize = TD.getTypeSize(field->getType());
345 int padSize = ((i == N-1? cvsLayout->StructSize
346 : cvsLayout->MemberOffsets[i+1])
347 - cvsLayout->MemberOffsets[i]) - fieldSize;
348 sizeSoFar += (fieldSize + padSize);
350 // Now print the actual field value
351 printConstantValueOnly(field, padSize);
353 assert(sizeSoFar == cvsLayout->StructSize &&
354 "Layout of constant struct may be incorrect!");
357 printSingleConstantValue(CV);
359 if (numPadBytesAfter) O << "\t.zero\t " << numPadBytesAfter << "\n";
362 /// printConstantPool - Print to the current output stream assembly
363 /// representations of the constants in the constant pool MCP. This is
364 /// used to print out constants which have been "spilled to memory" by
365 /// the code generator.
367 void Printer::printConstantPool(MachineConstantPool *MCP) {
368 const std::vector<Constant*> &CP = MCP->getConstants();
369 const TargetData &TD = TM.getTargetData();
371 if (CP.empty()) return;
373 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
374 O << "\t.section .rodata\n";
375 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
377 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
379 printConstantValueOnly (CP[i]);
383 /// runOnMachineFunction - This uses the printMachineInstruction()
384 /// method to print assembly for each instruction.
386 bool Printer::runOnMachineFunction(MachineFunction &MF) {
387 // BBNumber is used here so that a given Printer will never give two
388 // BBs the same name. (If you have a better way, please let me know!)
389 static unsigned BBNumber = 0;
392 // What's my mangled name?
393 CurrentFnName = Mang->getValueName(MF.getFunction());
395 // Print out constants referenced by the function
396 printConstantPool(MF.getConstantPool());
398 // Print out labels for the function.
400 O << "\t.align 16\n";
401 O << "\t.globl\t" << CurrentFnName << "\n";
402 O << "\t.type\t" << CurrentFnName << ", @function\n";
403 O << CurrentFnName << ":\n";
405 // Number each basic block so that we can consistently refer to them
406 // in PC-relative references.
408 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
410 NumberForBB[I->getBasicBlock()] = BBNumber++;
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" << NumberForBB[I->getBasicBlock()] << ":\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);
427 // We didn't modify anything.
431 static bool isScale(const MachineOperand &MO) {
432 return MO.isImmediate() &&
433 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
434 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
437 static bool isMem(const MachineInstr *MI, unsigned Op) {
438 if (MI->getOperand(Op).isFrameIndex()) return true;
439 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
440 return Op+4 <= MI->getNumOperands() &&
441 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
442 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
447 void Printer::printOp(const MachineOperand &MO,
448 bool elideOffsetKeyword /* = false */) {
449 const MRegisterInfo &RI = *TM.getRegisterInfo();
450 switch (MO.getType()) {
451 case MachineOperand::MO_VirtualRegister:
452 if (Value *V = MO.getVRegValueOrNull()) {
453 O << "<" << V->getName() << ">";
457 case MachineOperand::MO_MachineRegister:
458 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
459 // Bug Workaround: See note in Printer::doInitialization about %.
460 O << "%" << RI.get(MO.getReg()).Name;
462 O << "%reg" << MO.getReg();
465 case MachineOperand::MO_SignExtendedImmed:
466 case MachineOperand::MO_UnextendedImmed:
467 O << (int)MO.getImmedValue();
469 case MachineOperand::MO_PCRelativeDisp:
471 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
472 assert (i != NumberForBB.end()
473 && "Could not find a BB I previously put in the NumberForBB map!");
474 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
477 case MachineOperand::MO_GlobalAddress:
478 if (!elideOffsetKeyword)
480 O << Mang->getValueName(MO.getGlobal());
482 case MachineOperand::MO_ExternalSymbol:
483 O << MO.getSymbolName();
486 O << "<unknown operand type>"; return;
490 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
491 switch (Desc.TSFlags & X86II::ArgMask) {
492 default: assert(0 && "Unknown arg size!");
493 case X86II::Arg8: return "BYTE PTR";
494 case X86II::Arg16: return "WORD PTR";
495 case X86II::Arg32: return "DWORD PTR";
496 case X86II::Arg64: return "QWORD PTR";
497 case X86II::ArgF32: return "DWORD PTR";
498 case X86II::ArgF64: return "QWORD PTR";
499 case X86II::ArgF80: return "XWORD PTR";
503 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
504 assert(isMem(MI, Op) && "Invalid memory reference!");
506 if (MI->getOperand(Op).isFrameIndex()) {
507 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
508 if (MI->getOperand(Op+3).getImmedValue())
509 O << " + " << MI->getOperand(Op+3).getImmedValue();
512 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
513 O << "[.CPI" << CurrentFnName << "_"
514 << MI->getOperand(Op).getConstantPoolIndex();
515 if (MI->getOperand(Op+3).getImmedValue())
516 O << " + " << MI->getOperand(Op+3).getImmedValue();
521 const MachineOperand &BaseReg = MI->getOperand(Op);
522 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
523 const MachineOperand &IndexReg = MI->getOperand(Op+2);
524 int DispVal = MI->getOperand(Op+3).getImmedValue();
527 bool NeedPlus = false;
528 if (BaseReg.getReg()) {
533 if (IndexReg.getReg()) {
534 if (NeedPlus) O << " + ";
536 O << ScaleVal << "*";
554 /// checkImplUses - Emit the implicit-use registers for the
555 /// instruction described by DESC, if its PrintImplUses flag is set.
557 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
558 const MRegisterInfo &RI = *TM.getRegisterInfo();
559 if (Desc.TSFlags & X86II::PrintImplUses) {
560 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
561 // Bug Workaround: See note in Printer::doInitialization about %.
562 O << ", %" << RI.get(*p).Name;
567 /// printMachineInstruction -- Print out a single X86 LLVM instruction
568 /// MI in Intel syntax to the current output stream.
570 void Printer::printMachineInstruction(const MachineInstr *MI) {
571 unsigned Opcode = MI->getOpcode();
572 const TargetInstrInfo &TII = TM.getInstrInfo();
573 const TargetInstrDescriptor &Desc = TII.get(Opcode);
575 switch (Desc.TSFlags & X86II::FormMask) {
577 // Print pseudo-instructions as comments; either they should have been
578 // turned into real instructions by now, or they don't need to be
579 // seen by the assembler (e.g., IMPLICIT_USEs.)
581 if (Opcode == X86::PHI) {
582 printOp(MI->getOperand(0));
584 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
585 if (i != 1) O << ", ";
587 printOp(MI->getOperand(i));
589 printOp(MI->getOperand(i+1));
594 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
595 MI->getOperand(0).opIsDefAndUse())) {
596 printOp(MI->getOperand(0));
600 O << TII.getName(MI->getOpcode());
602 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
604 if (MI->getOperand(i).opIsDefOnly() ||
605 MI->getOperand(i).opIsDefAndUse()) O << "*";
606 printOp(MI->getOperand(i));
607 if (MI->getOperand(i).opIsDefOnly() ||
608 MI->getOperand(i).opIsDefAndUse()) O << "*";
615 // The accepted forms of Raw instructions are:
616 // 1. nop - No operand required
617 // 2. jmp foo - PC relative displacement operand
618 // 3. call bar - GlobalAddress Operand or External Symbol Operand
620 assert(MI->getNumOperands() == 0 ||
621 (MI->getNumOperands() == 1 &&
622 (MI->getOperand(0).isPCRelativeDisp() ||
623 MI->getOperand(0).isGlobalAddress() ||
624 MI->getOperand(0).isExternalSymbol())) &&
625 "Illegal raw instruction!");
626 O << TII.getName(MI->getOpcode()) << " ";
628 if (MI->getNumOperands() == 1) {
629 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
634 case X86II::AddRegFrm: {
635 // There are currently two forms of acceptable AddRegFrm instructions.
636 // Either the instruction JUST takes a single register (like inc, dec, etc),
637 // or it takes a register and an immediate of the same size as the register
638 // (move immediate f.e.). Note that this immediate value might be stored as
639 // an LLVM value, to represent, for example, loading the address of a global
640 // into a register. The initial register might be duplicated if this is a
641 // M_2_ADDR_REG instruction
643 assert(MI->getOperand(0).isRegister() &&
644 (MI->getNumOperands() == 1 ||
645 (MI->getNumOperands() == 2 &&
646 (MI->getOperand(1).getVRegValueOrNull() ||
647 MI->getOperand(1).isImmediate() ||
648 MI->getOperand(1).isRegister() ||
649 MI->getOperand(1).isGlobalAddress() ||
650 MI->getOperand(1).isExternalSymbol()))) &&
651 "Illegal form for AddRegFrm instruction!");
653 unsigned Reg = MI->getOperand(0).getReg();
655 O << TII.getName(MI->getOpCode()) << " ";
656 printOp(MI->getOperand(0));
657 if (MI->getNumOperands() == 2 &&
658 (!MI->getOperand(1).isRegister() ||
659 MI->getOperand(1).getVRegValueOrNull() ||
660 MI->getOperand(1).isGlobalAddress() ||
661 MI->getOperand(1).isExternalSymbol())) {
663 printOp(MI->getOperand(1));
669 case X86II::MRMDestReg: {
670 // There are two acceptable forms of MRMDestReg instructions, those with 2,
673 // 2 Operands: this is for things like mov that do not read a second input
675 // 3 Operands: in this form, the first two registers (the destination, and
676 // the first operand) should be the same, post register allocation. The 3rd
677 // operand is an additional input. This should be for things like add
680 // 4 Operands: This form is for instructions which are 3 operands forms, but
681 // have a constant argument as well.
683 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
684 assert(MI->getOperand(0).isRegister() &&
685 (MI->getNumOperands() == 2 ||
686 (isTwoAddr && MI->getOperand(1).isRegister() &&
687 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
688 (MI->getNumOperands() == 3 ||
689 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
690 && "Bad format for MRMDestReg!");
692 O << TII.getName(MI->getOpCode()) << " ";
693 printOp(MI->getOperand(0));
695 printOp(MI->getOperand(1+isTwoAddr));
696 if (MI->getNumOperands() == 4) {
698 printOp(MI->getOperand(3));
704 case X86II::MRMDestMem: {
705 // These instructions are the same as MRMDestReg, but instead of having a
706 // register reference for the mod/rm field, it's a memory reference.
708 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
709 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
711 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
712 printMemReference(MI, 0);
714 printOp(MI->getOperand(4));
719 case X86II::MRMSrcReg: {
720 // There is a two forms that are acceptable for MRMSrcReg instructions,
721 // those with 3 and 2 operands:
723 // 3 Operands: in this form, the last register (the second input) is the
724 // ModR/M input. The first two operands should be the same, post register
725 // allocation. This is for things like: add r32, r/m32
727 // 2 Operands: this is for things like mov that do not read a second input
729 assert(MI->getOperand(0).isRegister() &&
730 MI->getOperand(1).isRegister() &&
731 (MI->getNumOperands() == 2 ||
732 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
733 && "Bad format for MRMSrcReg!");
734 if (MI->getNumOperands() == 3 &&
735 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
738 O << TII.getName(MI->getOpCode()) << " ";
739 printOp(MI->getOperand(0));
741 printOp(MI->getOperand(MI->getNumOperands()-1));
746 case X86II::MRMSrcMem: {
747 // These instructions are the same as MRMSrcReg, but instead of having a
748 // register reference for the mod/rm field, it's a memory reference.
750 assert(MI->getOperand(0).isRegister() &&
751 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
752 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
754 && "Bad format for MRMDestReg!");
755 if (MI->getNumOperands() == 2+4 &&
756 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
759 O << TII.getName(MI->getOpCode()) << " ";
760 printOp(MI->getOperand(0));
761 O << ", " << sizePtr(Desc) << " ";
762 printMemReference(MI, MI->getNumOperands()-4);
767 case X86II::MRMS0r: case X86II::MRMS1r:
768 case X86II::MRMS2r: case X86II::MRMS3r:
769 case X86II::MRMS4r: case X86II::MRMS5r:
770 case X86II::MRMS6r: case X86II::MRMS7r: {
771 // In this form, the following are valid formats:
773 // 2. cmp reg, immediate
774 // 2. shl rdest, rinput <implicit CL or 1>
775 // 3. sbb rdest, rinput, immediate [rdest = rinput]
777 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
778 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
779 assert((MI->getNumOperands() != 2 ||
780 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
781 "Bad MRMSxR format!");
782 assert((MI->getNumOperands() < 3 ||
783 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
784 "Bad MRMSxR format!");
786 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
787 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
790 O << TII.getName(MI->getOpCode()) << " ";
791 printOp(MI->getOperand(0));
792 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
794 printOp(MI->getOperand(MI->getNumOperands()-1));
802 case X86II::MRMS0m: case X86II::MRMS1m:
803 case X86II::MRMS2m: case X86II::MRMS3m:
804 case X86II::MRMS4m: case X86II::MRMS5m:
805 case X86II::MRMS6m: case X86II::MRMS7m: {
806 // In this form, the following are valid formats:
808 // 2. cmp [m], immediate
809 // 2. shl [m], rinput <implicit CL or 1>
810 // 3. sbb [m], immediate
812 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
813 isMem(MI, 0) && "Bad MRMSxM format!");
814 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
815 "Bad MRMSxM format!");
816 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
817 // is misassembled by gas in intel_syntax mode as its 32-bit
818 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
819 // opcode bytes instead of the instruction.
820 if (MI->getOpCode() == X86::FSTPr80) {
821 if ((MI->getOperand(0).getReg() == X86::ESP)
822 && (MI->getOperand(1).getImmedValue() == 1)) {
823 int DispVal = MI->getOperand(3).getImmedValue();
824 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
825 unsigned int val = (unsigned int) DispVal;
826 O << ".byte 0xdb, 0xbc, 0x24\n\t";
827 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
828 } else { // 1 byte disp.
829 unsigned char val = (unsigned char) DispVal;
830 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
831 << std::dec << "\t# ";
835 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
836 // misassembled by gas in intel_syntax mode as its 32-bit
837 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
838 // opcode bytes instead of the instruction.
839 if (MI->getOpCode() == X86::FLDr80) {
840 if ((MI->getOperand(0).getReg() == X86::ESP)
841 && (MI->getOperand(1).getImmedValue() == 1)) {
842 int DispVal = MI->getOperand(3).getImmedValue();
843 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
844 unsigned int val = (unsigned int) DispVal;
845 O << ".byte 0xdb, 0xac, 0x24\n\t";
846 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
847 } else { // 1 byte disp.
848 unsigned char val = (unsigned char) DispVal;
849 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
850 << std::dec << "\t# ";
854 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
855 // invalid opcode, saying "64 bit operations are only supported in
856 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
857 // [...]", which is wrong. Workaround: Output the raw opcode bytes
858 // instead of the instruction.
859 if (MI->getOpCode() == X86::FILDr64) {
860 if ((MI->getOperand(0).getReg() == X86::ESP)
861 && (MI->getOperand(1).getImmedValue() == 1)) {
862 int DispVal = MI->getOperand(3).getImmedValue();
863 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
864 unsigned int val = (unsigned int) DispVal;
865 O << ".byte 0xdf, 0xac, 0x24\n\t";
866 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
867 } else { // 1 byte disp.
868 unsigned char val = (unsigned char) DispVal;
869 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
870 << std::dec << "\t# ";
874 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
875 // an invalid opcode, saying "64 bit operations are only
876 // supported in 64 bit modes." libopcodes disassembles it as
877 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
878 // "fistpll DWORD PTR " instead, which is what libopcodes is
880 if (MI->getOpCode() == X86::FISTPr64) {
881 O << "fistpll DWORD PTR ";
882 printMemReference(MI, 0);
883 if (MI->getNumOperands() == 5) {
885 printOp(MI->getOperand(4));
890 O << TII.getName(MI->getOpCode()) << " ";
891 O << sizePtr(Desc) << " ";
892 printMemReference(MI, 0);
893 if (MI->getNumOperands() == 5) {
895 printOp(MI->getOperand(4));
902 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
906 bool Printer::doInitialization(Module &M)
908 // Tell gas we are outputting Intel syntax (not AT&T syntax)
911 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol
912 // `Sp' in an instruction as a reference to the register named sp,
913 // and if you try to reference a symbol `Sp' (e.g. `mov ECX, OFFSET
914 // Sp') then it gets lowercased before being looked up in the symbol
915 // table. This creates spurious `undefined symbol' errors when
916 // linking. Workaround: Do not use `noprefix' mode, and decorate all
917 // register names with percent signs.
918 O << "\t.intel_syntax\n";
919 Mang = new Mangler(M);
920 return false; // success
923 static const Function *isConstantFunctionPointerRef(const Constant *C) {
924 if (const ConstantPointerRef *R = dyn_cast<ConstantPointerRef>(C))
925 if (const Function *F = dyn_cast<Function>(R->getValue()))
930 bool Printer::doFinalization(Module &M)
932 const TargetData &TD = TM.getTargetData();
933 // Print out module-level global variables here.
934 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
935 std::string name(Mang->getValueName(I));
936 if (I->hasInitializer()) {
937 Constant *C = I->getInitializer();
938 if (C->isNullValue()) {
939 O << "\n\n\t.comm " << name << "," << TD.getTypeSize(C->getType())
940 << "," << (unsigned)TD.getTypeAlignment(C->getType());
942 WriteAsOperand(O, I, true, true, &M);
945 O << "\n\n\t.data\n";
946 O << "\t.globl " << name << "\n";
947 O << "\t.type " << name << ",@object\n";
948 O << "\t.size " << name << "," << TD.getTypeSize(C->getType()) << "\n";
949 O << "\t.align " << (unsigned)TD.getTypeAlignment(C->getType()) << "\n";
950 O << name << ":\t\t\t\t# ";
951 WriteAsOperand(O, I, true, true, &M);
953 WriteAsOperand(O, C, false, false, &M);
955 printConstantValueOnly(C);
958 O << "\t.globl " << name << "\n";
959 O << "\t.comm " << name << ", "
960 << (unsigned)TD.getTypeSize(I->getType()) << ", "
961 << (unsigned)TD.getTypeAlignment(I->getType()) << "\n";
965 return false; // success