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)) {
226 // Constant expression built from operators, constants, and
228 O << ConstantExprToString(CE) << "\n";
229 } else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
230 O << (CB->getValue() ? "1\n" : "0\n");
231 } else if (type->isFloatingPoint()) {
232 // FP Constants are printed as integer constants to avoid losing
234 double Val = cast<ConstantFP>(CV)->getValue();
235 if (type == Type::FloatTy) {
236 float FVal = (float)Val;
237 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
238 O << *(unsigned int*)ProxyPtr;
239 } else if (type == Type::DoubleTy) {
240 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
241 O << *(uint64_t*)ProxyPtr;
243 assert(0 && "Unknown floating point type!");
246 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
247 } else if (type->isPrimitiveType()) {
249 WriteAsOperand(O, CV, false, false) << "\n";
250 } else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV)) {
251 // This is a constant address for a global variable or method.
252 // Use the name of the variable or method as the address value.
253 O << Mang->getValueName(CPR->getValue()) << "\n";
254 } else if (isa<ConstantPointerNull>(CV)) {
255 // Null pointer value
258 assert(0 && "Unknown elementary type for constant");
262 /// isStringCompatible - Can we treat the specified array as a string?
263 /// Only if it is an array of ubytes or non-negative sbytes.
265 static bool isStringCompatible(const ConstantArray *CVA) {
266 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
267 if (ETy == Type::UByteTy) return true;
268 if (ETy != Type::SByteTy) return false;
270 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
271 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
277 /// toOctal - Convert the low order bits of X into an octal digit.
279 static inline char toOctal(int X) {
283 /// getAsCString - Return the specified array as a C compatible
284 /// string, only if the predicate isStringCompatible is true.
286 static std::string getAsCString(const ConstantArray *CVA) {
287 assert(isStringCompatible(CVA) && "Array is not string compatible!");
290 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
292 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
293 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
297 } else if (C == '\\') {
299 } else if (isprint(C)) {
303 case '\b': Result += "\\b"; break;
304 case '\f': Result += "\\f"; break;
305 case '\n': Result += "\\n"; break;
306 case '\r': Result += "\\r"; break;
307 case '\t': Result += "\\t"; break;
310 Result += toOctal(C >> 6);
311 Result += toOctal(C >> 3);
312 Result += toOctal(C >> 0);
321 // Print a constant value or values (it may be an aggregate).
322 // Uses printSingleConstantValue() to print each individual value.
323 void Printer::printConstantValueOnly(const Constant *CV) {
324 const TargetData &TD = TM.getTargetData();
326 if (CV->isNullValue()) {
327 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
328 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
329 if (isStringCompatible(CVA)) {
330 // print the string alone and return
331 O << "\t.ascii\t" << getAsCString(CVA) << "\n";
332 } else { // Not a string. Print the values in successive locations
333 const std::vector<Use> &constValues = CVA->getValues();
334 for (unsigned i=0; i < constValues.size(); i++)
335 printConstantValueOnly(cast<Constant>(constValues[i].get()));
337 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
338 // Print the fields in successive locations. Pad to align if needed!
339 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
340 const std::vector<Use>& constValues = CVS->getValues();
341 unsigned sizeSoFar = 0;
342 for (unsigned i=0, N = constValues.size(); i < N; i++) {
343 const Constant* field = cast<Constant>(constValues[i].get());
345 // Check if padding is needed and insert one or more 0s.
346 unsigned fieldSize = TD.getTypeSize(field->getType());
347 unsigned padSize = ((i == N-1? cvsLayout->StructSize
348 : cvsLayout->MemberOffsets[i+1])
349 - cvsLayout->MemberOffsets[i]) - fieldSize;
350 sizeSoFar += fieldSize + padSize;
352 // Now print the actual field value
353 printConstantValueOnly(field);
355 // Insert the field padding unless it's zero bytes...
357 O << "\t.zero\t " << padSize << "\n";
359 assert(sizeSoFar == cvsLayout->StructSize &&
360 "Layout of constant struct may be incorrect!");
362 printSingleConstantValue(CV);
365 /// printConstantPool - Print to the current output stream assembly
366 /// representations of the constants in the constant pool MCP. This is
367 /// used to print out constants which have been "spilled to memory" by
368 /// the code generator.
370 void Printer::printConstantPool(MachineConstantPool *MCP) {
371 const std::vector<Constant*> &CP = MCP->getConstants();
372 const TargetData &TD = TM.getTargetData();
374 if (CP.empty()) return;
376 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
377 O << "\t.section .rodata\n";
378 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
380 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
382 printConstantValueOnly (CP[i]);
386 /// runOnMachineFunction - This uses the printMachineInstruction()
387 /// method to print assembly for each instruction.
389 bool Printer::runOnMachineFunction(MachineFunction &MF) {
390 // BBNumber is used here so that a given Printer will never give two
391 // BBs the same name. (If you have a better way, please let me know!)
392 static unsigned BBNumber = 0;
395 // What's my mangled name?
396 CurrentFnName = Mang->getValueName(MF.getFunction());
398 // Print out constants referenced by the function
399 printConstantPool(MF.getConstantPool());
401 // Print out labels for the function.
403 O << "\t.align 16\n";
404 O << "\t.globl\t" << CurrentFnName << "\n";
406 O << "\t.type\t" << CurrentFnName << ", @function\n";
407 O << CurrentFnName << ":\n";
409 // Number each basic block so that we can consistently refer to them
410 // in PC-relative references.
412 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
414 NumberForBB[I->getBasicBlock()] = BBNumber++;
417 // Print out code for the function.
418 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
420 // Print a label for the basic block.
421 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
422 << I->getBasicBlock()->getName() << "\n";
423 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
425 // Print the assembly for the instruction.
427 printMachineInstruction(*II);
431 // We didn't modify anything.
435 static bool isScale(const MachineOperand &MO) {
436 return MO.isImmediate() &&
437 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
438 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
441 static bool isMem(const MachineInstr *MI, unsigned Op) {
442 if (MI->getOperand(Op).isFrameIndex()) return true;
443 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
444 return Op+4 <= MI->getNumOperands() &&
445 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
446 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
451 void Printer::printOp(const MachineOperand &MO,
452 bool elideOffsetKeyword /* = false */) {
453 const MRegisterInfo &RI = *TM.getRegisterInfo();
454 switch (MO.getType()) {
455 case MachineOperand::MO_VirtualRegister:
456 if (Value *V = MO.getVRegValueOrNull()) {
457 O << "<" << V->getName() << ">";
461 case MachineOperand::MO_MachineRegister:
462 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
463 // Bug Workaround: See note in Printer::doInitialization about %.
464 O << "%" << RI.get(MO.getReg()).Name;
466 O << "%reg" << MO.getReg();
469 case MachineOperand::MO_SignExtendedImmed:
470 case MachineOperand::MO_UnextendedImmed:
471 O << (int)MO.getImmedValue();
473 case MachineOperand::MO_PCRelativeDisp: {
474 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
475 assert (i != NumberForBB.end()
476 && "Could not find a BB in the NumberForBB map!");
477 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
480 case MachineOperand::MO_GlobalAddress:
481 if (!elideOffsetKeyword)
483 O << Mang->getValueName(MO.getGlobal());
485 case MachineOperand::MO_ExternalSymbol:
486 O << MO.getSymbolName();
489 O << "<unknown operand type>"; return;
493 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
494 switch (Desc.TSFlags & X86II::ArgMask) {
495 default: assert(0 && "Unknown arg size!");
496 case X86II::Arg8: return "BYTE PTR";
497 case X86II::Arg16: return "WORD PTR";
498 case X86II::Arg32: return "DWORD PTR";
499 case X86II::Arg64: return "QWORD PTR";
500 case X86II::ArgF32: return "DWORD PTR";
501 case X86II::ArgF64: return "QWORD PTR";
502 case X86II::ArgF80: return "XWORD PTR";
506 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
507 assert(isMem(MI, Op) && "Invalid memory reference!");
509 if (MI->getOperand(Op).isFrameIndex()) {
510 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
511 if (MI->getOperand(Op+3).getImmedValue())
512 O << " + " << MI->getOperand(Op+3).getImmedValue();
515 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
516 O << "[.CPI" << CurrentFnName << "_"
517 << MI->getOperand(Op).getConstantPoolIndex();
518 if (MI->getOperand(Op+3).getImmedValue())
519 O << " + " << MI->getOperand(Op+3).getImmedValue();
524 const MachineOperand &BaseReg = MI->getOperand(Op);
525 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
526 const MachineOperand &IndexReg = MI->getOperand(Op+2);
527 int DispVal = MI->getOperand(Op+3).getImmedValue();
530 bool NeedPlus = false;
531 if (BaseReg.getReg()) {
536 if (IndexReg.getReg()) {
537 if (NeedPlus) O << " + ";
539 O << ScaleVal << "*";
557 /// checkImplUses - Emit the implicit-use registers for the
558 /// instruction described by DESC, if its PrintImplUses flag is set.
560 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
561 const MRegisterInfo &RI = *TM.getRegisterInfo();
562 if (Desc.TSFlags & X86II::PrintImplUses) {
563 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
564 // Bug Workaround: See note in Printer::doInitialization about %.
565 O << ", %" << RI.get(*p).Name;
570 /// printMachineInstruction -- Print out a single X86 LLVM instruction
571 /// MI in Intel syntax to the current output stream.
573 void Printer::printMachineInstruction(const MachineInstr *MI) {
574 unsigned Opcode = MI->getOpcode();
575 const TargetInstrInfo &TII = TM.getInstrInfo();
576 const TargetInstrDescriptor &Desc = TII.get(Opcode);
579 switch (Desc.TSFlags & X86II::FormMask) {
581 // Print pseudo-instructions as comments; either they should have been
582 // turned into real instructions by now, or they don't need to be
583 // seen by the assembler (e.g., IMPLICIT_USEs.)
585 if (Opcode == X86::PHI) {
586 printOp(MI->getOperand(0));
588 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
589 if (i != 1) O << ", ";
591 printOp(MI->getOperand(i));
593 printOp(MI->getOperand(i+1));
598 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
599 MI->getOperand(0).opIsDefAndUse())) {
600 printOp(MI->getOperand(0));
604 O << TII.getName(MI->getOpcode());
606 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
608 if (MI->getOperand(i).opIsDefOnly() ||
609 MI->getOperand(i).opIsDefAndUse()) O << "*";
610 printOp(MI->getOperand(i));
611 if (MI->getOperand(i).opIsDefOnly() ||
612 MI->getOperand(i).opIsDefAndUse()) O << "*";
619 // The accepted forms of Raw instructions are:
620 // 1. nop - No operand required
621 // 2. jmp foo - PC relative displacement operand
622 // 3. call bar - GlobalAddress Operand or External Symbol Operand
624 assert(MI->getNumOperands() == 0 ||
625 (MI->getNumOperands() == 1 &&
626 (MI->getOperand(0).isPCRelativeDisp() ||
627 MI->getOperand(0).isGlobalAddress() ||
628 MI->getOperand(0).isExternalSymbol())) &&
629 "Illegal raw instruction!");
630 O << TII.getName(MI->getOpcode()) << " ";
632 if (MI->getNumOperands() == 1) {
633 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
638 case X86II::AddRegFrm: {
639 // There are currently two forms of acceptable AddRegFrm instructions.
640 // Either the instruction JUST takes a single register (like inc, dec, etc),
641 // or it takes a register and an immediate of the same size as the register
642 // (move immediate f.e.). Note that this immediate value might be stored as
643 // an LLVM value, to represent, for example, loading the address of a global
644 // into a register. The initial register might be duplicated if this is a
645 // M_2_ADDR_REG instruction
647 assert(MI->getOperand(0).isRegister() &&
648 (MI->getNumOperands() == 1 ||
649 (MI->getNumOperands() == 2 &&
650 (MI->getOperand(1).getVRegValueOrNull() ||
651 MI->getOperand(1).isImmediate() ||
652 MI->getOperand(1).isRegister() ||
653 MI->getOperand(1).isGlobalAddress() ||
654 MI->getOperand(1).isExternalSymbol()))) &&
655 "Illegal form for AddRegFrm instruction!");
657 unsigned Reg = MI->getOperand(0).getReg();
659 O << TII.getName(MI->getOpCode()) << " ";
660 printOp(MI->getOperand(0));
661 if (MI->getNumOperands() == 2 &&
662 (!MI->getOperand(1).isRegister() ||
663 MI->getOperand(1).getVRegValueOrNull() ||
664 MI->getOperand(1).isGlobalAddress() ||
665 MI->getOperand(1).isExternalSymbol())) {
667 printOp(MI->getOperand(1));
673 case X86II::MRMDestReg: {
674 // There are two acceptable forms of MRMDestReg instructions, those with 2,
677 // 2 Operands: this is for things like mov that do not read a second input
679 // 3 Operands: in this form, the first two registers (the destination, and
680 // the first operand) should be the same, post register allocation. The 3rd
681 // operand is an additional input. This should be for things like add
684 // 4 Operands: This form is for instructions which are 3 operands forms, but
685 // have a constant argument as well.
687 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
688 assert(MI->getOperand(0).isRegister() &&
689 (MI->getNumOperands() == 2 ||
690 (isTwoAddr && MI->getOperand(1).isRegister() &&
691 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
692 (MI->getNumOperands() == 3 ||
693 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
694 && "Bad format for MRMDestReg!");
696 O << TII.getName(MI->getOpCode()) << " ";
697 printOp(MI->getOperand(0));
699 printOp(MI->getOperand(1+isTwoAddr));
700 if (MI->getNumOperands() == 4) {
702 printOp(MI->getOperand(3));
708 case X86II::MRMDestMem: {
709 // These instructions are the same as MRMDestReg, but instead of having a
710 // register reference for the mod/rm field, it's a memory reference.
712 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
713 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
715 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
716 printMemReference(MI, 0);
718 printOp(MI->getOperand(4));
723 case X86II::MRMSrcReg: {
724 // There are three forms that are acceptable for MRMSrcReg instructions,
725 // those with 3 and 2 operands:
727 // 3 Operands: in this form, the last register (the second input) is the
728 // ModR/M input. The first two operands should be the same, post register
729 // allocation. This is for things like: add r32, r/m32
731 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
732 // instructions like the IMULri instructions.
734 // 2 Operands: this is for things like mov that do not read a second input
736 assert(MI->getOperand(0).isRegister() &&
737 MI->getOperand(1).isRegister() &&
738 (MI->getNumOperands() == 2 ||
739 (MI->getNumOperands() == 3 &&
740 (MI->getOperand(2).isRegister() ||
741 MI->getOperand(2).isImmediate())))
742 && "Bad format for MRMSrcReg!");
743 if (MI->getNumOperands() == 3 &&
744 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
747 O << TII.getName(MI->getOpCode()) << " ";
748 printOp(MI->getOperand(0));
750 // If this is IMULri* instructions, print the non-two-address operand.
751 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
753 printOp(MI->getOperand(1));
757 printOp(MI->getOperand(MI->getNumOperands()-1));
762 case X86II::MRMSrcMem: {
763 // These instructions are the same as MRMSrcReg, but instead of having a
764 // register reference for the mod/rm field, it's a memory reference.
766 assert(MI->getOperand(0).isRegister() &&
767 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
768 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
770 && "Bad format for MRMDestReg!");
771 if (MI->getNumOperands() == 2+4 &&
772 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
775 O << TII.getName(MI->getOpCode()) << " ";
776 printOp(MI->getOperand(0));
777 O << ", " << sizePtr(Desc) << " ";
778 printMemReference(MI, MI->getNumOperands()-4);
783 case X86II::MRMS0r: case X86II::MRMS1r:
784 case X86II::MRMS2r: case X86II::MRMS3r:
785 case X86II::MRMS4r: case X86II::MRMS5r:
786 case X86II::MRMS6r: case X86II::MRMS7r: {
787 // In this form, the following are valid formats:
789 // 2. cmp reg, immediate
790 // 2. shl rdest, rinput <implicit CL or 1>
791 // 3. sbb rdest, rinput, immediate [rdest = rinput]
793 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
794 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
795 assert((MI->getNumOperands() != 2 ||
796 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
797 "Bad MRMSxR format!");
798 assert((MI->getNumOperands() < 3 ||
799 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
800 "Bad MRMSxR format!");
802 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
803 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
806 O << TII.getName(MI->getOpCode()) << " ";
807 printOp(MI->getOperand(0));
808 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
810 printOp(MI->getOperand(MI->getNumOperands()-1));
818 case X86II::MRMS0m: case X86II::MRMS1m:
819 case X86II::MRMS2m: case X86II::MRMS3m:
820 case X86II::MRMS4m: case X86II::MRMS5m:
821 case X86II::MRMS6m: case X86II::MRMS7m: {
822 // In this form, the following are valid formats:
824 // 2. cmp [m], immediate
825 // 2. shl [m], rinput <implicit CL or 1>
826 // 3. sbb [m], immediate
828 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
829 isMem(MI, 0) && "Bad MRMSxM format!");
830 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
831 "Bad MRMSxM format!");
832 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
833 // is misassembled by gas in intel_syntax mode as its 32-bit
834 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
835 // opcode bytes instead of the instruction.
836 if (MI->getOpCode() == X86::FSTPr80) {
837 if ((MI->getOperand(0).getReg() == X86::ESP)
838 && (MI->getOperand(1).getImmedValue() == 1)) {
839 int DispVal = MI->getOperand(3).getImmedValue();
840 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
841 unsigned int val = (unsigned int) DispVal;
842 O << ".byte 0xdb, 0xbc, 0x24\n\t";
843 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
844 } else { // 1 byte disp.
845 unsigned char val = (unsigned char) DispVal;
846 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
847 << std::dec << "\t# ";
851 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
852 // misassembled by gas in intel_syntax mode as its 32-bit
853 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
854 // opcode bytes instead of the instruction.
855 if (MI->getOpCode() == X86::FLDr80) {
856 if ((MI->getOperand(0).getReg() == X86::ESP)
857 && (MI->getOperand(1).getImmedValue() == 1)) {
858 int DispVal = MI->getOperand(3).getImmedValue();
859 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
860 unsigned int val = (unsigned int) DispVal;
861 O << ".byte 0xdb, 0xac, 0x24\n\t";
862 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
863 } else { // 1 byte disp.
864 unsigned char val = (unsigned char) DispVal;
865 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
866 << std::dec << "\t# ";
870 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
871 // invalid opcode, saying "64 bit operations are only supported in
872 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
873 // [...]", which is wrong. Workaround: Output the raw opcode bytes
874 // instead of the instruction.
875 if (MI->getOpCode() == X86::FILDr64) {
876 if ((MI->getOperand(0).getReg() == X86::ESP)
877 && (MI->getOperand(1).getImmedValue() == 1)) {
878 int DispVal = MI->getOperand(3).getImmedValue();
879 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
880 unsigned int val = (unsigned int) DispVal;
881 O << ".byte 0xdf, 0xac, 0x24\n\t";
882 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
883 } else { // 1 byte disp.
884 unsigned char val = (unsigned char) DispVal;
885 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
886 << std::dec << "\t# ";
890 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
891 // an invalid opcode, saying "64 bit operations are only
892 // supported in 64 bit modes." libopcodes disassembles it as
893 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
894 // "fistpll DWORD PTR " instead, which is what libopcodes is
896 if (MI->getOpCode() == X86::FISTPr64) {
897 O << "fistpll DWORD PTR ";
898 printMemReference(MI, 0);
899 if (MI->getNumOperands() == 5) {
901 printOp(MI->getOperand(4));
906 O << TII.getName(MI->getOpCode()) << " ";
907 O << sizePtr(Desc) << " ";
908 printMemReference(MI, 0);
909 if (MI->getNumOperands() == 5) {
911 printOp(MI->getOperand(4));
918 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
922 bool Printer::doInitialization(Module &M) {
923 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
925 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
926 // instruction as a reference to the register named sp, and if you try to
927 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
928 // before being looked up in the symbol table. This creates spurious
929 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
930 // mode, and decorate all register names with percent signs.
931 O << "\t.intel_syntax\n";
932 Mang = new Mangler(M, EmitCygwin);
933 return false; // success
936 // SwitchSection - Switch to the specified section of the executable if we are
937 // not already in it!
939 static void SwitchSection(std::ostream &OS, std::string &CurSection,
940 const char *NewSection) {
941 if (CurSection != NewSection) {
942 CurSection = NewSection;
943 if (!CurSection.empty())
944 OS << "\t" << NewSection << "\n";
948 bool Printer::doFinalization(Module &M) {
949 const TargetData &TD = TM.getTargetData();
950 std::string CurSection;
952 // Print out module-level global variables here.
953 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
954 if (I->hasInitializer()) { // External global require no code
956 std::string name = Mang->getValueName(I);
957 Constant *C = I->getInitializer();
958 unsigned Size = TD.getTypeSize(C->getType());
959 unsigned Align = TD.getTypeAlignment(C->getType());
961 if (C->isNullValue() &&
962 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
963 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
964 SwitchSection(O, CurSection, ".data");
965 if (I->hasInternalLinkage())
966 O << "\t.local " << name << "\n";
968 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
969 << "," << (unsigned)TD.getTypeAlignment(C->getType());
971 WriteAsOperand(O, I, true, true, &M);
974 switch (I->getLinkage()) {
975 case GlobalValue::LinkOnceLinkage:
976 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
977 // Nonnull linkonce -> weak
978 O << "\t.weak " << name << "\n";
979 SwitchSection(O, CurSection, "");
980 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
983 case GlobalValue::AppendingLinkage:
984 // FIXME: appending linkage variables should go into a section of
985 // their name or something. For now, just emit them as external.
986 case GlobalValue::ExternalLinkage:
987 // If external or appending, declare as a global symbol
988 O << "\t.globl " << name << "\n";
990 case GlobalValue::InternalLinkage:
991 if (C->isNullValue())
992 SwitchSection(O, CurSection, ".bss");
994 SwitchSection(O, CurSection, ".data");
998 O << "\t.align " << Align << "\n";
999 O << "\t.type " << name << ",@object\n";
1000 O << "\t.size " << name << "," << Size << "\n";
1001 O << name << ":\t\t\t\t# ";
1002 WriteAsOperand(O, I, true, true, &M);
1004 WriteAsOperand(O, C, false, false, &M);
1006 printConstantValueOnly(C);
1011 return false; // success