1 //===-- X86/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal
11 // representation of machine-dependent LLVM code to Intel-format
12 // assembly language. This printer is the output mechanism used
13 // by `llc' and `lli -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Mangler.h"
28 #include "Support/Statistic.h"
29 #include "Support/StringExtras.h"
30 #include "Support/CommandLine.h"
33 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35 // FIXME: This should be automatically picked up by autoconf from the C
37 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
38 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
40 struct Printer : public MachineFunctionPass {
41 /// Output stream on which we're printing assembly code.
45 /// Target machine description which we query for reg. names, data
50 /// Name-mangler for global names.
54 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
56 /// We name each basic block in a Function with a unique number, so
57 /// that we can consistently refer to them later. This is cleared
58 /// at the beginning of each call to runOnMachineFunction().
60 typedef std::map<const Value *, unsigned> ValueMapTy;
61 ValueMapTy NumberForBB;
63 /// Cache of mangled name for current function. This is
64 /// recalculated at the beginning of each call to
65 /// runOnMachineFunction().
67 std::string CurrentFnName;
69 virtual const char *getPassName() const {
70 return "X86 Assembly Printer";
73 void checkImplUses (const TargetInstrDescriptor &Desc);
74 void printMachineInstruction(const MachineInstr *MI);
75 void printOp(const MachineOperand &MO,
76 bool elideOffsetKeyword = false);
77 void printMemReference(const MachineInstr *MI, unsigned Op);
78 void printConstantPool(MachineConstantPool *MCP);
79 bool runOnMachineFunction(MachineFunction &F);
80 std::string ConstantExprToString(const ConstantExpr* CE);
81 std::string valToExprString(const Value* V);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
84 void printConstantValueOnly(const Constant* CV);
85 void printSingleConstantValue(const Constant* CV);
87 } // end of anonymous namespace
89 /// createX86CodePrinterPass - Returns a pass that prints the X86
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
94 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
95 return new Printer(o, tm);
98 /// valToExprString - Helper function for ConstantExprToString().
99 /// Appends result to argument string S.
101 std::string Printer::valToExprString(const Value* V) {
104 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
105 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
106 S += std::string(CB == ConstantBool::True ? "1" : "0");
107 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
108 S += itostr(CI->getValue());
109 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
110 S += utostr(CI->getValue());
111 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
112 S += ftostr(CFP->getValue());
113 else if (isa<ConstantPointerNull>(CV))
115 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
116 S += valToExprString(CPR->getValue());
117 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
118 S += ConstantExprToString(CE);
121 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
122 S += Mang->getValueName(GV);
128 assert(0 && "Cannot convert value to string");
129 S += "<illegal-value>";
134 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
135 /// and return this as a string.
137 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
138 const TargetData &TD = TM.getTargetData();
139 switch(CE->getOpcode()) {
140 case Instruction::GetElementPtr:
141 { // generate a symbolic expression for the byte address
142 const Value* ptrVal = CE->getOperand(0);
143 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
144 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
145 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
147 return valToExprString(ptrVal);
150 case Instruction::Cast:
151 // Support only non-converting or widening casts for now, that is,
152 // ones that do not involve a change in value. This assertion is
153 // not a complete check.
155 Constant *Op = CE->getOperand(0);
156 const Type *OpTy = Op->getType(), *Ty = CE->getType();
157 assert(((isa<PointerType>(OpTy)
158 && (Ty == Type::LongTy || Ty == Type::ULongTy))
159 || (isa<PointerType>(Ty)
160 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
161 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
162 && (OpTy->isLosslesslyConvertibleTo(Ty))))
163 && "FIXME: Don't yet support this kind of constant cast expr");
164 return "(" + valToExprString(Op) + ")";
167 case Instruction::Add:
168 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
169 + valToExprString(CE->getOperand(1)) + ")";
172 assert(0 && "Unsupported operator in ConstantExprToString()");
177 /// printSingleConstantValue - Print a single constant value.
180 Printer::printSingleConstantValue(const Constant* CV)
182 assert(CV->getType() != Type::VoidTy &&
183 CV->getType() != Type::TypeTy &&
184 CV->getType() != Type::LabelTy &&
185 "Unexpected type for Constant");
187 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
188 && "Aggregate types should be handled outside this function");
190 const Type *type = CV->getType();
192 switch(type->getPrimitiveID())
194 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
197 case Type::UShortTyID: case Type::ShortTyID:
200 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
203 case Type::ULongTyID: case Type::LongTyID:
206 case Type::FloatTyID:
209 case Type::DoubleTyID:
212 case Type::ArrayTyID:
213 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
214 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
217 assert (0 && "Can't handle printing this type of array");
220 assert (0 && "Can't handle printing this type of thing");
225 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
227 // Constant expression built from operators, constants, and
229 O << ConstantExprToString(CE) << "\n";
231 else if (type->isPrimitiveType())
233 if (type->isFloatingPoint()) {
234 // FP Constants are printed as integer constants to avoid losing
236 double Val = cast<ConstantFP>(CV)->getValue();
237 if (type == Type::FloatTy) {
238 float FVal = (float)Val;
239 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
240 O << *(unsigned int*)ProxyPtr;
241 } else if (type == Type::DoubleTy) {
242 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
243 O << *(uint64_t*)ProxyPtr;
245 assert(0 && "Unknown floating point type!");
248 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
250 WriteAsOperand(O, CV, false, false) << "\n";
253 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
255 // This is a constant address for a global variable or method.
256 // Use the name of the variable or method as the address value.
257 O << Mang->getValueName(CPR->getValue()) << "\n";
259 else if (isa<ConstantPointerNull>(CV))
261 // Null pointer value
266 assert(0 && "Unknown elementary type for constant");
270 /// isStringCompatible - Can we treat the specified array as a string?
271 /// Only if it is an array of ubytes or non-negative sbytes.
273 static bool isStringCompatible(const ConstantArray *CVA) {
274 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
275 if (ETy == Type::UByteTy) return true;
276 if (ETy != Type::SByteTy) return false;
278 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
279 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
285 /// toOctal - Convert the low order bits of X into an octal digit.
287 static inline char toOctal(int X) {
291 /// getAsCString - Return the specified array as a C compatible
292 /// string, only if the predicate isStringCompatible is true.
294 static std::string getAsCString(const ConstantArray *CVA) {
295 assert(isStringCompatible(CVA) && "Array is not string compatible!");
298 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
300 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
301 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
305 } else if (C == '\\') {
307 } else if (isprint(C)) {
311 case '\b': Result += "\\b"; break;
312 case '\f': Result += "\\f"; break;
313 case '\n': Result += "\\n"; break;
314 case '\r': Result += "\\r"; break;
315 case '\t': Result += "\\t"; break;
318 Result += toOctal(C >> 6);
319 Result += toOctal(C >> 3);
320 Result += toOctal(C >> 0);
329 // Print a constant value or values (it may be an aggregate).
330 // Uses printSingleConstantValue() to print each individual value.
331 void Printer::printConstantValueOnly(const Constant *CV) {
332 const TargetData &TD = TM.getTargetData();
334 if (CV->isNullValue()) {
335 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
336 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
337 if (isStringCompatible(CVA)) {
338 // print the string alone and return
339 O << "\t.ascii\t" << getAsCString(CVA) << "\n";
340 } else { // Not a string. Print the values in successive locations
341 const std::vector<Use> &constValues = CVA->getValues();
342 for (unsigned i=0; i < constValues.size(); i++)
343 printConstantValueOnly(cast<Constant>(constValues[i].get()));
345 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
346 // Print the fields in successive locations. Pad to align if needed!
347 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
348 const std::vector<Use>& constValues = CVS->getValues();
349 unsigned sizeSoFar = 0;
350 for (unsigned i=0, N = constValues.size(); i < N; i++) {
351 const Constant* field = cast<Constant>(constValues[i].get());
353 // Check if padding is needed and insert one or more 0s.
354 unsigned fieldSize = TD.getTypeSize(field->getType());
355 unsigned padSize = ((i == N-1? cvsLayout->StructSize
356 : cvsLayout->MemberOffsets[i+1])
357 - cvsLayout->MemberOffsets[i]) - fieldSize;
358 sizeSoFar += fieldSize + padSize;
360 // Now print the actual field value
361 printConstantValueOnly(field);
363 // Insert the field padding unless it's zero bytes...
365 O << "\t.zero\t " << padSize << "\n";
367 assert(sizeSoFar == cvsLayout->StructSize &&
368 "Layout of constant struct may be incorrect!");
370 printSingleConstantValue(CV);
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
378 void Printer::printConstantPool(MachineConstantPool *MCP) {
379 const std::vector<Constant*> &CP = MCP->getConstants();
380 const TargetData &TD = TM.getTargetData();
382 if (CP.empty()) return;
384 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385 O << "\t.section .rodata\n";
386 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
388 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
390 printConstantValueOnly (CP[i]);
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
397 bool Printer::runOnMachineFunction(MachineFunction &MF) {
398 // BBNumber is used here so that a given Printer will never give two
399 // BBs the same name. (If you have a better way, please let me know!)
400 static unsigned BBNumber = 0;
403 // What's my mangled name?
404 CurrentFnName = Mang->getValueName(MF.getFunction());
406 // Print out constants referenced by the function
407 printConstantPool(MF.getConstantPool());
409 // Print out labels for the function.
411 O << "\t.align 16\n";
412 O << "\t.globl\t" << CurrentFnName << "\n";
414 O << "\t.type\t" << CurrentFnName << ", @function\n";
415 O << CurrentFnName << ":\n";
417 // Number each basic block so that we can consistently refer to them
418 // in PC-relative references.
420 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
422 NumberForBB[I->getBasicBlock()] = BBNumber++;
425 // Print out code for the function.
426 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
428 // Print a label for the basic block.
429 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
430 << I->getBasicBlock()->getName() << "\n";
431 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
433 // Print the assembly for the instruction.
435 printMachineInstruction(*II);
439 // We didn't modify anything.
443 static bool isScale(const MachineOperand &MO) {
444 return MO.isImmediate() &&
445 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
446 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
449 static bool isMem(const MachineInstr *MI, unsigned Op) {
450 if (MI->getOperand(Op).isFrameIndex()) return true;
451 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
452 return Op+4 <= MI->getNumOperands() &&
453 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
454 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
459 void Printer::printOp(const MachineOperand &MO,
460 bool elideOffsetKeyword /* = false */) {
461 const MRegisterInfo &RI = *TM.getRegisterInfo();
462 switch (MO.getType()) {
463 case MachineOperand::MO_VirtualRegister:
464 if (Value *V = MO.getVRegValueOrNull()) {
465 O << "<" << V->getName() << ">";
469 case MachineOperand::MO_MachineRegister:
470 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
471 // Bug Workaround: See note in Printer::doInitialization about %.
472 O << "%" << RI.get(MO.getReg()).Name;
474 O << "%reg" << MO.getReg();
477 case MachineOperand::MO_SignExtendedImmed:
478 case MachineOperand::MO_UnextendedImmed:
479 O << (int)MO.getImmedValue();
481 case MachineOperand::MO_PCRelativeDisp: {
482 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
483 assert (i != NumberForBB.end()
484 && "Could not find a BB in the NumberForBB map!");
485 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
488 case MachineOperand::MO_GlobalAddress:
489 if (!elideOffsetKeyword)
491 O << Mang->getValueName(MO.getGlobal());
493 case MachineOperand::MO_ExternalSymbol:
494 O << MO.getSymbolName();
497 O << "<unknown operand type>"; return;
501 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
502 switch (Desc.TSFlags & X86II::ArgMask) {
503 default: assert(0 && "Unknown arg size!");
504 case X86II::Arg8: return "BYTE PTR";
505 case X86II::Arg16: return "WORD PTR";
506 case X86II::Arg32: return "DWORD PTR";
507 case X86II::Arg64: return "QWORD PTR";
508 case X86II::ArgF32: return "DWORD PTR";
509 case X86II::ArgF64: return "QWORD PTR";
510 case X86II::ArgF80: return "XWORD PTR";
514 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
515 assert(isMem(MI, Op) && "Invalid memory reference!");
517 if (MI->getOperand(Op).isFrameIndex()) {
518 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
519 if (MI->getOperand(Op+3).getImmedValue())
520 O << " + " << MI->getOperand(Op+3).getImmedValue();
523 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
524 O << "[.CPI" << CurrentFnName << "_"
525 << MI->getOperand(Op).getConstantPoolIndex();
526 if (MI->getOperand(Op+3).getImmedValue())
527 O << " + " << MI->getOperand(Op+3).getImmedValue();
532 const MachineOperand &BaseReg = MI->getOperand(Op);
533 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
534 const MachineOperand &IndexReg = MI->getOperand(Op+2);
535 int DispVal = MI->getOperand(Op+3).getImmedValue();
538 bool NeedPlus = false;
539 if (BaseReg.getReg()) {
544 if (IndexReg.getReg()) {
545 if (NeedPlus) O << " + ";
547 O << ScaleVal << "*";
565 /// checkImplUses - Emit the implicit-use registers for the
566 /// instruction described by DESC, if its PrintImplUses flag is set.
568 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
569 const MRegisterInfo &RI = *TM.getRegisterInfo();
570 if (Desc.TSFlags & X86II::PrintImplUses) {
571 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
572 // Bug Workaround: See note in Printer::doInitialization about %.
573 O << ", %" << RI.get(*p).Name;
578 /// printMachineInstruction -- Print out a single X86 LLVM instruction
579 /// MI in Intel syntax to the current output stream.
581 void Printer::printMachineInstruction(const MachineInstr *MI) {
582 unsigned Opcode = MI->getOpcode();
583 const TargetInstrInfo &TII = TM.getInstrInfo();
584 const TargetInstrDescriptor &Desc = TII.get(Opcode);
587 switch (Desc.TSFlags & X86II::FormMask) {
589 // Print pseudo-instructions as comments; either they should have been
590 // turned into real instructions by now, or they don't need to be
591 // seen by the assembler (e.g., IMPLICIT_USEs.)
593 if (Opcode == X86::PHI) {
594 printOp(MI->getOperand(0));
596 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
597 if (i != 1) O << ", ";
599 printOp(MI->getOperand(i));
601 printOp(MI->getOperand(i+1));
606 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
607 MI->getOperand(0).opIsDefAndUse())) {
608 printOp(MI->getOperand(0));
612 O << TII.getName(MI->getOpcode());
614 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
616 if (MI->getOperand(i).opIsDefOnly() ||
617 MI->getOperand(i).opIsDefAndUse()) O << "*";
618 printOp(MI->getOperand(i));
619 if (MI->getOperand(i).opIsDefOnly() ||
620 MI->getOperand(i).opIsDefAndUse()) O << "*";
627 // The accepted forms of Raw instructions are:
628 // 1. nop - No operand required
629 // 2. jmp foo - PC relative displacement operand
630 // 3. call bar - GlobalAddress Operand or External Symbol Operand
632 assert(MI->getNumOperands() == 0 ||
633 (MI->getNumOperands() == 1 &&
634 (MI->getOperand(0).isPCRelativeDisp() ||
635 MI->getOperand(0).isGlobalAddress() ||
636 MI->getOperand(0).isExternalSymbol())) &&
637 "Illegal raw instruction!");
638 O << TII.getName(MI->getOpcode()) << " ";
640 if (MI->getNumOperands() == 1) {
641 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
646 case X86II::AddRegFrm: {
647 // There are currently two forms of acceptable AddRegFrm instructions.
648 // Either the instruction JUST takes a single register (like inc, dec, etc),
649 // or it takes a register and an immediate of the same size as the register
650 // (move immediate f.e.). Note that this immediate value might be stored as
651 // an LLVM value, to represent, for example, loading the address of a global
652 // into a register. The initial register might be duplicated if this is a
653 // M_2_ADDR_REG instruction
655 assert(MI->getOperand(0).isRegister() &&
656 (MI->getNumOperands() == 1 ||
657 (MI->getNumOperands() == 2 &&
658 (MI->getOperand(1).getVRegValueOrNull() ||
659 MI->getOperand(1).isImmediate() ||
660 MI->getOperand(1).isRegister() ||
661 MI->getOperand(1).isGlobalAddress() ||
662 MI->getOperand(1).isExternalSymbol()))) &&
663 "Illegal form for AddRegFrm instruction!");
665 unsigned Reg = MI->getOperand(0).getReg();
667 O << TII.getName(MI->getOpCode()) << " ";
668 printOp(MI->getOperand(0));
669 if (MI->getNumOperands() == 2 &&
670 (!MI->getOperand(1).isRegister() ||
671 MI->getOperand(1).getVRegValueOrNull() ||
672 MI->getOperand(1).isGlobalAddress() ||
673 MI->getOperand(1).isExternalSymbol())) {
675 printOp(MI->getOperand(1));
681 case X86II::MRMDestReg: {
682 // There are two acceptable forms of MRMDestReg instructions, those with 2,
685 // 2 Operands: this is for things like mov that do not read a second input
687 // 3 Operands: in this form, the first two registers (the destination, and
688 // the first operand) should be the same, post register allocation. The 3rd
689 // operand is an additional input. This should be for things like add
692 // 4 Operands: This form is for instructions which are 3 operands forms, but
693 // have a constant argument as well.
695 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
696 assert(MI->getOperand(0).isRegister() &&
697 (MI->getNumOperands() == 2 ||
698 (isTwoAddr && MI->getOperand(1).isRegister() &&
699 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
700 (MI->getNumOperands() == 3 ||
701 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
702 && "Bad format for MRMDestReg!");
704 O << TII.getName(MI->getOpCode()) << " ";
705 printOp(MI->getOperand(0));
707 printOp(MI->getOperand(1+isTwoAddr));
708 if (MI->getNumOperands() == 4) {
710 printOp(MI->getOperand(3));
716 case X86II::MRMDestMem: {
717 // These instructions are the same as MRMDestReg, but instead of having a
718 // register reference for the mod/rm field, it's a memory reference.
720 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
721 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
723 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
724 printMemReference(MI, 0);
726 printOp(MI->getOperand(4));
731 case X86II::MRMSrcReg: {
732 // There are three forms that are acceptable for MRMSrcReg instructions,
733 // those with 3 and 2 operands:
735 // 3 Operands: in this form, the last register (the second input) is the
736 // ModR/M input. The first two operands should be the same, post register
737 // allocation. This is for things like: add r32, r/m32
739 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
740 // instructions like the IMULri instructions.
742 // 2 Operands: this is for things like mov that do not read a second input
744 assert(MI->getOperand(0).isRegister() &&
745 MI->getOperand(1).isRegister() &&
746 (MI->getNumOperands() == 2 ||
747 (MI->getNumOperands() == 3 &&
748 (MI->getOperand(2).isRegister() ||
749 MI->getOperand(2).isImmediate())))
750 && "Bad format for MRMSrcReg!");
751 if (MI->getNumOperands() == 3 &&
752 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
755 O << TII.getName(MI->getOpCode()) << " ";
756 printOp(MI->getOperand(0));
758 // If this is IMULri* instructions, print the non-two-address operand.
759 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
761 printOp(MI->getOperand(1));
765 printOp(MI->getOperand(MI->getNumOperands()-1));
770 case X86II::MRMSrcMem: {
771 // These instructions are the same as MRMSrcReg, but instead of having a
772 // register reference for the mod/rm field, it's a memory reference.
774 assert(MI->getOperand(0).isRegister() &&
775 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
776 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
778 && "Bad format for MRMDestReg!");
779 if (MI->getNumOperands() == 2+4 &&
780 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
783 O << TII.getName(MI->getOpCode()) << " ";
784 printOp(MI->getOperand(0));
785 O << ", " << sizePtr(Desc) << " ";
786 printMemReference(MI, MI->getNumOperands()-4);
791 case X86II::MRMS0r: case X86II::MRMS1r:
792 case X86II::MRMS2r: case X86II::MRMS3r:
793 case X86II::MRMS4r: case X86II::MRMS5r:
794 case X86II::MRMS6r: case X86II::MRMS7r: {
795 // In this form, the following are valid formats:
797 // 2. cmp reg, immediate
798 // 2. shl rdest, rinput <implicit CL or 1>
799 // 3. sbb rdest, rinput, immediate [rdest = rinput]
801 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
802 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
803 assert((MI->getNumOperands() != 2 ||
804 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
805 "Bad MRMSxR format!");
806 assert((MI->getNumOperands() < 3 ||
807 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
808 "Bad MRMSxR format!");
810 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
811 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
814 O << TII.getName(MI->getOpCode()) << " ";
815 printOp(MI->getOperand(0));
816 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
818 printOp(MI->getOperand(MI->getNumOperands()-1));
826 case X86II::MRMS0m: case X86II::MRMS1m:
827 case X86II::MRMS2m: case X86II::MRMS3m:
828 case X86II::MRMS4m: case X86II::MRMS5m:
829 case X86II::MRMS6m: case X86II::MRMS7m: {
830 // In this form, the following are valid formats:
832 // 2. cmp [m], immediate
833 // 2. shl [m], rinput <implicit CL or 1>
834 // 3. sbb [m], immediate
836 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
837 isMem(MI, 0) && "Bad MRMSxM format!");
838 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
839 "Bad MRMSxM format!");
840 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
841 // is misassembled by gas in intel_syntax mode as its 32-bit
842 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
843 // opcode bytes instead of the instruction.
844 if (MI->getOpCode() == X86::FSTPr80) {
845 if ((MI->getOperand(0).getReg() == X86::ESP)
846 && (MI->getOperand(1).getImmedValue() == 1)) {
847 int DispVal = MI->getOperand(3).getImmedValue();
848 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
849 unsigned int val = (unsigned int) DispVal;
850 O << ".byte 0xdb, 0xbc, 0x24\n\t";
851 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
852 } else { // 1 byte disp.
853 unsigned char val = (unsigned char) DispVal;
854 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
855 << std::dec << "\t# ";
859 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
860 // misassembled by gas in intel_syntax mode as its 32-bit
861 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
862 // opcode bytes instead of the instruction.
863 if (MI->getOpCode() == X86::FLDr80) {
864 if ((MI->getOperand(0).getReg() == X86::ESP)
865 && (MI->getOperand(1).getImmedValue() == 1)) {
866 int DispVal = MI->getOperand(3).getImmedValue();
867 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
868 unsigned int val = (unsigned int) DispVal;
869 O << ".byte 0xdb, 0xac, 0x24\n\t";
870 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
871 } else { // 1 byte disp.
872 unsigned char val = (unsigned char) DispVal;
873 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
874 << std::dec << "\t# ";
878 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
879 // invalid opcode, saying "64 bit operations are only supported in
880 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
881 // [...]", which is wrong. Workaround: Output the raw opcode bytes
882 // instead of the instruction.
883 if (MI->getOpCode() == X86::FILDr64) {
884 if ((MI->getOperand(0).getReg() == X86::ESP)
885 && (MI->getOperand(1).getImmedValue() == 1)) {
886 int DispVal = MI->getOperand(3).getImmedValue();
887 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
888 unsigned int val = (unsigned int) DispVal;
889 O << ".byte 0xdf, 0xac, 0x24\n\t";
890 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
891 } else { // 1 byte disp.
892 unsigned char val = (unsigned char) DispVal;
893 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
894 << std::dec << "\t# ";
898 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
899 // an invalid opcode, saying "64 bit operations are only
900 // supported in 64 bit modes." libopcodes disassembles it as
901 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
902 // "fistpll DWORD PTR " instead, which is what libopcodes is
904 if (MI->getOpCode() == X86::FISTPr64) {
905 O << "fistpll DWORD PTR ";
906 printMemReference(MI, 0);
907 if (MI->getNumOperands() == 5) {
909 printOp(MI->getOperand(4));
914 O << TII.getName(MI->getOpCode()) << " ";
915 O << sizePtr(Desc) << " ";
916 printMemReference(MI, 0);
917 if (MI->getNumOperands() == 5) {
919 printOp(MI->getOperand(4));
926 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
930 bool Printer::doInitialization(Module &M) {
931 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
933 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
934 // instruction as a reference to the register named sp, and if you try to
935 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
936 // before being looked up in the symbol table. This creates spurious
937 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
938 // mode, and decorate all register names with percent signs.
939 O << "\t.intel_syntax\n";
940 Mang = new Mangler(M, EmitCygwin);
941 return false; // success
944 // SwitchSection - Switch to the specified section of the executable if we are
945 // not already in it!
947 static void SwitchSection(std::ostream &OS, std::string &CurSection,
948 const char *NewSection) {
949 if (CurSection != NewSection) {
950 CurSection = NewSection;
951 if (!CurSection.empty())
952 OS << "\t" << NewSection << "\n";
956 bool Printer::doFinalization(Module &M) {
957 const TargetData &TD = TM.getTargetData();
958 std::string CurSection;
960 // Print out module-level global variables here.
961 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
962 if (I->hasInitializer()) { // External global require no code
964 std::string name = Mang->getValueName(I);
965 Constant *C = I->getInitializer();
966 unsigned Size = TD.getTypeSize(C->getType());
967 unsigned Align = TD.getTypeAlignment(C->getType());
969 if (C->isNullValue() &&
970 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
971 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
972 SwitchSection(O, CurSection, ".data");
973 if (I->hasInternalLinkage())
974 O << "\t.local " << name << "\n";
976 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
977 << "," << (unsigned)TD.getTypeAlignment(C->getType());
979 WriteAsOperand(O, I, true, true, &M);
982 switch (I->getLinkage()) {
983 case GlobalValue::LinkOnceLinkage:
984 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
985 // Nonnull linkonce -> weak
986 O << "\t.weak " << name << "\n";
987 SwitchSection(O, CurSection, "");
988 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
991 case GlobalValue::AppendingLinkage:
992 // FIXME: appending linkage variables should go into a section of
993 // their name or something. For now, just emit them as external.
994 case GlobalValue::ExternalLinkage:
995 // If external or appending, declare as a global symbol
996 O << "\t.globl " << name << "\n";
998 case GlobalValue::InternalLinkage:
999 if (C->isNullValue())
1000 SwitchSection(O, CurSection, ".bss");
1002 SwitchSection(O, CurSection, ".data");
1006 O << "\t.align " << Align << "\n";
1007 O << "\t.type " << name << ",@object\n";
1008 O << "\t.size " << name << "," << Size << "\n";
1009 O << name << ":\t\t\t\t# ";
1010 WriteAsOperand(O, I, true, true, &M);
1012 WriteAsOperand(O, C, false, false, &M);
1014 printConstantValueOnly(C);
1019 return false; // success