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 bool doInitialization(Module &M);
81 bool doFinalization(Module &M);
82 void emitGlobalConstant(const Constant* CV);
83 void emitConstantValueOnly(const Constant *CV);
85 } // end of anonymous namespace
87 /// createX86CodePrinterPass - Returns a pass that prints the X86
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description. This should work
90 /// regardless of whether the function is in SSA form.
92 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
93 return new Printer(o, tm);
96 /// isStringCompatible - Can we treat the specified array as a string?
97 /// Only if it is an array of ubytes or non-negative sbytes.
99 static bool isStringCompatible(const ConstantArray *CVA) {
100 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
101 if (ETy == Type::UByteTy) return true;
102 if (ETy != Type::SByteTy) return false;
104 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
105 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
111 /// toOctal - Convert the low order bits of X into an octal digit.
113 static inline char toOctal(int X) {
117 /// getAsCString - Return the specified array as a C compatible
118 /// string, only if the predicate isStringCompatible is true.
120 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
121 assert(isStringCompatible(CVA) && "Array is not string compatible!");
124 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
125 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
129 } else if (C == '\\') {
131 } else if (isprint(C)) {
135 case '\b': O << "\\b"; break;
136 case '\f': O << "\\f"; break;
137 case '\n': O << "\\n"; break;
138 case '\r': O << "\\r"; break;
139 case '\t': O << "\\t"; break;
142 O << toOctal(C >> 6);
143 O << toOctal(C >> 3);
144 O << toOctal(C >> 0);
152 // Print out the specified constant, without a storage class. Only the
153 // constants valid in constant expressions can occur here.
154 void Printer::emitConstantValueOnly(const Constant *CV) {
155 if (CV->isNullValue())
157 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
158 assert(CB == ConstantBool::True);
160 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
162 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
164 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
165 // This is a constant address for a global variable or function. Use the
166 // name of the variable or function as the address value.
167 O << Mang->getValueName(CPR->getValue()) << "\n";
168 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
169 const TargetData &TD = TM.getTargetData();
170 switch(CE->getOpcode()) {
171 case Instruction::GetElementPtr: {
172 // generate a symbolic expression for the byte address
173 const Constant *ptrVal = CE->getOperand(0);
174 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
175 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
177 emitConstantValueOnly(ptrVal);
178 O << ") + " + Offset;
180 emitConstantValueOnly(ptrVal);
184 case Instruction::Cast: {
185 // Support only non-converting or widening casts for now, that is, ones
186 // that do not involve a change in value. This assertion is not a
188 Constant *Op = CE->getOperand(0);
189 const Type *OpTy = Op->getType(), *Ty = CE->getType();
190 assert(((isa<PointerType>(OpTy)
191 && (Ty == Type::LongTy || Ty == Type::ULongTy))
192 || (isa<PointerType>(Ty)
193 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
194 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
195 && (OpTy->isLosslesslyConvertibleTo(Ty))))
196 && "FIXME: Don't yet support this kind of constant cast expr");
198 emitConstantValueOnly(Op);
202 case Instruction::Add:
204 emitConstantValueOnly(CE->getOperand(0));
206 emitConstantValueOnly(CE->getOperand(1));
210 assert(0 && "Unsupported operator!");
213 assert(0 && "Unknown constant value!");
217 // Print a constant value or values, with the appropriate storage class as a
219 void Printer::emitGlobalConstant(const Constant *CV) {
220 const TargetData &TD = TM.getTargetData();
222 if (CV->isNullValue()) {
223 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
225 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
226 if (isStringCompatible(CVA)) {
228 printAsCString(O, CVA);
230 } else { // Not a string. Print the values in successive locations
231 const std::vector<Use> &constValues = CVA->getValues();
232 for (unsigned i=0; i < constValues.size(); i++)
233 emitGlobalConstant(cast<Constant>(constValues[i].get()));
236 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
237 // Print the fields in successive locations. Pad to align if needed!
238 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
239 const std::vector<Use>& constValues = CVS->getValues();
240 unsigned sizeSoFar = 0;
241 for (unsigned i=0, N = constValues.size(); i < N; i++) {
242 const Constant* field = cast<Constant>(constValues[i].get());
244 // Check if padding is needed and insert one or more 0s.
245 unsigned fieldSize = TD.getTypeSize(field->getType());
246 unsigned padSize = ((i == N-1? cvsLayout->StructSize
247 : cvsLayout->MemberOffsets[i+1])
248 - cvsLayout->MemberOffsets[i]) - fieldSize;
249 sizeSoFar += fieldSize + padSize;
251 // Now print the actual field value
252 emitGlobalConstant(field);
254 // Insert the field padding unless it's zero bytes...
256 O << "\t.zero\t " << padSize << "\n";
258 assert(sizeSoFar == cvsLayout->StructSize &&
259 "Layout of constant struct may be incorrect!");
261 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
262 // FP Constants are printed as integer constants to avoid losing
264 double Val = CFP->getValue();
265 switch (CFP->getType()->getPrimitiveID()) {
266 default: assert(0 && "Unknown floating point type!");
267 case Type::FloatTyID: {
268 union FU { // Abide by C TBAA rules
273 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
276 case Type::DoubleTyID: {
277 union DU { // Abide by C TBAA rules
282 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
288 const Type *type = CV->getType();
290 switch (type->getPrimitiveID()) {
291 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
294 case Type::UShortTyID: case Type::ShortTyID:
297 case Type::FloatTyID: case Type::PointerTyID:
298 case Type::UIntTyID: case Type::IntTyID:
301 case Type::DoubleTyID:
302 case Type::ULongTyID: case Type::LongTyID:
306 assert (0 && "Can't handle printing this type of thing");
310 emitConstantValueOnly(CV);
314 /// printConstantPool - Print to the current output stream assembly
315 /// representations of the constants in the constant pool MCP. This is
316 /// used to print out constants which have been "spilled to memory" by
317 /// the code generator.
319 void Printer::printConstantPool(MachineConstantPool *MCP) {
320 const std::vector<Constant*> &CP = MCP->getConstants();
321 const TargetData &TD = TM.getTargetData();
323 if (CP.empty()) return;
325 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
326 O << "\t.section .rodata\n";
327 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
329 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
331 emitGlobalConstant(CP[i]);
335 /// runOnMachineFunction - This uses the printMachineInstruction()
336 /// method to print assembly for each instruction.
338 bool Printer::runOnMachineFunction(MachineFunction &MF) {
339 // BBNumber is used here so that a given Printer will never give two
340 // BBs the same name. (If you have a better way, please let me know!)
341 static unsigned BBNumber = 0;
344 // What's my mangled name?
345 CurrentFnName = Mang->getValueName(MF.getFunction());
347 // Print out constants referenced by the function
348 printConstantPool(MF.getConstantPool());
350 // Print out labels for the function.
352 O << "\t.align 16\n";
353 O << "\t.globl\t" << CurrentFnName << "\n";
355 O << "\t.type\t" << CurrentFnName << ", @function\n";
356 O << CurrentFnName << ":\n";
358 // Number each basic block so that we can consistently refer to them
359 // in PC-relative references.
361 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
363 NumberForBB[I->getBasicBlock()] = BBNumber++;
366 // Print out code for the function.
367 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
369 // Print a label for the basic block.
370 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
371 << I->getBasicBlock()->getName() << "\n";
372 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
374 // Print the assembly for the instruction.
376 printMachineInstruction(*II);
380 // We didn't modify anything.
384 static bool isScale(const MachineOperand &MO) {
385 return MO.isImmediate() &&
386 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
387 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
390 static bool isMem(const MachineInstr *MI, unsigned Op) {
391 if (MI->getOperand(Op).isFrameIndex()) return true;
392 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
393 return Op+4 <= MI->getNumOperands() &&
394 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
395 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
400 void Printer::printOp(const MachineOperand &MO,
401 bool elideOffsetKeyword /* = false */) {
402 const MRegisterInfo &RI = *TM.getRegisterInfo();
403 switch (MO.getType()) {
404 case MachineOperand::MO_VirtualRegister:
405 if (Value *V = MO.getVRegValueOrNull()) {
406 O << "<" << V->getName() << ">";
410 case MachineOperand::MO_MachineRegister:
411 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
412 // Bug Workaround: See note in Printer::doInitialization about %.
413 O << "%" << RI.get(MO.getReg()).Name;
415 O << "%reg" << MO.getReg();
418 case MachineOperand::MO_SignExtendedImmed:
419 case MachineOperand::MO_UnextendedImmed:
420 O << (int)MO.getImmedValue();
422 case MachineOperand::MO_PCRelativeDisp: {
423 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
424 assert (i != NumberForBB.end()
425 && "Could not find a BB in the NumberForBB map!");
426 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
429 case MachineOperand::MO_GlobalAddress:
430 if (!elideOffsetKeyword)
432 O << Mang->getValueName(MO.getGlobal());
434 case MachineOperand::MO_ExternalSymbol:
435 O << MO.getSymbolName();
438 O << "<unknown operand type>"; return;
442 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
443 switch (Desc.TSFlags & X86II::ArgMask) {
444 default: assert(0 && "Unknown arg size!");
445 case X86II::Arg8: return "BYTE PTR";
446 case X86II::Arg16: return "WORD PTR";
447 case X86II::Arg32: return "DWORD PTR";
448 case X86II::Arg64: return "QWORD PTR";
449 case X86II::ArgF32: return "DWORD PTR";
450 case X86II::ArgF64: return "QWORD PTR";
451 case X86II::ArgF80: return "XWORD PTR";
455 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
456 assert(isMem(MI, Op) && "Invalid memory reference!");
458 if (MI->getOperand(Op).isFrameIndex()) {
459 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
460 if (MI->getOperand(Op+3).getImmedValue())
461 O << " + " << MI->getOperand(Op+3).getImmedValue();
464 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
465 O << "[.CPI" << CurrentFnName << "_"
466 << MI->getOperand(Op).getConstantPoolIndex();
467 if (MI->getOperand(Op+3).getImmedValue())
468 O << " + " << MI->getOperand(Op+3).getImmedValue();
473 const MachineOperand &BaseReg = MI->getOperand(Op);
474 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
475 const MachineOperand &IndexReg = MI->getOperand(Op+2);
476 int DispVal = MI->getOperand(Op+3).getImmedValue();
479 bool NeedPlus = false;
480 if (BaseReg.getReg()) {
485 if (IndexReg.getReg()) {
486 if (NeedPlus) O << " + ";
488 O << ScaleVal << "*";
506 /// checkImplUses - Emit the implicit-use registers for the
507 /// instruction described by DESC, if its PrintImplUses flag is set.
509 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
510 const MRegisterInfo &RI = *TM.getRegisterInfo();
511 if (Desc.TSFlags & X86II::PrintImplUses) {
512 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
513 // Bug Workaround: See note in Printer::doInitialization about %.
514 O << ", %" << RI.get(*p).Name;
519 /// printMachineInstruction -- Print out a single X86 LLVM instruction
520 /// MI in Intel syntax to the current output stream.
522 void Printer::printMachineInstruction(const MachineInstr *MI) {
523 unsigned Opcode = MI->getOpcode();
524 const TargetInstrInfo &TII = TM.getInstrInfo();
525 const TargetInstrDescriptor &Desc = TII.get(Opcode);
528 switch (Desc.TSFlags & X86II::FormMask) {
530 // Print pseudo-instructions as comments; either they should have been
531 // turned into real instructions by now, or they don't need to be
532 // seen by the assembler (e.g., IMPLICIT_USEs.)
534 if (Opcode == X86::PHI) {
535 printOp(MI->getOperand(0));
537 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
538 if (i != 1) O << ", ";
540 printOp(MI->getOperand(i));
542 printOp(MI->getOperand(i+1));
547 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
548 MI->getOperand(0).opIsDefAndUse())) {
549 printOp(MI->getOperand(0));
553 O << TII.getName(MI->getOpcode());
555 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
557 if (MI->getOperand(i).opIsDefOnly() ||
558 MI->getOperand(i).opIsDefAndUse()) O << "*";
559 printOp(MI->getOperand(i));
560 if (MI->getOperand(i).opIsDefOnly() ||
561 MI->getOperand(i).opIsDefAndUse()) O << "*";
568 // The accepted forms of Raw instructions are:
569 // 1. nop - No operand required
570 // 2. jmp foo - PC relative displacement operand
571 // 3. call bar - GlobalAddress Operand or External Symbol Operand
573 assert(MI->getNumOperands() == 0 ||
574 (MI->getNumOperands() == 1 &&
575 (MI->getOperand(0).isPCRelativeDisp() ||
576 MI->getOperand(0).isGlobalAddress() ||
577 MI->getOperand(0).isExternalSymbol())) &&
578 "Illegal raw instruction!");
579 O << TII.getName(MI->getOpcode()) << " ";
581 if (MI->getNumOperands() == 1) {
582 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
587 case X86II::AddRegFrm: {
588 // There are currently two forms of acceptable AddRegFrm instructions.
589 // Either the instruction JUST takes a single register (like inc, dec, etc),
590 // or it takes a register and an immediate of the same size as the register
591 // (move immediate f.e.). Note that this immediate value might be stored as
592 // an LLVM value, to represent, for example, loading the address of a global
593 // into a register. The initial register might be duplicated if this is a
594 // M_2_ADDR_REG instruction
596 assert(MI->getOperand(0).isRegister() &&
597 (MI->getNumOperands() == 1 ||
598 (MI->getNumOperands() == 2 &&
599 (MI->getOperand(1).getVRegValueOrNull() ||
600 MI->getOperand(1).isImmediate() ||
601 MI->getOperand(1).isRegister() ||
602 MI->getOperand(1).isGlobalAddress() ||
603 MI->getOperand(1).isExternalSymbol()))) &&
604 "Illegal form for AddRegFrm instruction!");
606 unsigned Reg = MI->getOperand(0).getReg();
608 O << TII.getName(MI->getOpCode()) << " ";
609 printOp(MI->getOperand(0));
610 if (MI->getNumOperands() == 2 &&
611 (!MI->getOperand(1).isRegister() ||
612 MI->getOperand(1).getVRegValueOrNull() ||
613 MI->getOperand(1).isGlobalAddress() ||
614 MI->getOperand(1).isExternalSymbol())) {
616 printOp(MI->getOperand(1));
622 case X86II::MRMDestReg: {
623 // There are two acceptable forms of MRMDestReg instructions, those with 2,
626 // 2 Operands: this is for things like mov that do not read a second input
628 // 3 Operands: in this form, the first two registers (the destination, and
629 // the first operand) should be the same, post register allocation. The 3rd
630 // operand is an additional input. This should be for things like add
633 // 4 Operands: This form is for instructions which are 3 operands forms, but
634 // have a constant argument as well.
636 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
637 assert(MI->getOperand(0).isRegister() &&
638 (MI->getNumOperands() == 2 ||
639 (isTwoAddr && MI->getOperand(1).isRegister() &&
640 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
641 (MI->getNumOperands() == 3 ||
642 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
643 && "Bad format for MRMDestReg!");
645 O << TII.getName(MI->getOpCode()) << " ";
646 printOp(MI->getOperand(0));
648 printOp(MI->getOperand(1+isTwoAddr));
649 if (MI->getNumOperands() == 4) {
651 printOp(MI->getOperand(3));
657 case X86II::MRMDestMem: {
658 // These instructions are the same as MRMDestReg, but instead of having a
659 // register reference for the mod/rm field, it's a memory reference.
661 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
662 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
664 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
665 printMemReference(MI, 0);
667 printOp(MI->getOperand(4));
672 case X86II::MRMSrcReg: {
673 // There are three forms that are acceptable for MRMSrcReg instructions,
674 // those with 3 and 2 operands:
676 // 3 Operands: in this form, the last register (the second input) is the
677 // ModR/M input. The first two operands should be the same, post register
678 // allocation. This is for things like: add r32, r/m32
680 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
681 // instructions like the IMULri instructions.
683 // 2 Operands: this is for things like mov that do not read a second input
685 assert(MI->getOperand(0).isRegister() &&
686 MI->getOperand(1).isRegister() &&
687 (MI->getNumOperands() == 2 ||
688 (MI->getNumOperands() == 3 &&
689 (MI->getOperand(2).isRegister() ||
690 MI->getOperand(2).isImmediate())))
691 && "Bad format for MRMSrcReg!");
692 if (MI->getNumOperands() == 3 &&
693 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
696 O << TII.getName(MI->getOpCode()) << " ";
697 printOp(MI->getOperand(0));
699 // If this is IMULri* instructions, print the non-two-address operand.
700 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
702 printOp(MI->getOperand(1));
706 printOp(MI->getOperand(MI->getNumOperands()-1));
711 case X86II::MRMSrcMem: {
712 // These instructions are the same as MRMSrcReg, but instead of having a
713 // register reference for the mod/rm field, it's a memory reference.
715 assert(MI->getOperand(0).isRegister() &&
716 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
717 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
719 && "Bad format for MRMDestReg!");
720 if (MI->getNumOperands() == 2+4 &&
721 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
724 O << TII.getName(MI->getOpCode()) << " ";
725 printOp(MI->getOperand(0));
726 O << ", " << sizePtr(Desc) << " ";
727 printMemReference(MI, MI->getNumOperands()-4);
732 case X86II::MRMS0r: case X86II::MRMS1r:
733 case X86II::MRMS2r: case X86II::MRMS3r:
734 case X86II::MRMS4r: case X86II::MRMS5r:
735 case X86II::MRMS6r: case X86II::MRMS7r: {
736 // In this form, the following are valid formats:
738 // 2. cmp reg, immediate
739 // 2. shl rdest, rinput <implicit CL or 1>
740 // 3. sbb rdest, rinput, immediate [rdest = rinput]
742 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
743 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
744 assert((MI->getNumOperands() != 2 ||
745 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
746 "Bad MRMSxR format!");
747 assert((MI->getNumOperands() < 3 ||
748 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
749 "Bad MRMSxR format!");
751 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
752 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
755 O << TII.getName(MI->getOpCode()) << " ";
756 printOp(MI->getOperand(0));
757 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
759 printOp(MI->getOperand(MI->getNumOperands()-1));
767 case X86II::MRMS0m: case X86II::MRMS1m:
768 case X86II::MRMS2m: case X86II::MRMS3m:
769 case X86II::MRMS4m: case X86II::MRMS5m:
770 case X86II::MRMS6m: case X86II::MRMS7m: {
771 // In this form, the following are valid formats:
773 // 2. cmp [m], immediate
774 // 2. shl [m], rinput <implicit CL or 1>
775 // 3. sbb [m], immediate
777 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
778 isMem(MI, 0) && "Bad MRMSxM format!");
779 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
780 "Bad MRMSxM format!");
781 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
782 // is misassembled by gas in intel_syntax mode as its 32-bit
783 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
784 // opcode bytes instead of the instruction.
785 if (MI->getOpCode() == X86::FSTPr80) {
786 if ((MI->getOperand(0).getReg() == X86::ESP)
787 && (MI->getOperand(1).getImmedValue() == 1)) {
788 int DispVal = MI->getOperand(3).getImmedValue();
789 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
790 unsigned int val = (unsigned int) DispVal;
791 O << ".byte 0xdb, 0xbc, 0x24\n\t";
792 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
793 } else { // 1 byte disp.
794 unsigned char val = (unsigned char) DispVal;
795 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
796 << std::dec << "\t# ";
800 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
801 // misassembled by gas in intel_syntax mode as its 32-bit
802 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
803 // opcode bytes instead of the instruction.
804 if (MI->getOpCode() == X86::FLDr80) {
805 if ((MI->getOperand(0).getReg() == X86::ESP)
806 && (MI->getOperand(1).getImmedValue() == 1)) {
807 int DispVal = MI->getOperand(3).getImmedValue();
808 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
809 unsigned int val = (unsigned int) DispVal;
810 O << ".byte 0xdb, 0xac, 0x24\n\t";
811 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
812 } else { // 1 byte disp.
813 unsigned char val = (unsigned char) DispVal;
814 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
815 << std::dec << "\t# ";
819 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
820 // invalid opcode, saying "64 bit operations are only supported in
821 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
822 // [...]", which is wrong. Workaround: Output the raw opcode bytes
823 // instead of the instruction.
824 if (MI->getOpCode() == X86::FILDr64) {
825 if ((MI->getOperand(0).getReg() == X86::ESP)
826 && (MI->getOperand(1).getImmedValue() == 1)) {
827 int DispVal = MI->getOperand(3).getImmedValue();
828 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
829 unsigned int val = (unsigned int) DispVal;
830 O << ".byte 0xdf, 0xac, 0x24\n\t";
831 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
832 } else { // 1 byte disp.
833 unsigned char val = (unsigned char) DispVal;
834 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
835 << std::dec << "\t# ";
839 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
840 // an invalid opcode, saying "64 bit operations are only
841 // supported in 64 bit modes." libopcodes disassembles it as
842 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
843 // "fistpll DWORD PTR " instead, which is what libopcodes is
845 if (MI->getOpCode() == X86::FISTPr64) {
846 O << "fistpll DWORD PTR ";
847 printMemReference(MI, 0);
848 if (MI->getNumOperands() == 5) {
850 printOp(MI->getOperand(4));
855 O << TII.getName(MI->getOpCode()) << " ";
856 O << sizePtr(Desc) << " ";
857 printMemReference(MI, 0);
858 if (MI->getNumOperands() == 5) {
860 printOp(MI->getOperand(4));
867 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
871 bool Printer::doInitialization(Module &M) {
872 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
874 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
875 // instruction as a reference to the register named sp, and if you try to
876 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
877 // before being looked up in the symbol table. This creates spurious
878 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
879 // mode, and decorate all register names with percent signs.
880 O << "\t.intel_syntax\n";
881 Mang = new Mangler(M, EmitCygwin);
882 return false; // success
885 // SwitchSection - Switch to the specified section of the executable if we are
886 // not already in it!
888 static void SwitchSection(std::ostream &OS, std::string &CurSection,
889 const char *NewSection) {
890 if (CurSection != NewSection) {
891 CurSection = NewSection;
892 if (!CurSection.empty())
893 OS << "\t" << NewSection << "\n";
897 bool Printer::doFinalization(Module &M) {
898 const TargetData &TD = TM.getTargetData();
899 std::string CurSection;
901 // Print out module-level global variables here.
902 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
903 if (I->hasInitializer()) { // External global require no code
905 std::string name = Mang->getValueName(I);
906 Constant *C = I->getInitializer();
907 unsigned Size = TD.getTypeSize(C->getType());
908 unsigned Align = TD.getTypeAlignment(C->getType());
910 if (C->isNullValue() &&
911 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
912 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
913 SwitchSection(O, CurSection, ".data");
914 if (I->hasInternalLinkage())
915 O << "\t.local " << name << "\n";
917 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
918 << "," << (unsigned)TD.getTypeAlignment(C->getType());
920 WriteAsOperand(O, I, true, true, &M);
923 switch (I->getLinkage()) {
924 case GlobalValue::LinkOnceLinkage:
925 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
926 // Nonnull linkonce -> weak
927 O << "\t.weak " << name << "\n";
928 SwitchSection(O, CurSection, "");
929 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
932 case GlobalValue::AppendingLinkage:
933 // FIXME: appending linkage variables should go into a section of
934 // their name or something. For now, just emit them as external.
935 case GlobalValue::ExternalLinkage:
936 // If external or appending, declare as a global symbol
937 O << "\t.globl " << name << "\n";
939 case GlobalValue::InternalLinkage:
940 if (C->isNullValue())
941 SwitchSection(O, CurSection, ".bss");
943 SwitchSection(O, CurSection, ".data");
947 O << "\t.align " << Align << "\n";
948 O << "\t.type " << name << ",@object\n";
949 O << "\t.size " << name << "," << Size << "\n";
950 O << name << ":\t\t\t\t# ";
951 WriteAsOperand(O, I, true, true, &M);
953 WriteAsOperand(O, C, false, false, &M);
955 emitGlobalConstant(C);
960 return false; // success