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/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Module.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Support/Mangler.h"
21 #include "Support/StringExtras.h"
22 #include "Support/CommandLine.h"
25 // FIXME: This should be automatically picked up by autoconf from the C
27 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
28 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
30 struct Printer : public MachineFunctionPass {
31 /// Output stream on which we're printing assembly code.
35 /// Target machine description which we query for reg. names, data
40 /// Name-mangler for global names.
44 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
46 /// We name each basic block in a Function with a unique number, so
47 /// that we can consistently refer to them later. This is cleared
48 /// at the beginning of each call to runOnMachineFunction().
50 typedef std::map<const Value *, unsigned> ValueMapTy;
51 ValueMapTy NumberForBB;
53 /// Cache of mangled name for current function. This is
54 /// recalculated at the beginning of each call to
55 /// runOnMachineFunction().
57 std::string CurrentFnName;
59 virtual const char *getPassName() const {
60 return "X86 Assembly Printer";
63 void checkImplUses (const TargetInstrDescriptor &Desc);
64 void printMachineInstruction(const MachineInstr *MI);
65 void printOp(const MachineOperand &MO,
66 bool elideOffsetKeyword = false);
67 void printMemReference(const MachineInstr *MI, unsigned Op);
68 void printConstantPool(MachineConstantPool *MCP);
69 bool runOnMachineFunction(MachineFunction &F);
70 std::string ConstantExprToString(const ConstantExpr* CE);
71 std::string valToExprString(const Value* V);
72 bool doInitialization(Module &M);
73 bool doFinalization(Module &M);
74 void printConstantValueOnly(const Constant* CV);
75 void printSingleConstantValue(const Constant* CV);
77 } // end of anonymous namespace
79 /// createX86CodePrinterPass - Returns a pass that prints the X86
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description. This should work
82 /// regardless of whether the function is in SSA form.
84 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
85 return new Printer(o, tm);
88 /// valToExprString - Helper function for ConstantExprToString().
89 /// Appends result to argument string S.
91 std::string Printer::valToExprString(const Value* V) {
94 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
95 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
96 S += std::string(CB == ConstantBool::True ? "1" : "0");
97 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
98 S += itostr(CI->getValue());
99 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
100 S += utostr(CI->getValue());
101 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
102 S += ftostr(CFP->getValue());
103 else if (isa<ConstantPointerNull>(CV))
105 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
106 S += valToExprString(CPR->getValue());
107 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
108 S += ConstantExprToString(CE);
111 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
112 S += Mang->getValueName(GV);
118 assert(0 && "Cannot convert value to string");
119 S += "<illegal-value>";
124 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
125 /// and return this as a string.
127 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
128 const TargetData &TD = TM.getTargetData();
129 switch(CE->getOpcode()) {
130 case Instruction::GetElementPtr:
131 { // generate a symbolic expression for the byte address
132 const Value* ptrVal = CE->getOperand(0);
133 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
134 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
135 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
137 return valToExprString(ptrVal);
140 case Instruction::Cast:
141 // Support only non-converting or widening casts for now, that is,
142 // ones that do not involve a change in value. This assertion is
143 // not a complete check.
145 Constant *Op = CE->getOperand(0);
146 const Type *OpTy = Op->getType(), *Ty = CE->getType();
147 assert(((isa<PointerType>(OpTy)
148 && (Ty == Type::LongTy || Ty == Type::ULongTy))
149 || (isa<PointerType>(Ty)
150 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
151 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
152 && (OpTy->isLosslesslyConvertibleTo(Ty))))
153 && "FIXME: Don't yet support this kind of constant cast expr");
154 return "(" + valToExprString(Op) + ")";
157 case Instruction::Add:
158 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
159 + valToExprString(CE->getOperand(1)) + ")";
162 assert(0 && "Unsupported operator in ConstantExprToString()");
167 /// printSingleConstantValue - Print a single constant value.
170 Printer::printSingleConstantValue(const Constant* CV)
172 assert(CV->getType() != Type::VoidTy &&
173 CV->getType() != Type::TypeTy &&
174 CV->getType() != Type::LabelTy &&
175 "Unexpected type for Constant");
177 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
178 && "Aggregate types should be handled outside this function");
180 const Type *type = CV->getType();
182 switch(type->getPrimitiveID())
184 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
187 case Type::UShortTyID: case Type::ShortTyID:
190 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
193 case Type::ULongTyID: case Type::LongTyID:
196 case Type::FloatTyID:
199 case Type::DoubleTyID:
202 case Type::ArrayTyID:
203 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
204 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
207 assert (0 && "Can't handle printing this type of array");
210 assert (0 && "Can't handle printing this type of thing");
215 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
217 // Constant expression built from operators, constants, and
219 O << ConstantExprToString(CE) << "\n";
221 else if (type->isPrimitiveType())
223 if (type->isFloatingPoint()) {
224 // FP Constants are printed as integer constants to avoid losing
226 double Val = cast<ConstantFP>(CV)->getValue();
227 if (type == Type::FloatTy) {
228 float FVal = (float)Val;
229 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
230 O << *(unsigned int*)ProxyPtr;
231 } else if (type == Type::DoubleTy) {
232 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
233 O << *(uint64_t*)ProxyPtr;
235 assert(0 && "Unknown floating point type!");
238 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
240 WriteAsOperand(O, CV, false, false) << "\n";
243 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
245 // This is a constant address for a global variable or method.
246 // Use the name of the variable or method as the address value.
247 O << Mang->getValueName(CPR->getValue()) << "\n";
249 else if (isa<ConstantPointerNull>(CV))
251 // Null pointer value
256 assert(0 && "Unknown elementary type for constant");
260 /// isStringCompatible - Can we treat the specified array as a string?
261 /// Only if it is an array of ubytes or non-negative sbytes.
263 static bool isStringCompatible(const ConstantArray *CVA) {
264 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
265 if (ETy == Type::UByteTy) return true;
266 if (ETy != Type::SByteTy) return false;
268 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
269 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
275 /// toOctal - Convert the low order bits of X into an octal digit.
277 static inline char toOctal(int X) {
281 /// getAsCString - Return the specified array as a C compatible
282 /// string, only if the predicate isStringCompatible is true.
284 static std::string getAsCString(const ConstantArray *CVA) {
285 assert(isStringCompatible(CVA) && "Array is not string compatible!");
288 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
290 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
291 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
295 } else if (C == '\\') {
297 } else if (isprint(C)) {
301 case '\b': Result += "\\b"; break;
302 case '\f': Result += "\\f"; break;
303 case '\n': Result += "\\n"; break;
304 case '\r': Result += "\\r"; break;
305 case '\t': Result += "\\t"; break;
308 Result += toOctal(C >> 6);
309 Result += toOctal(C >> 3);
310 Result += toOctal(C >> 0);
319 // Print a constant value or values (it may be an aggregate).
320 // Uses printSingleConstantValue() to print each individual value.
321 void Printer::printConstantValueOnly(const Constant *CV) {
322 const TargetData &TD = TM.getTargetData();
324 if (CV->isNullValue()) {
325 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
326 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
327 if (isStringCompatible(CVA)) {
328 // print the string alone and return
329 O << "\t.string\t" << getAsCString(CVA) << "\n";
330 } else { // Not a string. Print the values in successive locations
331 const std::vector<Use> &constValues = CVA->getValues();
332 for (unsigned i=0; i < constValues.size(); i++)
333 printConstantValueOnly(cast<Constant>(constValues[i].get()));
335 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
336 // Print the fields in successive locations. Pad to align if needed!
337 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
338 const std::vector<Use>& constValues = CVS->getValues();
339 unsigned sizeSoFar = 0;
340 for (unsigned i=0, N = constValues.size(); i < N; i++) {
341 const Constant* field = cast<Constant>(constValues[i].get());
343 // Check if padding is needed and insert one or more 0s.
344 unsigned fieldSize = TD.getTypeSize(field->getType());
345 unsigned padSize = ((i == N-1? cvsLayout->StructSize
346 : cvsLayout->MemberOffsets[i+1])
347 - cvsLayout->MemberOffsets[i]) - fieldSize;
348 sizeSoFar += fieldSize + padSize;
350 // Now print the actual field value
351 printConstantValueOnly(field);
353 // Insert the field padding unless it's zero bytes...
355 O << "\t.zero\t " << padSize << "\n";
357 assert(sizeSoFar == cvsLayout->StructSize &&
358 "Layout of constant struct may be incorrect!");
360 printSingleConstantValue(CV);
363 /// printConstantPool - Print to the current output stream assembly
364 /// representations of the constants in the constant pool MCP. This is
365 /// used to print out constants which have been "spilled to memory" by
366 /// the code generator.
368 void Printer::printConstantPool(MachineConstantPool *MCP) {
369 const std::vector<Constant*> &CP = MCP->getConstants();
370 const TargetData &TD = TM.getTargetData();
372 if (CP.empty()) return;
374 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
375 O << "\t.section .rodata\n";
376 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
378 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
380 printConstantValueOnly (CP[i]);
384 /// runOnMachineFunction - This uses the printMachineInstruction()
385 /// method to print assembly for each instruction.
387 bool Printer::runOnMachineFunction(MachineFunction &MF) {
388 // BBNumber is used here so that a given Printer will never give two
389 // BBs the same name. (If you have a better way, please let me know!)
390 static unsigned BBNumber = 0;
393 // What's my mangled name?
394 CurrentFnName = Mang->getValueName(MF.getFunction());
396 // Print out constants referenced by the function
397 printConstantPool(MF.getConstantPool());
399 // Print out labels for the function.
401 O << "\t.align 16\n";
402 O << "\t.globl\t" << CurrentFnName << "\n";
404 O << "\t.type\t" << CurrentFnName << ", @function\n";
405 O << CurrentFnName << ":\n";
407 // Number each basic block so that we can consistently refer to them
408 // in PC-relative references.
410 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
412 NumberForBB[I->getBasicBlock()] = BBNumber++;
415 // Print out code for the function.
416 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
418 // Print a label for the basic block.
419 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
420 << I->getBasicBlock()->getName() << "\n";
421 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
423 // Print the assembly for the instruction.
425 printMachineInstruction(*II);
429 // We didn't modify anything.
433 static bool isScale(const MachineOperand &MO) {
434 return MO.isImmediate() &&
435 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
436 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
439 static bool isMem(const MachineInstr *MI, unsigned Op) {
440 if (MI->getOperand(Op).isFrameIndex()) return true;
441 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
442 return Op+4 <= MI->getNumOperands() &&
443 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
444 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
449 void Printer::printOp(const MachineOperand &MO,
450 bool elideOffsetKeyword /* = false */) {
451 const MRegisterInfo &RI = *TM.getRegisterInfo();
452 switch (MO.getType()) {
453 case MachineOperand::MO_VirtualRegister:
454 if (Value *V = MO.getVRegValueOrNull()) {
455 O << "<" << V->getName() << ">";
459 case MachineOperand::MO_MachineRegister:
460 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
461 // Bug Workaround: See note in Printer::doInitialization about %.
462 O << "%" << RI.get(MO.getReg()).Name;
464 O << "%reg" << MO.getReg();
467 case MachineOperand::MO_SignExtendedImmed:
468 case MachineOperand::MO_UnextendedImmed:
469 O << (int)MO.getImmedValue();
471 case MachineOperand::MO_PCRelativeDisp: {
472 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
473 assert (i != NumberForBB.end()
474 && "Could not find a BB in the NumberForBB map!");
475 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
478 case MachineOperand::MO_GlobalAddress:
479 if (!elideOffsetKeyword)
481 O << Mang->getValueName(MO.getGlobal());
483 case MachineOperand::MO_ExternalSymbol:
484 O << MO.getSymbolName();
487 O << "<unknown operand type>"; return;
491 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
492 switch (Desc.TSFlags & X86II::ArgMask) {
493 default: assert(0 && "Unknown arg size!");
494 case X86II::Arg8: return "BYTE PTR";
495 case X86II::Arg16: return "WORD PTR";
496 case X86II::Arg32: return "DWORD PTR";
497 case X86II::Arg64: return "QWORD PTR";
498 case X86II::ArgF32: return "DWORD PTR";
499 case X86II::ArgF64: return "QWORD PTR";
500 case X86II::ArgF80: return "XWORD PTR";
504 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
505 assert(isMem(MI, Op) && "Invalid memory reference!");
507 if (MI->getOperand(Op).isFrameIndex()) {
508 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
509 if (MI->getOperand(Op+3).getImmedValue())
510 O << " + " << MI->getOperand(Op+3).getImmedValue();
513 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
514 O << "[.CPI" << CurrentFnName << "_"
515 << MI->getOperand(Op).getConstantPoolIndex();
516 if (MI->getOperand(Op+3).getImmedValue())
517 O << " + " << MI->getOperand(Op+3).getImmedValue();
522 const MachineOperand &BaseReg = MI->getOperand(Op);
523 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
524 const MachineOperand &IndexReg = MI->getOperand(Op+2);
525 int DispVal = MI->getOperand(Op+3).getImmedValue();
528 bool NeedPlus = false;
529 if (BaseReg.getReg()) {
534 if (IndexReg.getReg()) {
535 if (NeedPlus) O << " + ";
537 O << ScaleVal << "*";
555 /// checkImplUses - Emit the implicit-use registers for the
556 /// instruction described by DESC, if its PrintImplUses flag is set.
558 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
559 const MRegisterInfo &RI = *TM.getRegisterInfo();
560 if (Desc.TSFlags & X86II::PrintImplUses) {
561 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
562 // Bug Workaround: See note in Printer::doInitialization about %.
563 O << ", %" << RI.get(*p).Name;
568 /// printMachineInstruction -- Print out a single X86 LLVM instruction
569 /// MI in Intel syntax to the current output stream.
571 void Printer::printMachineInstruction(const MachineInstr *MI) {
572 unsigned Opcode = MI->getOpcode();
573 const TargetInstrInfo &TII = TM.getInstrInfo();
574 const TargetInstrDescriptor &Desc = TII.get(Opcode);
576 switch (Desc.TSFlags & X86II::FormMask) {
578 // Print pseudo-instructions as comments; either they should have been
579 // turned into real instructions by now, or they don't need to be
580 // seen by the assembler (e.g., IMPLICIT_USEs.)
582 if (Opcode == X86::PHI) {
583 printOp(MI->getOperand(0));
585 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
586 if (i != 1) O << ", ";
588 printOp(MI->getOperand(i));
590 printOp(MI->getOperand(i+1));
595 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
596 MI->getOperand(0).opIsDefAndUse())) {
597 printOp(MI->getOperand(0));
601 O << TII.getName(MI->getOpcode());
603 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
605 if (MI->getOperand(i).opIsDefOnly() ||
606 MI->getOperand(i).opIsDefAndUse()) O << "*";
607 printOp(MI->getOperand(i));
608 if (MI->getOperand(i).opIsDefOnly() ||
609 MI->getOperand(i).opIsDefAndUse()) O << "*";
616 // The accepted forms of Raw instructions are:
617 // 1. nop - No operand required
618 // 2. jmp foo - PC relative displacement operand
619 // 3. call bar - GlobalAddress Operand or External Symbol Operand
621 assert(MI->getNumOperands() == 0 ||
622 (MI->getNumOperands() == 1 &&
623 (MI->getOperand(0).isPCRelativeDisp() ||
624 MI->getOperand(0).isGlobalAddress() ||
625 MI->getOperand(0).isExternalSymbol())) &&
626 "Illegal raw instruction!");
627 O << TII.getName(MI->getOpcode()) << " ";
629 if (MI->getNumOperands() == 1) {
630 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
635 case X86II::AddRegFrm: {
636 // There are currently two forms of acceptable AddRegFrm instructions.
637 // Either the instruction JUST takes a single register (like inc, dec, etc),
638 // or it takes a register and an immediate of the same size as the register
639 // (move immediate f.e.). Note that this immediate value might be stored as
640 // an LLVM value, to represent, for example, loading the address of a global
641 // into a register. The initial register might be duplicated if this is a
642 // M_2_ADDR_REG instruction
644 assert(MI->getOperand(0).isRegister() &&
645 (MI->getNumOperands() == 1 ||
646 (MI->getNumOperands() == 2 &&
647 (MI->getOperand(1).getVRegValueOrNull() ||
648 MI->getOperand(1).isImmediate() ||
649 MI->getOperand(1).isRegister() ||
650 MI->getOperand(1).isGlobalAddress() ||
651 MI->getOperand(1).isExternalSymbol()))) &&
652 "Illegal form for AddRegFrm instruction!");
654 unsigned Reg = MI->getOperand(0).getReg();
656 O << TII.getName(MI->getOpCode()) << " ";
657 printOp(MI->getOperand(0));
658 if (MI->getNumOperands() == 2 &&
659 (!MI->getOperand(1).isRegister() ||
660 MI->getOperand(1).getVRegValueOrNull() ||
661 MI->getOperand(1).isGlobalAddress() ||
662 MI->getOperand(1).isExternalSymbol())) {
664 printOp(MI->getOperand(1));
670 case X86II::MRMDestReg: {
671 // There are two acceptable forms of MRMDestReg instructions, those with 2,
674 // 2 Operands: this is for things like mov that do not read a second input
676 // 3 Operands: in this form, the first two registers (the destination, and
677 // the first operand) should be the same, post register allocation. The 3rd
678 // operand is an additional input. This should be for things like add
681 // 4 Operands: This form is for instructions which are 3 operands forms, but
682 // have a constant argument as well.
684 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
685 assert(MI->getOperand(0).isRegister() &&
686 (MI->getNumOperands() == 2 ||
687 (isTwoAddr && MI->getOperand(1).isRegister() &&
688 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
689 (MI->getNumOperands() == 3 ||
690 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
691 && "Bad format for MRMDestReg!");
693 O << TII.getName(MI->getOpCode()) << " ";
694 printOp(MI->getOperand(0));
696 printOp(MI->getOperand(1+isTwoAddr));
697 if (MI->getNumOperands() == 4) {
699 printOp(MI->getOperand(3));
705 case X86II::MRMDestMem: {
706 // These instructions are the same as MRMDestReg, but instead of having a
707 // register reference for the mod/rm field, it's a memory reference.
709 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
710 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
712 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
713 printMemReference(MI, 0);
715 printOp(MI->getOperand(4));
720 case X86II::MRMSrcReg: {
721 // There is a two forms that are acceptable for MRMSrcReg instructions,
722 // those with 3 and 2 operands:
724 // 3 Operands: in this form, the last register (the second input) is the
725 // ModR/M input. The first two operands should be the same, post register
726 // allocation. This is for things like: add r32, r/m32
728 // 2 Operands: this is for things like mov that do not read a second input
730 assert(MI->getOperand(0).isRegister() &&
731 MI->getOperand(1).isRegister() &&
732 (MI->getNumOperands() == 2 ||
733 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
734 && "Bad format for MRMSrcReg!");
735 if (MI->getNumOperands() == 3 &&
736 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
739 O << TII.getName(MI->getOpCode()) << " ";
740 printOp(MI->getOperand(0));
742 printOp(MI->getOperand(MI->getNumOperands()-1));
747 case X86II::MRMSrcMem: {
748 // These instructions are the same as MRMSrcReg, but instead of having a
749 // register reference for the mod/rm field, it's a memory reference.
751 assert(MI->getOperand(0).isRegister() &&
752 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
753 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
755 && "Bad format for MRMDestReg!");
756 if (MI->getNumOperands() == 2+4 &&
757 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
760 O << TII.getName(MI->getOpCode()) << " ";
761 printOp(MI->getOperand(0));
762 O << ", " << sizePtr(Desc) << " ";
763 printMemReference(MI, MI->getNumOperands()-4);
768 case X86II::MRMS0r: case X86II::MRMS1r:
769 case X86II::MRMS2r: case X86II::MRMS3r:
770 case X86II::MRMS4r: case X86II::MRMS5r:
771 case X86II::MRMS6r: case X86II::MRMS7r: {
772 // In this form, the following are valid formats:
774 // 2. cmp reg, immediate
775 // 2. shl rdest, rinput <implicit CL or 1>
776 // 3. sbb rdest, rinput, immediate [rdest = rinput]
778 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
779 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
780 assert((MI->getNumOperands() != 2 ||
781 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
782 "Bad MRMSxR format!");
783 assert((MI->getNumOperands() < 3 ||
784 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
785 "Bad MRMSxR format!");
787 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
788 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
791 O << TII.getName(MI->getOpCode()) << " ";
792 printOp(MI->getOperand(0));
793 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
795 printOp(MI->getOperand(MI->getNumOperands()-1));
803 case X86II::MRMS0m: case X86II::MRMS1m:
804 case X86II::MRMS2m: case X86II::MRMS3m:
805 case X86II::MRMS4m: case X86II::MRMS5m:
806 case X86II::MRMS6m: case X86II::MRMS7m: {
807 // In this form, the following are valid formats:
809 // 2. cmp [m], immediate
810 // 2. shl [m], rinput <implicit CL or 1>
811 // 3. sbb [m], immediate
813 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
814 isMem(MI, 0) && "Bad MRMSxM format!");
815 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
816 "Bad MRMSxM format!");
817 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
818 // is misassembled by gas in intel_syntax mode as its 32-bit
819 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
820 // opcode bytes instead of the instruction.
821 if (MI->getOpCode() == X86::FSTPr80) {
822 if ((MI->getOperand(0).getReg() == X86::ESP)
823 && (MI->getOperand(1).getImmedValue() == 1)) {
824 int DispVal = MI->getOperand(3).getImmedValue();
825 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
826 unsigned int val = (unsigned int) DispVal;
827 O << ".byte 0xdb, 0xbc, 0x24\n\t";
828 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
829 } else { // 1 byte disp.
830 unsigned char val = (unsigned char) DispVal;
831 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
832 << std::dec << "\t# ";
836 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
837 // misassembled by gas in intel_syntax mode as its 32-bit
838 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
839 // opcode bytes instead of the instruction.
840 if (MI->getOpCode() == X86::FLDr80) {
841 if ((MI->getOperand(0).getReg() == X86::ESP)
842 && (MI->getOperand(1).getImmedValue() == 1)) {
843 int DispVal = MI->getOperand(3).getImmedValue();
844 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
845 unsigned int val = (unsigned int) DispVal;
846 O << ".byte 0xdb, 0xac, 0x24\n\t";
847 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
848 } else { // 1 byte disp.
849 unsigned char val = (unsigned char) DispVal;
850 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
851 << std::dec << "\t# ";
855 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
856 // invalid opcode, saying "64 bit operations are only supported in
857 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
858 // [...]", which is wrong. Workaround: Output the raw opcode bytes
859 // instead of the instruction.
860 if (MI->getOpCode() == X86::FILDr64) {
861 if ((MI->getOperand(0).getReg() == X86::ESP)
862 && (MI->getOperand(1).getImmedValue() == 1)) {
863 int DispVal = MI->getOperand(3).getImmedValue();
864 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
865 unsigned int val = (unsigned int) DispVal;
866 O << ".byte 0xdf, 0xac, 0x24\n\t";
867 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
868 } else { // 1 byte disp.
869 unsigned char val = (unsigned char) DispVal;
870 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
871 << std::dec << "\t# ";
875 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
876 // an invalid opcode, saying "64 bit operations are only
877 // supported in 64 bit modes." libopcodes disassembles it as
878 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
879 // "fistpll DWORD PTR " instead, which is what libopcodes is
881 if (MI->getOpCode() == X86::FISTPr64) {
882 O << "fistpll DWORD PTR ";
883 printMemReference(MI, 0);
884 if (MI->getNumOperands() == 5) {
886 printOp(MI->getOperand(4));
891 O << TII.getName(MI->getOpCode()) << " ";
892 O << sizePtr(Desc) << " ";
893 printMemReference(MI, 0);
894 if (MI->getNumOperands() == 5) {
896 printOp(MI->getOperand(4));
903 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
907 bool Printer::doInitialization(Module &M) {
908 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
910 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
911 // instruction as a reference to the register named sp, and if you try to
912 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
913 // before being looked up in the symbol table. This creates spurious
914 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
915 // mode, and decorate all register names with percent signs.
916 O << "\t.intel_syntax\n";
917 Mang = new Mangler(M, EmitCygwin);
918 return false; // success
921 // SwitchSection - Switch to the specified section of the executable if we are
922 // not already in it!
924 static void SwitchSection(std::ostream &OS, std::string &CurSection,
925 const char *NewSection) {
926 if (CurSection != NewSection) {
927 CurSection = NewSection;
928 if (!CurSection.empty())
929 OS << "\t" << NewSection << "\n";
933 bool Printer::doFinalization(Module &M) {
934 const TargetData &TD = TM.getTargetData();
935 std::string CurSection;
937 // Print out module-level global variables here.
938 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
939 if (I->hasInitializer()) { // External global require no code
941 std::string name = Mang->getValueName(I);
942 Constant *C = I->getInitializer();
943 unsigned Size = TD.getTypeSize(C->getType());
944 unsigned Align = TD.getTypeAlignment(C->getType());
946 if (C->isNullValue() &&
947 (I->hasLinkOnceLinkage() || I->hasInternalLinkage())) {
948 SwitchSection(O, CurSection, ".data");
949 if (I->hasInternalLinkage())
950 O << "\t.local " << name << "\n";
952 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
953 << "," << (unsigned)TD.getTypeAlignment(C->getType());
955 WriteAsOperand(O, I, true, true, &M);
958 switch (I->getLinkage()) {
959 case GlobalValue::LinkOnceLinkage:
960 // Nonnull linkonce -> weak
961 O << "\t.weak " << name << "\n";
962 SwitchSection(O, CurSection, "");
963 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
966 case GlobalValue::AppendingLinkage:
967 // FIXME: appending linkage variables should go into a section of
968 // their name or something. For now, just emit them as external.
969 case GlobalValue::ExternalLinkage:
970 // If external or appending, declare as a global symbol
971 O << "\t.globl " << name << "\n";
973 case GlobalValue::InternalLinkage:
974 if (C->isNullValue())
975 SwitchSection(O, CurSection, ".bss");
977 SwitchSection(O, CurSection, ".data");
981 O << "\t.align " << Align << "\n";
982 O << "\t.type " << name << ",@object\n";
983 O << "\t.size " << name << "," << Size << "\n";
984 O << name << ":\t\t\t\t# ";
985 WriteAsOperand(O, I, true, true, &M);
987 WriteAsOperand(O, C, false, false, &M);
989 printConstantValueOnly(C);
994 return false; // success