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 -print-machineinstrs' 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"
23 #include "Support/CommandLine.h"
26 // FIXME: This should be automatically picked up by autoconf from the C
28 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
29 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
31 struct Printer : public MachineFunctionPass {
32 /// Output stream on which we're printing assembly code.
36 /// Target machine description which we query for reg. names, data
41 /// Name-mangler for global names.
45 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
47 /// We name each basic block in a Function with a unique number, so
48 /// that we can consistently refer to them later. This is cleared
49 /// at the beginning of each call to runOnMachineFunction().
51 typedef std::map<const Value *, unsigned> ValueMapTy;
52 ValueMapTy NumberForBB;
54 /// Cache of mangled name for current function. This is
55 /// recalculated at the beginning of each call to
56 /// runOnMachineFunction().
58 std::string CurrentFnName;
60 virtual const char *getPassName() const {
61 return "X86 Assembly Printer";
64 void checkImplUses (const TargetInstrDescriptor &Desc);
65 void printMachineInstruction(const MachineInstr *MI);
66 void printOp(const MachineOperand &MO,
67 bool elideOffsetKeyword = false);
68 void printMemReference(const MachineInstr *MI, unsigned Op);
69 void printConstantPool(MachineConstantPool *MCP);
70 bool runOnMachineFunction(MachineFunction &F);
71 std::string ConstantExprToString(const ConstantExpr* CE);
72 std::string valToExprString(const Value* V);
73 bool doInitialization(Module &M);
74 bool doFinalization(Module &M);
75 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
76 void printSingleConstantValue(const Constant* CV);
78 } // end of anonymous namespace
80 /// createX86CodePrinterPass - Returns a pass that prints the X86
81 /// assembly code for a MachineFunction to the given output stream,
82 /// using the given target machine description. This should work
83 /// regardless of whether the function is in SSA form.
85 Pass *createX86CodePrinterPass(std::ostream &o, TargetMachine &tm) {
86 return new Printer(o, tm);
89 /// valToExprString - Helper function for ConstantExprToString().
90 /// Appends result to argument string S.
92 std::string Printer::valToExprString(const Value* V) {
95 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
96 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
97 S += std::string(CB == ConstantBool::True ? "1" : "0");
98 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
99 S += itostr(CI->getValue());
100 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
101 S += utostr(CI->getValue());
102 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
103 S += ftostr(CFP->getValue());
104 else if (isa<ConstantPointerNull>(CV))
106 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
107 S += valToExprString(CPR->getValue());
108 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
109 S += ConstantExprToString(CE);
112 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
113 S += Mang->getValueName(GV);
119 assert(0 && "Cannot convert value to string");
120 S += "<illegal-value>";
125 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
126 /// and return this as a string.
128 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
129 const TargetData &TD = TM.getTargetData();
130 switch(CE->getOpcode()) {
131 case Instruction::GetElementPtr:
132 { // generate a symbolic expression for the byte address
133 const Value* ptrVal = CE->getOperand(0);
134 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
135 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
136 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
138 return valToExprString(ptrVal);
141 case Instruction::Cast:
142 // Support only non-converting or widening casts for now, that is,
143 // ones that do not involve a change in value. This assertion is
144 // not a complete check.
146 Constant *Op = CE->getOperand(0);
147 const Type *OpTy = Op->getType(), *Ty = CE->getType();
148 assert(((isa<PointerType>(OpTy)
149 && (Ty == Type::LongTy || Ty == Type::ULongTy))
150 || (isa<PointerType>(Ty)
151 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
152 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
153 && (OpTy->isLosslesslyConvertibleTo(Ty))))
154 && "FIXME: Don't yet support this kind of constant cast expr");
155 return "(" + valToExprString(Op) + ")";
158 case Instruction::Add:
159 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
160 + valToExprString(CE->getOperand(1)) + ")";
163 assert(0 && "Unsupported operator in ConstantExprToString()");
168 /// printSingleConstantValue - Print a single constant value.
171 Printer::printSingleConstantValue(const Constant* CV)
173 assert(CV->getType() != Type::VoidTy &&
174 CV->getType() != Type::TypeTy &&
175 CV->getType() != Type::LabelTy &&
176 "Unexpected type for Constant");
178 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
179 && "Aggregate types should be handled outside this function");
181 const Type *type = CV->getType();
183 switch(type->getPrimitiveID())
185 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
188 case Type::UShortTyID: case Type::ShortTyID:
191 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
194 case Type::ULongTyID: case Type::LongTyID:
197 case Type::FloatTyID:
200 case Type::DoubleTyID:
203 case Type::ArrayTyID:
204 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
205 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
208 assert (0 && "Can't handle printing this type of array");
211 assert (0 && "Can't handle printing this type of thing");
216 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
218 // Constant expression built from operators, constants, and
220 O << ConstantExprToString(CE) << "\n";
222 else if (type->isPrimitiveType())
224 if (type->isFloatingPoint()) {
225 // FP Constants are printed as integer constants to avoid losing
227 double Val = cast<ConstantFP>(CV)->getValue();
228 if (type == Type::FloatTy) {
229 float FVal = (float)Val;
230 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
231 O << *(unsigned int*)ProxyPtr;
232 } else if (type == Type::DoubleTy) {
233 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
234 O << *(uint64_t*)ProxyPtr;
236 assert(0 && "Unknown floating point type!");
239 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
241 WriteAsOperand(O, CV, false, false) << "\n";
244 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
246 // This is a constant address for a global variable or method.
247 // Use the name of the variable or method as the address value.
248 O << Mang->getValueName(CPR->getValue()) << "\n";
250 else if (isa<ConstantPointerNull>(CV))
252 // Null pointer value
257 assert(0 && "Unknown elementary type for constant");
261 /// isStringCompatible - Can we treat the specified array as a string?
262 /// Only if it is an array of ubytes or non-negative sbytes.
264 static bool isStringCompatible(const ConstantArray *CVA) {
265 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
266 if (ETy == Type::UByteTy) return true;
267 if (ETy != Type::SByteTy) return false;
269 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
270 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
276 /// toOctal - Convert the low order bits of X into an octal digit.
278 static inline char toOctal(int X) {
282 /// getAsCString - Return the specified array as a C compatible
283 /// string, only if the predicate isStringCompatible is true.
285 static std::string getAsCString(const ConstantArray *CVA) {
286 assert(isStringCompatible(CVA) && "Array is not string compatible!");
289 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
291 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
292 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
296 } else if (C == '\\') {
298 } else if (isprint(C)) {
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;
309 Result += toOctal(C >> 6);
310 Result += toOctal(C >> 3);
311 Result += toOctal(C >> 0);
320 // Print a constant value or values (it may be an aggregate).
321 // Uses printSingleConstantValue() to print each individual value.
323 Printer::printConstantValueOnly(const Constant* CV,
324 int numPadBytesAfter /* = 0 */)
326 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
327 const TargetData &TD = TM.getTargetData();
329 if (CVA && isStringCompatible(CVA))
330 { // print the string alone and return
331 O << "\t.string\t" << getAsCString(CVA) << "\n";
334 { // Not a string. Print the values in successive locations
335 const std::vector<Use> &constValues = CVA->getValues();
336 for (unsigned i=0; i < constValues.size(); i++)
337 printConstantValueOnly(cast<Constant>(constValues[i].get()));
339 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
340 { // Print the fields in successive locations. Pad to align if needed!
341 const StructLayout *cvsLayout =
342 TD.getStructLayout(CVS->getType());
343 const std::vector<Use>& constValues = CVS->getValues();
344 unsigned sizeSoFar = 0;
345 for (unsigned i=0, N = constValues.size(); i < N; i++)
347 const Constant* field = cast<Constant>(constValues[i].get());
349 // Check if padding is needed and insert one or more 0s.
350 unsigned fieldSize = TD.getTypeSize(field->getType());
351 int padSize = ((i == N-1? cvsLayout->StructSize
352 : cvsLayout->MemberOffsets[i+1])
353 - cvsLayout->MemberOffsets[i]) - fieldSize;
354 sizeSoFar += (fieldSize + padSize);
356 // Now print the actual field value
357 printConstantValueOnly(field, padSize);
359 assert(sizeSoFar == cvsLayout->StructSize &&
360 "Layout of constant struct may be incorrect!");
363 printSingleConstantValue(CV);
365 if (numPadBytesAfter) O << "\t.zero\t " << numPadBytesAfter << "\n";
368 /// printConstantPool - Print to the current output stream assembly
369 /// representations of the constants in the constant pool MCP. This is
370 /// used to print out constants which have been "spilled to memory" by
371 /// the code generator.
373 void Printer::printConstantPool(MachineConstantPool *MCP) {
374 const std::vector<Constant*> &CP = MCP->getConstants();
375 const TargetData &TD = TM.getTargetData();
377 if (CP.empty()) return;
379 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
380 O << "\t.section .rodata\n";
381 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
383 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
385 printConstantValueOnly (CP[i]);
389 /// runOnMachineFunction - This uses the printMachineInstruction()
390 /// method to print assembly for each instruction.
392 bool Printer::runOnMachineFunction(MachineFunction &MF) {
393 // BBNumber is used here so that a given Printer will never give two
394 // BBs the same name. (If you have a better way, please let me know!)
395 static unsigned BBNumber = 0;
398 // What's my mangled name?
399 CurrentFnName = Mang->getValueName(MF.getFunction());
401 // Print out constants referenced by the function
402 printConstantPool(MF.getConstantPool());
404 // Print out labels for the function.
406 O << "\t.align 16\n";
407 O << "\t.globl\t" << CurrentFnName << "\n";
409 O << "\t.type\t" << CurrentFnName << ", @function\n";
410 O << CurrentFnName << ":\n";
412 // Number each basic block so that we can consistently refer to them
413 // in PC-relative references.
415 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
417 NumberForBB[I->getBasicBlock()] = BBNumber++;
420 // Print out code for the function.
421 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
423 // Print a label for the basic block.
424 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
425 << I->getBasicBlock()->getName() << "\n";
426 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
428 // Print the assembly for the instruction.
430 printMachineInstruction(*II);
434 // We didn't modify anything.
438 static bool isScale(const MachineOperand &MO) {
439 return MO.isImmediate() &&
440 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
441 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
444 static bool isMem(const MachineInstr *MI, unsigned Op) {
445 if (MI->getOperand(Op).isFrameIndex()) return true;
446 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
447 return Op+4 <= MI->getNumOperands() &&
448 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
449 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
454 void Printer::printOp(const MachineOperand &MO,
455 bool elideOffsetKeyword /* = false */) {
456 const MRegisterInfo &RI = *TM.getRegisterInfo();
457 switch (MO.getType()) {
458 case MachineOperand::MO_VirtualRegister:
459 if (Value *V = MO.getVRegValueOrNull()) {
460 O << "<" << V->getName() << ">";
464 case MachineOperand::MO_MachineRegister:
465 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister) {
466 // Bug Workaround: See note in Printer::doInitialization about %.
467 if (!EmitCygwin) O << "%";
468 O << RI.get(MO.getReg()).Name;
470 O << "%reg" << MO.getReg();
473 case MachineOperand::MO_SignExtendedImmed:
474 case MachineOperand::MO_UnextendedImmed:
475 O << (int)MO.getImmedValue();
477 case MachineOperand::MO_PCRelativeDisp:
479 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
480 assert (i != NumberForBB.end()
481 && "Could not find a BB I previously put in the NumberForBB map!");
482 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
485 case MachineOperand::MO_GlobalAddress:
486 if (!elideOffsetKeyword)
488 O << Mang->getValueName(MO.getGlobal());
490 case MachineOperand::MO_ExternalSymbol:
491 O << MO.getSymbolName();
494 O << "<unknown operand type>"; return;
498 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
499 switch (Desc.TSFlags & X86II::ArgMask) {
500 default: assert(0 && "Unknown arg size!");
501 case X86II::Arg8: return "BYTE PTR";
502 case X86II::Arg16: return "WORD PTR";
503 case X86II::Arg32: return "DWORD PTR";
504 case X86II::Arg64: return "QWORD PTR";
505 case X86II::ArgF32: return "DWORD PTR";
506 case X86II::ArgF64: return "QWORD PTR";
507 case X86II::ArgF80: return "XWORD PTR";
511 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
512 assert(isMem(MI, Op) && "Invalid memory reference!");
514 if (MI->getOperand(Op).isFrameIndex()) {
515 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
516 if (MI->getOperand(Op+3).getImmedValue())
517 O << " + " << MI->getOperand(Op+3).getImmedValue();
520 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
521 O << "[.CPI" << CurrentFnName << "_"
522 << MI->getOperand(Op).getConstantPoolIndex();
523 if (MI->getOperand(Op+3).getImmedValue())
524 O << " + " << MI->getOperand(Op+3).getImmedValue();
529 const MachineOperand &BaseReg = MI->getOperand(Op);
530 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
531 const MachineOperand &IndexReg = MI->getOperand(Op+2);
532 int DispVal = MI->getOperand(Op+3).getImmedValue();
535 bool NeedPlus = false;
536 if (BaseReg.getReg()) {
541 if (IndexReg.getReg()) {
542 if (NeedPlus) O << " + ";
544 O << ScaleVal << "*";
562 /// checkImplUses - Emit the implicit-use registers for the
563 /// instruction described by DESC, if its PrintImplUses flag is set.
565 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
566 const MRegisterInfo &RI = *TM.getRegisterInfo();
567 if (Desc.TSFlags & X86II::PrintImplUses) {
568 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
569 // Bug Workaround: See note in Printer::doInitialization about %.
570 O << ", " << (EmitCygwin ? "" : "%") << RI.get(*p).Name;
575 /// printMachineInstruction -- Print out a single X86 LLVM instruction
576 /// MI in Intel syntax to the current output stream.
578 void Printer::printMachineInstruction(const MachineInstr *MI) {
579 unsigned Opcode = MI->getOpcode();
580 const TargetInstrInfo &TII = TM.getInstrInfo();
581 const TargetInstrDescriptor &Desc = TII.get(Opcode);
583 switch (Desc.TSFlags & X86II::FormMask) {
585 // Print pseudo-instructions as comments; either they should have been
586 // turned into real instructions by now, or they don't need to be
587 // seen by the assembler (e.g., IMPLICIT_USEs.)
589 if (Opcode == X86::PHI) {
590 printOp(MI->getOperand(0));
592 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
593 if (i != 1) O << ", ";
595 printOp(MI->getOperand(i));
597 printOp(MI->getOperand(i+1));
602 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
603 MI->getOperand(0).opIsDefAndUse())) {
604 printOp(MI->getOperand(0));
608 O << TII.getName(MI->getOpcode());
610 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
612 if (MI->getOperand(i).opIsDefOnly() ||
613 MI->getOperand(i).opIsDefAndUse()) O << "*";
614 printOp(MI->getOperand(i));
615 if (MI->getOperand(i).opIsDefOnly() ||
616 MI->getOperand(i).opIsDefAndUse()) O << "*";
623 // The accepted forms of Raw instructions are:
624 // 1. nop - No operand required
625 // 2. jmp foo - PC relative displacement operand
626 // 3. call bar - GlobalAddress Operand or External Symbol Operand
628 assert(MI->getNumOperands() == 0 ||
629 (MI->getNumOperands() == 1 &&
630 (MI->getOperand(0).isPCRelativeDisp() ||
631 MI->getOperand(0).isGlobalAddress() ||
632 MI->getOperand(0).isExternalSymbol())) &&
633 "Illegal raw instruction!");
634 O << TII.getName(MI->getOpcode()) << " ";
636 if (MI->getNumOperands() == 1) {
637 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
642 case X86II::AddRegFrm: {
643 // There are currently two forms of acceptable AddRegFrm instructions.
644 // Either the instruction JUST takes a single register (like inc, dec, etc),
645 // or it takes a register and an immediate of the same size as the register
646 // (move immediate f.e.). Note that this immediate value might be stored as
647 // an LLVM value, to represent, for example, loading the address of a global
648 // into a register. The initial register might be duplicated if this is a
649 // M_2_ADDR_REG instruction
651 assert(MI->getOperand(0).isRegister() &&
652 (MI->getNumOperands() == 1 ||
653 (MI->getNumOperands() == 2 &&
654 (MI->getOperand(1).getVRegValueOrNull() ||
655 MI->getOperand(1).isImmediate() ||
656 MI->getOperand(1).isRegister() ||
657 MI->getOperand(1).isGlobalAddress() ||
658 MI->getOperand(1).isExternalSymbol()))) &&
659 "Illegal form for AddRegFrm instruction!");
661 unsigned Reg = MI->getOperand(0).getReg();
663 O << TII.getName(MI->getOpCode()) << " ";
664 printOp(MI->getOperand(0));
665 if (MI->getNumOperands() == 2 &&
666 (!MI->getOperand(1).isRegister() ||
667 MI->getOperand(1).getVRegValueOrNull() ||
668 MI->getOperand(1).isGlobalAddress() ||
669 MI->getOperand(1).isExternalSymbol())) {
671 printOp(MI->getOperand(1));
677 case X86II::MRMDestReg: {
678 // There are two acceptable forms of MRMDestReg instructions, those with 2,
681 // 2 Operands: this is for things like mov that do not read a second input
683 // 3 Operands: in this form, the first two registers (the destination, and
684 // the first operand) should be the same, post register allocation. The 3rd
685 // operand is an additional input. This should be for things like add
688 // 4 Operands: This form is for instructions which are 3 operands forms, but
689 // have a constant argument as well.
691 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
692 assert(MI->getOperand(0).isRegister() &&
693 (MI->getNumOperands() == 2 ||
694 (isTwoAddr && MI->getOperand(1).isRegister() &&
695 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
696 (MI->getNumOperands() == 3 ||
697 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
698 && "Bad format for MRMDestReg!");
700 O << TII.getName(MI->getOpCode()) << " ";
701 printOp(MI->getOperand(0));
703 printOp(MI->getOperand(1+isTwoAddr));
704 if (MI->getNumOperands() == 4) {
706 printOp(MI->getOperand(3));
712 case X86II::MRMDestMem: {
713 // These instructions are the same as MRMDestReg, but instead of having a
714 // register reference for the mod/rm field, it's a memory reference.
716 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
717 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
719 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
720 printMemReference(MI, 0);
722 printOp(MI->getOperand(4));
727 case X86II::MRMSrcReg: {
728 // There is a two forms that are acceptable for MRMSrcReg instructions,
729 // those with 3 and 2 operands:
731 // 3 Operands: in this form, the last register (the second input) is the
732 // ModR/M input. The first two operands should be the same, post register
733 // allocation. This is for things like: add r32, r/m32
735 // 2 Operands: this is for things like mov that do not read a second input
737 assert(MI->getOperand(0).isRegister() &&
738 MI->getOperand(1).isRegister() &&
739 (MI->getNumOperands() == 2 ||
740 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
741 && "Bad format for MRMSrcReg!");
742 if (MI->getNumOperands() == 3 &&
743 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
746 O << TII.getName(MI->getOpCode()) << " ";
747 printOp(MI->getOperand(0));
749 printOp(MI->getOperand(MI->getNumOperands()-1));
754 case X86II::MRMSrcMem: {
755 // These instructions are the same as MRMSrcReg, but instead of having a
756 // register reference for the mod/rm field, it's a memory reference.
758 assert(MI->getOperand(0).isRegister() &&
759 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
760 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
762 && "Bad format for MRMDestReg!");
763 if (MI->getNumOperands() == 2+4 &&
764 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
767 O << TII.getName(MI->getOpCode()) << " ";
768 printOp(MI->getOperand(0));
769 O << ", " << sizePtr(Desc) << " ";
770 printMemReference(MI, MI->getNumOperands()-4);
775 case X86II::MRMS0r: case X86II::MRMS1r:
776 case X86II::MRMS2r: case X86II::MRMS3r:
777 case X86II::MRMS4r: case X86II::MRMS5r:
778 case X86II::MRMS6r: case X86II::MRMS7r: {
779 // In this form, the following are valid formats:
781 // 2. cmp reg, immediate
782 // 2. shl rdest, rinput <implicit CL or 1>
783 // 3. sbb rdest, rinput, immediate [rdest = rinput]
785 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
786 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
787 assert((MI->getNumOperands() != 2 ||
788 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
789 "Bad MRMSxR format!");
790 assert((MI->getNumOperands() < 3 ||
791 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
792 "Bad MRMSxR format!");
794 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
795 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
798 O << TII.getName(MI->getOpCode()) << " ";
799 printOp(MI->getOperand(0));
800 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
802 printOp(MI->getOperand(MI->getNumOperands()-1));
810 case X86II::MRMS0m: case X86II::MRMS1m:
811 case X86II::MRMS2m: case X86II::MRMS3m:
812 case X86II::MRMS4m: case X86II::MRMS5m:
813 case X86II::MRMS6m: case X86II::MRMS7m: {
814 // In this form, the following are valid formats:
816 // 2. cmp [m], immediate
817 // 2. shl [m], rinput <implicit CL or 1>
818 // 3. sbb [m], immediate
820 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
821 isMem(MI, 0) && "Bad MRMSxM format!");
822 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
823 "Bad MRMSxM format!");
824 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
825 // is misassembled by gas in intel_syntax mode as its 32-bit
826 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
827 // opcode bytes instead of the instruction.
828 if (MI->getOpCode() == X86::FSTPr80) {
829 if ((MI->getOperand(0).getReg() == X86::ESP)
830 && (MI->getOperand(1).getImmedValue() == 1)) {
831 int DispVal = MI->getOperand(3).getImmedValue();
832 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
833 unsigned int val = (unsigned int) DispVal;
834 O << ".byte 0xdb, 0xbc, 0x24\n\t";
835 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
836 } else { // 1 byte disp.
837 unsigned char val = (unsigned char) DispVal;
838 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
839 << std::dec << "\t# ";
843 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
844 // misassembled by gas in intel_syntax mode as its 32-bit
845 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
846 // opcode bytes instead of the instruction.
847 if (MI->getOpCode() == X86::FLDr80) {
848 if ((MI->getOperand(0).getReg() == X86::ESP)
849 && (MI->getOperand(1).getImmedValue() == 1)) {
850 int DispVal = MI->getOperand(3).getImmedValue();
851 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
852 unsigned int val = (unsigned int) DispVal;
853 O << ".byte 0xdb, 0xac, 0x24\n\t";
854 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
855 } else { // 1 byte disp.
856 unsigned char val = (unsigned char) DispVal;
857 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
858 << std::dec << "\t# ";
862 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
863 // invalid opcode, saying "64 bit operations are only supported in
864 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
865 // [...]", which is wrong. Workaround: Output the raw opcode bytes
866 // instead of the instruction.
867 if (MI->getOpCode() == X86::FILDr64) {
868 if ((MI->getOperand(0).getReg() == X86::ESP)
869 && (MI->getOperand(1).getImmedValue() == 1)) {
870 int DispVal = MI->getOperand(3).getImmedValue();
871 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
872 unsigned int val = (unsigned int) DispVal;
873 O << ".byte 0xdf, 0xac, 0x24\n\t";
874 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
875 } else { // 1 byte disp.
876 unsigned char val = (unsigned char) DispVal;
877 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
878 << std::dec << "\t# ";
882 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
883 // an invalid opcode, saying "64 bit operations are only
884 // supported in 64 bit modes." libopcodes disassembles it as
885 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
886 // "fistpll DWORD PTR " instead, which is what libopcodes is
888 if (MI->getOpCode() == X86::FISTPr64) {
889 O << "fistpll DWORD PTR ";
890 printMemReference(MI, 0);
891 if (MI->getNumOperands() == 5) {
893 printOp(MI->getOperand(4));
898 O << TII.getName(MI->getOpCode()) << " ";
899 O << sizePtr(Desc) << " ";
900 printMemReference(MI, 0);
901 if (MI->getNumOperands() == 5) {
903 printOp(MI->getOperand(4));
910 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
914 bool Printer::doInitialization(Module &M) {
915 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
917 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
918 // instruction as a reference to the register named sp, and if you try to
919 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
920 // before being looked up in the symbol table. This creates spurious
921 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
922 // mode, and decorate all register names with percent signs.
924 // Cygwin presumably doesn't have this problem, so drop the %'s.
926 O << "\t.intel_syntax";
927 if (EmitCygwin) O << " noprefix";
929 Mang = new Mangler(M, EmitCygwin);
930 return false; // success
933 static const Function *isConstantFunctionPointerRef(const Constant *C) {
934 if (const ConstantPointerRef *R = dyn_cast<ConstantPointerRef>(C))
935 if (const Function *F = dyn_cast<Function>(R->getValue()))
940 bool Printer::doFinalization(Module &M)
942 const TargetData &TD = TM.getTargetData();
943 // Print out module-level global variables here.
944 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
945 std::string name(Mang->getValueName(I));
946 if (I->hasInitializer()) {
947 Constant *C = I->getInitializer();
948 if (C->isNullValue()) {
949 O << "\n\n\t.comm " << name << "," << TD.getTypeSize(C->getType())
950 << "," << (unsigned)TD.getTypeAlignment(C->getType());
952 WriteAsOperand(O, I, true, true, &M);
955 O << "\n\n\t.data\n";
956 O << "\t.globl " << name << "\n";
957 O << "\t.type " << name << ",@object\n";
958 O << "\t.size " << name << "," << TD.getTypeSize(C->getType()) << "\n";
959 O << "\t.align " << (unsigned)TD.getTypeAlignment(C->getType()) << "\n";
960 O << name << ":\t\t\t\t# ";
961 WriteAsOperand(O, I, true, true, &M);
963 WriteAsOperand(O, C, false, false, &M);
965 printConstantValueOnly(C);
968 O << "\t.globl " << name << "\n";
969 O << "\t.comm " << name << ", "
970 << (unsigned)TD.getTypeSize(I->getType()) << ", "
971 << (unsigned)TD.getTypeAlignment(I->getType()) << "\n";
975 return false; // success