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 printMachineInstruction(const MachineInstr *MI);
59 void printOp(const MachineOperand &MO,
60 bool elideOffsetKeyword = false);
61 void printMemReference(const MachineInstr *MI, unsigned Op);
62 void printConstantPool(MachineConstantPool *MCP);
63 bool runOnMachineFunction(MachineFunction &F);
64 std::string ConstantExprToString(const ConstantExpr* CE);
65 std::string valToExprString(const Value* V);
66 bool doInitialization(Module &M);
67 bool doFinalization(Module &M);
68 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
69 void printSingleConstantValue(const Constant* CV);
71 } // end of anonymous namespace
73 /// createX86CodePrinterPass - Returns a pass that prints the X86
74 /// assembly code for a MachineFunction to the given output stream,
75 /// using the given target machine description. This should work
76 /// regardless of whether the function is in SSA form.
78 Pass *createX86CodePrinterPass(std::ostream &o, TargetMachine &tm) {
79 return new Printer(o, tm);
82 /// valToExprString - Helper function for ConstantExprToString().
83 /// Appends result to argument string S.
85 std::string Printer::valToExprString(const Value* V) {
88 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
89 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
90 S += std::string(CB == ConstantBool::True ? "1" : "0");
91 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
92 S += itostr(CI->getValue());
93 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
94 S += utostr(CI->getValue());
95 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
96 S += ftostr(CFP->getValue());
97 else if (isa<ConstantPointerNull>(CV))
99 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
100 S += valToExprString(CPR->getValue());
101 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
102 S += ConstantExprToString(CE);
105 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
106 S += Mang->getValueName(GV);
112 assert(0 && "Cannot convert value to string");
113 S += "<illegal-value>";
118 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
119 /// and return this as a string.
121 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
122 const TargetData &TD = TM.getTargetData();
123 switch(CE->getOpcode()) {
124 case Instruction::GetElementPtr:
125 { // generate a symbolic expression for the byte address
126 const Value* ptrVal = CE->getOperand(0);
127 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
128 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
129 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
131 return valToExprString(ptrVal);
134 case Instruction::Cast:
135 // Support only non-converting or widening casts for now, that is,
136 // ones that do not involve a change in value. This assertion is
137 // not a complete check.
139 Constant *Op = CE->getOperand(0);
140 const Type *OpTy = Op->getType(), *Ty = CE->getType();
141 assert(((isa<PointerType>(OpTy)
142 && (Ty == Type::LongTy || Ty == Type::ULongTy))
143 || (isa<PointerType>(Ty)
144 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
145 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
146 && (OpTy->isLosslesslyConvertibleTo(Ty))))
147 && "FIXME: Don't yet support this kind of constant cast expr");
148 return "(" + valToExprString(Op) + ")";
151 case Instruction::Add:
152 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
153 + valToExprString(CE->getOperand(1)) + ")";
156 assert(0 && "Unsupported operator in ConstantExprToString()");
161 /// printSingleConstantValue - Print a single constant value.
164 Printer::printSingleConstantValue(const Constant* CV)
166 assert(CV->getType() != Type::VoidTy &&
167 CV->getType() != Type::TypeTy &&
168 CV->getType() != Type::LabelTy &&
169 "Unexpected type for Constant");
171 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
172 && "Aggregate types should be handled outside this function");
174 const Type *type = CV->getType();
176 switch(type->getPrimitiveID())
178 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
181 case Type::UShortTyID: case Type::ShortTyID:
184 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
187 case Type::ULongTyID: case Type::LongTyID:
190 case Type::FloatTyID:
193 case Type::DoubleTyID:
196 case Type::ArrayTyID:
197 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
198 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
201 assert (0 && "Can't handle printing this type of array");
204 assert (0 && "Can't handle printing this type of thing");
209 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
211 // Constant expression built from operators, constants, and
213 O << ConstantExprToString(CE) << "\n";
215 else if (type->isPrimitiveType())
217 if (type->isFloatingPoint()) {
218 // FP Constants are printed as integer constants to avoid losing
220 double Val = cast<ConstantFP>(CV)->getValue();
221 if (type == Type::FloatTy) {
222 float FVal = (float)Val;
223 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
224 O << *(unsigned int*)ProxyPtr;
225 } else if (type == Type::DoubleTy) {
226 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
227 O << *(uint64_t*)ProxyPtr;
229 assert(0 && "Unknown floating point type!");
232 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
234 WriteAsOperand(O, CV, false, false) << "\n";
237 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
239 // This is a constant address for a global variable or method.
240 // Use the name of the variable or method as the address value.
241 O << Mang->getValueName(CPR->getValue()) << "\n";
243 else if (isa<ConstantPointerNull>(CV))
245 // Null pointer value
250 assert(0 && "Unknown elementary type for constant");
254 /// isStringCompatible - Can we treat the specified array as a string?
255 /// Only if it is an array of ubytes or non-negative sbytes.
257 static bool isStringCompatible(const ConstantArray *CVA) {
258 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
259 if (ETy == Type::UByteTy) return true;
260 if (ETy != Type::SByteTy) return false;
262 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
263 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
269 /// toOctal - Convert the low order bits of X into an octal digit.
271 static inline char toOctal(int X) {
275 /// getAsCString - Return the specified array as a C compatible
276 /// string, only if the predicate isStringCompatible is true.
278 static std::string getAsCString(const ConstantArray *CVA) {
279 assert(isStringCompatible(CVA) && "Array is not string compatible!");
282 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
284 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
285 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
289 } else if (C == '\\') {
291 } else if (isprint(C)) {
295 case '\b': Result += "\\b"; break;
296 case '\f': Result += "\\f"; break;
297 case '\n': Result += "\\n"; break;
298 case '\r': Result += "\\r"; break;
299 case '\t': Result += "\\t"; break;
302 Result += toOctal(C >> 6);
303 Result += toOctal(C >> 3);
304 Result += toOctal(C >> 0);
313 // Print a constant value or values (it may be an aggregate).
314 // Uses printSingleConstantValue() to print each individual value.
316 Printer::printConstantValueOnly(const Constant* CV,
317 int numPadBytesAfter /* = 0 */)
319 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
320 const TargetData &TD = TM.getTargetData();
322 if (CVA && isStringCompatible(CVA))
323 { // print the string alone and return
324 O << "\t.string\t" << getAsCString(CVA) << "\n";
327 { // Not a string. Print the values in successive locations
328 const std::vector<Use> &constValues = CVA->getValues();
329 for (unsigned i=0; i < constValues.size(); i++)
330 printConstantValueOnly(cast<Constant>(constValues[i].get()));
332 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
333 { // Print the fields in successive locations. Pad to align if needed!
334 const StructLayout *cvsLayout =
335 TD.getStructLayout(CVS->getType());
336 const std::vector<Use>& constValues = CVS->getValues();
337 unsigned sizeSoFar = 0;
338 for (unsigned i=0, N = constValues.size(); i < N; i++)
340 const Constant* field = cast<Constant>(constValues[i].get());
342 // Check if padding is needed and insert one or more 0s.
343 unsigned fieldSize = TD.getTypeSize(field->getType());
344 int padSize = ((i == N-1? cvsLayout->StructSize
345 : cvsLayout->MemberOffsets[i+1])
346 - cvsLayout->MemberOffsets[i]) - fieldSize;
347 sizeSoFar += (fieldSize + padSize);
349 // Now print the actual field value
350 printConstantValueOnly(field, padSize);
352 assert(sizeSoFar == cvsLayout->StructSize &&
353 "Layout of constant struct may be incorrect!");
356 printSingleConstantValue(CV);
358 if (numPadBytesAfter) O << "\t.zero\t " << numPadBytesAfter << "\n";
361 /// printConstantPool - Print to the current output stream assembly
362 /// representations of the constants in the constant pool MCP. This is
363 /// used to print out constants which have been "spilled to memory" by
364 /// the code generator.
366 void Printer::printConstantPool(MachineConstantPool *MCP) {
367 const std::vector<Constant*> &CP = MCP->getConstants();
368 const TargetData &TD = TM.getTargetData();
370 if (CP.empty()) return;
372 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
373 O << "\t.section .rodata\n";
374 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
376 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
378 printConstantValueOnly (CP[i]);
382 /// runOnMachineFunction - This uses the printMachineInstruction()
383 /// method to print assembly for each instruction.
385 bool Printer::runOnMachineFunction(MachineFunction &MF) {
386 // BBNumber is used here so that a given Printer will never give two
387 // BBs the same name. (If you have a better way, please let me know!)
388 static unsigned BBNumber = 0;
391 // What's my mangled name?
392 CurrentFnName = Mang->getValueName(MF.getFunction());
394 // Print out constants referenced by the function
395 printConstantPool(MF.getConstantPool());
397 // Print out labels for the function.
399 O << "\t.align 16\n";
400 O << "\t.globl\t" << CurrentFnName << "\n";
401 O << "\t.type\t" << CurrentFnName << ", @function\n";
402 O << CurrentFnName << ":\n";
404 // Number each basic block so that we can consistently refer to them
405 // in PC-relative references.
407 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
409 NumberForBB[I->getBasicBlock()] = BBNumber++;
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" << NumberForBB[I->getBasicBlock()] << ":\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);
426 // We didn't modify anything.
430 static bool isScale(const MachineOperand &MO) {
431 return MO.isImmediate() &&
432 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
433 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
436 static bool isMem(const MachineInstr *MI, unsigned Op) {
437 if (MI->getOperand(Op).isFrameIndex()) return true;
438 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
439 return Op+4 <= MI->getNumOperands() &&
440 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
441 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
444 void Printer::printOp(const MachineOperand &MO,
445 bool elideOffsetKeyword /* = false */) {
446 const MRegisterInfo &RI = *TM.getRegisterInfo();
447 switch (MO.getType()) {
448 case MachineOperand::MO_VirtualRegister:
449 if (Value *V = MO.getVRegValueOrNull()) {
450 O << "<" << V->getName() << ">";
454 case MachineOperand::MO_MachineRegister:
455 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
456 O << RI.get(MO.getReg()).Name;
458 O << "%reg" << MO.getReg();
461 case MachineOperand::MO_SignExtendedImmed:
462 case MachineOperand::MO_UnextendedImmed:
463 O << (int)MO.getImmedValue();
465 case MachineOperand::MO_PCRelativeDisp:
467 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
468 assert (i != NumberForBB.end()
469 && "Could not find a BB I previously put in the NumberForBB map!");
470 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
473 case MachineOperand::MO_GlobalAddress:
474 if (!elideOffsetKeyword)
476 O << Mang->getValueName(MO.getGlobal());
478 case MachineOperand::MO_ExternalSymbol:
479 O << MO.getSymbolName();
482 O << "<unknown operand type>"; return;
486 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
487 switch (Desc.TSFlags & X86II::ArgMask) {
488 default: assert(0 && "Unknown arg size!");
489 case X86II::Arg8: return "BYTE PTR";
490 case X86II::Arg16: return "WORD PTR";
491 case X86II::Arg32: return "DWORD PTR";
492 case X86II::Arg64: return "QWORD PTR";
493 case X86II::ArgF32: return "DWORD PTR";
494 case X86II::ArgF64: return "QWORD PTR";
495 case X86II::ArgF80: return "XWORD PTR";
499 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
500 const MRegisterInfo &RI = *TM.getRegisterInfo();
501 assert(isMem(MI, Op) && "Invalid memory reference!");
503 if (MI->getOperand(Op).isFrameIndex()) {
504 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
505 if (MI->getOperand(Op+3).getImmedValue())
506 O << " + " << MI->getOperand(Op+3).getImmedValue();
509 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
510 O << "[.CPI" << CurrentFnName << "_"
511 << MI->getOperand(Op).getConstantPoolIndex();
512 if (MI->getOperand(Op+3).getImmedValue())
513 O << " + " << MI->getOperand(Op+3).getImmedValue();
518 const MachineOperand &BaseReg = MI->getOperand(Op);
519 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
520 const MachineOperand &IndexReg = MI->getOperand(Op+2);
521 int DispVal = MI->getOperand(Op+3).getImmedValue();
524 bool NeedPlus = false;
525 if (BaseReg.getReg()) {
530 if (IndexReg.getReg()) {
531 if (NeedPlus) O << " + ";
533 O << ScaleVal << "*";
551 /// printMachineInstruction -- Print out a single X86 LLVM instruction
552 /// MI in Intel syntax to the current output stream.
554 void Printer::printMachineInstruction(const MachineInstr *MI) {
555 unsigned Opcode = MI->getOpcode();
556 const TargetInstrInfo &TII = TM.getInstrInfo();
557 const TargetInstrDescriptor &Desc = TII.get(Opcode);
558 const MRegisterInfo &RI = *TM.getRegisterInfo();
560 switch (Desc.TSFlags & X86II::FormMask) {
562 // Print pseudo-instructions as comments; either they should have been
563 // turned into real instructions by now, or they don't need to be
564 // seen by the assembler (e.g., IMPLICIT_USEs.)
566 if (Opcode == X86::PHI) {
567 printOp(MI->getOperand(0));
569 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
570 if (i != 1) O << ", ";
572 printOp(MI->getOperand(i));
574 printOp(MI->getOperand(i+1));
579 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
580 MI->getOperand(0).opIsDefAndUse())) {
581 printOp(MI->getOperand(0));
585 O << TII.getName(MI->getOpcode());
587 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
589 if (MI->getOperand(i).opIsDefOnly() ||
590 MI->getOperand(i).opIsDefAndUse()) O << "*";
591 printOp(MI->getOperand(i));
592 if (MI->getOperand(i).opIsDefOnly() ||
593 MI->getOperand(i).opIsDefAndUse()) O << "*";
600 // The accepted forms of Raw instructions are:
601 // 1. nop - No operand required
602 // 2. jmp foo - PC relative displacement operand
603 // 3. call bar - GlobalAddress Operand or External Symbol Operand
605 assert(MI->getNumOperands() == 0 ||
606 (MI->getNumOperands() == 1 &&
607 (MI->getOperand(0).isPCRelativeDisp() ||
608 MI->getOperand(0).isGlobalAddress() ||
609 MI->getOperand(0).isExternalSymbol())) &&
610 "Illegal raw instruction!");
611 O << TII.getName(MI->getOpcode()) << " ";
613 if (MI->getNumOperands() == 1) {
614 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
619 case X86II::AddRegFrm: {
620 // There are currently two forms of acceptable AddRegFrm instructions.
621 // Either the instruction JUST takes a single register (like inc, dec, etc),
622 // or it takes a register and an immediate of the same size as the register
623 // (move immediate f.e.). Note that this immediate value might be stored as
624 // an LLVM value, to represent, for example, loading the address of a global
625 // into a register. The initial register might be duplicated if this is a
626 // M_2_ADDR_REG instruction
628 assert(MI->getOperand(0).isRegister() &&
629 (MI->getNumOperands() == 1 ||
630 (MI->getNumOperands() == 2 &&
631 (MI->getOperand(1).getVRegValueOrNull() ||
632 MI->getOperand(1).isImmediate() ||
633 MI->getOperand(1).isRegister() ||
634 MI->getOperand(1).isGlobalAddress() ||
635 MI->getOperand(1).isExternalSymbol()))) &&
636 "Illegal form for AddRegFrm instruction!");
638 unsigned Reg = MI->getOperand(0).getReg();
640 O << TII.getName(MI->getOpCode()) << " ";
641 printOp(MI->getOperand(0));
642 if (MI->getNumOperands() == 2 &&
643 (!MI->getOperand(1).isRegister() ||
644 MI->getOperand(1).getVRegValueOrNull() ||
645 MI->getOperand(1).isGlobalAddress() ||
646 MI->getOperand(1).isExternalSymbol())) {
648 printOp(MI->getOperand(1));
650 if (Desc.TSFlags & X86II::PrintImplUses) {
651 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
652 O << ", " << RI.get(*p).Name;
658 case X86II::MRMDestReg: {
659 // There are two acceptable forms of MRMDestReg instructions, those with 2,
662 // 2 Operands: this is for things like mov that do not read a second input
664 // 3 Operands: in this form, the first two registers (the destination, and
665 // the first operand) should be the same, post register allocation. The 3rd
666 // operand is an additional input. This should be for things like add
669 // 4 Operands: This form is for instructions which are 3 operands forms, but
670 // have a constant argument as well.
672 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
673 assert(MI->getOperand(0).isRegister() &&
674 (MI->getNumOperands() == 2 ||
675 (isTwoAddr && MI->getOperand(1).isRegister() &&
676 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
677 (MI->getNumOperands() == 3 ||
678 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
679 && "Bad format for MRMDestReg!");
681 O << TII.getName(MI->getOpCode()) << " ";
682 printOp(MI->getOperand(0));
684 printOp(MI->getOperand(1+isTwoAddr));
685 if (MI->getNumOperands() == 4) {
687 printOp(MI->getOperand(3));
693 case X86II::MRMDestMem: {
694 // These instructions are the same as MRMDestReg, but instead of having a
695 // register reference for the mod/rm field, it's a memory reference.
697 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
698 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
700 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
701 printMemReference(MI, 0);
703 printOp(MI->getOperand(4));
708 case X86II::MRMSrcReg: {
709 // There is a two forms that are acceptable for MRMSrcReg instructions,
710 // those with 3 and 2 operands:
712 // 3 Operands: in this form, the last register (the second input) is the
713 // ModR/M input. The first two operands should be the same, post register
714 // allocation. This is for things like: add r32, r/m32
716 // 2 Operands: this is for things like mov that do not read a second input
718 assert(MI->getOperand(0).isRegister() &&
719 MI->getOperand(1).isRegister() &&
720 (MI->getNumOperands() == 2 ||
721 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
722 && "Bad format for MRMSrcReg!");
723 if (MI->getNumOperands() == 3 &&
724 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
727 O << TII.getName(MI->getOpCode()) << " ";
728 printOp(MI->getOperand(0));
730 printOp(MI->getOperand(MI->getNumOperands()-1));
735 case X86II::MRMSrcMem: {
736 // These instructions are the same as MRMSrcReg, but instead of having a
737 // register reference for the mod/rm field, it's a memory reference.
739 assert(MI->getOperand(0).isRegister() &&
740 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
741 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
743 && "Bad format for MRMDestReg!");
744 if (MI->getNumOperands() == 2+4 &&
745 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
748 O << TII.getName(MI->getOpCode()) << " ";
749 printOp(MI->getOperand(0));
750 O << ", " << sizePtr(Desc) << " ";
751 printMemReference(MI, MI->getNumOperands()-4);
756 case X86II::MRMS0r: case X86II::MRMS1r:
757 case X86II::MRMS2r: case X86II::MRMS3r:
758 case X86II::MRMS4r: case X86II::MRMS5r:
759 case X86II::MRMS6r: case X86II::MRMS7r: {
760 // In this form, the following are valid formats:
762 // 2. cmp reg, immediate
763 // 2. shl rdest, rinput <implicit CL or 1>
764 // 3. sbb rdest, rinput, immediate [rdest = rinput]
766 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
767 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
768 assert((MI->getNumOperands() != 2 ||
769 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
770 "Bad MRMSxR format!");
771 assert((MI->getNumOperands() < 3 ||
772 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
773 "Bad MRMSxR format!");
775 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
776 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
779 O << TII.getName(MI->getOpCode()) << " ";
780 printOp(MI->getOperand(0));
781 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
783 printOp(MI->getOperand(MI->getNumOperands()-1));
785 if (Desc.TSFlags & X86II::PrintImplUses) {
786 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
787 O << ", " << RI.get(*p).Name;
795 case X86II::MRMS0m: case X86II::MRMS1m:
796 case X86II::MRMS2m: case X86II::MRMS3m:
797 case X86II::MRMS4m: case X86II::MRMS5m:
798 case X86II::MRMS6m: case X86II::MRMS7m: {
799 // In this form, the following are valid formats:
801 // 2. cmp [m], immediate
802 // 2. shl [m], rinput <implicit CL or 1>
803 // 3. sbb [m], immediate
805 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
806 isMem(MI, 0) && "Bad MRMSxM format!");
807 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
808 "Bad MRMSxM format!");
809 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
810 // is misassembled by gas in intel_syntax mode as its 32-bit
811 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
812 // opcode bytes instead of the instruction.
813 if (MI->getOpCode() == X86::FSTPr80) {
814 if ((MI->getOperand(0).getReg() == X86::ESP)
815 && (MI->getOperand(1).getImmedValue() == 1)) {
816 int DispVal = MI->getOperand(3).getImmedValue();
817 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
818 unsigned int val = (unsigned int) DispVal;
819 O << ".byte 0xdb, 0xbc, 0x24\n\t";
820 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
821 } else { // 1 byte disp.
822 unsigned char val = (unsigned char) DispVal;
823 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
824 << std::dec << "\t# ";
828 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
829 // misassembled by gas in intel_syntax mode as its 32-bit
830 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
831 // opcode bytes instead of the instruction.
832 if (MI->getOpCode() == X86::FLDr80) {
833 if ((MI->getOperand(0).getReg() == X86::ESP)
834 && (MI->getOperand(1).getImmedValue() == 1)) {
835 int DispVal = MI->getOperand(3).getImmedValue();
836 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
837 unsigned int val = (unsigned int) DispVal;
838 O << ".byte 0xdb, 0xac, 0x24\n\t";
839 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
840 } else { // 1 byte disp.
841 unsigned char val = (unsigned char) DispVal;
842 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
843 << std::dec << "\t# ";
847 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
848 // invalid opcode, saying "64 bit operations are only supported in
849 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
850 // [...]", which is wrong. Workaround: Output the raw opcode bytes
851 // instead of the instruction.
852 if (MI->getOpCode() == X86::FILDr64) {
853 if ((MI->getOperand(0).getReg() == X86::ESP)
854 && (MI->getOperand(1).getImmedValue() == 1)) {
855 int DispVal = MI->getOperand(3).getImmedValue();
856 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
857 unsigned int val = (unsigned int) DispVal;
858 O << ".byte 0xdf, 0xac, 0x24\n\t";
859 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
860 } else { // 1 byte disp.
861 unsigned char val = (unsigned char) DispVal;
862 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
863 << std::dec << "\t# ";
867 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
868 // an invalid opcode, saying "64 bit operations are only
869 // supported in 64 bit modes." libopcodes disassembles it as
870 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
871 // "fistpll DWORD PTR " instead, which is what libopcodes is
873 if (MI->getOpCode() == X86::FISTPr64) {
874 O << "fistpll DWORD PTR ";
875 printMemReference(MI, 0);
876 if (MI->getNumOperands() == 5) {
878 printOp(MI->getOperand(4));
883 O << TII.getName(MI->getOpCode()) << " ";
884 O << sizePtr(Desc) << " ";
885 printMemReference(MI, 0);
886 if (MI->getNumOperands() == 5) {
888 printOp(MI->getOperand(4));
895 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
899 bool Printer::doInitialization(Module &M)
901 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
902 // with no % decorations on register names.
903 O << "\t.intel_syntax noprefix\n";
904 Mang = new Mangler(M);
905 return false; // success
908 static const Function *isConstantFunctionPointerRef(const Constant *C) {
909 if (const ConstantPointerRef *R = dyn_cast<ConstantPointerRef>(C))
910 if (const Function *F = dyn_cast<Function>(R->getValue()))
915 bool Printer::doFinalization(Module &M)
917 const TargetData &TD = TM.getTargetData();
918 // Print out module-level global variables here.
919 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
920 std::string name(Mang->getValueName(I));
921 if (I->hasInitializer()) {
922 Constant *C = I->getInitializer();
923 if (C->isNullValue()) {
924 O << "\n\n\t.comm " << name << "," << TD.getTypeSize(C->getType())
925 << "," << (unsigned)TD.getTypeAlignment(C->getType());
927 WriteAsOperand(O, I, true, true, &M);
930 O << "\n\n\t.data\n";
931 O << "\t.globl " << name << "\n";
932 O << "\t.type " << name << ",@object\n";
933 O << "\t.size " << name << "," << TD.getTypeSize(C->getType()) << "\n";
934 O << "\t.align " << (unsigned)TD.getTypeAlignment(C->getType()) << "\n";
935 O << name << ":\t\t\t\t# ";
936 WriteAsOperand(O, I, true, true, &M);
938 WriteAsOperand(O, C, false, false, &M);
940 printConstantValueOnly(C);
943 O << "\t.globl " << name << "\n";
944 O << "\t.comm " << name << ", "
945 << (unsigned)TD.getTypeSize(I->getType()) << ", "
946 << (unsigned)TD.getTypeAlignment(I->getType()) << "\n";
950 return false; // success