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"
35 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
37 // FIXME: This should be automatically picked up by autoconf from the C
39 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
40 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
42 struct Printer : public MachineFunctionPass {
43 /// Output stream on which we're printing assembly code.
47 /// Target machine description which we query for reg. names, data
52 /// Name-mangler for global names.
56 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
58 /// We name each basic block in a Function with a unique number, so
59 /// that we can consistently refer to them later. This is cleared
60 /// at the beginning of each call to runOnMachineFunction().
62 typedef std::map<const Value *, unsigned> ValueMapTy;
63 ValueMapTy NumberForBB;
65 /// Cache of mangled name for current function. This is
66 /// recalculated at the beginning of each call to
67 /// runOnMachineFunction().
69 std::string CurrentFnName;
71 virtual const char *getPassName() const {
72 return "X86 Assembly Printer";
75 void checkImplUses (const TargetInstrDescriptor &Desc);
76 void printMachineInstruction(const MachineInstr *MI);
77 void printOp(const MachineOperand &MO,
78 bool elideOffsetKeyword = false);
79 void printMemReference(const MachineInstr *MI, unsigned Op);
80 void printConstantPool(MachineConstantPool *MCP);
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
84 void emitGlobalConstant(const Constant* CV);
85 void emitConstantValueOnly(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 /// toOctal - Convert the low order bits of X into an octal digit.
100 static inline char toOctal(int X) {
104 /// getAsCString - Return the specified array as a C compatible
105 /// string, only if the predicate isStringCompatible is true.
107 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
108 assert(CVA->isString() && "Array is not string compatible!");
111 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
112 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
116 } else if (C == '\\') {
118 } else if (isprint(C)) {
122 case '\b': O << "\\b"; break;
123 case '\f': O << "\\f"; break;
124 case '\n': O << "\\n"; break;
125 case '\r': O << "\\r"; break;
126 case '\t': O << "\\t"; break;
129 O << toOctal(C >> 6);
130 O << toOctal(C >> 3);
131 O << toOctal(C >> 0);
139 // Print out the specified constant, without a storage class. Only the
140 // constants valid in constant expressions can occur here.
141 void Printer::emitConstantValueOnly(const Constant *CV) {
142 if (CV->isNullValue())
144 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
145 assert(CB == ConstantBool::True);
147 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
149 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
151 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
152 // This is a constant address for a global variable or function. Use the
153 // name of the variable or function as the address value.
154 O << Mang->getValueName(CPR->getValue());
155 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
156 const TargetData &TD = TM.getTargetData();
157 switch(CE->getOpcode()) {
158 case Instruction::GetElementPtr: {
159 // generate a symbolic expression for the byte address
160 const Constant *ptrVal = CE->getOperand(0);
161 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
162 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
164 emitConstantValueOnly(ptrVal);
165 O << ") + " << Offset;
167 emitConstantValueOnly(ptrVal);
171 case Instruction::Cast: {
172 // Support only non-converting or widening casts for now, that is, ones
173 // that do not involve a change in value. This assertion is really gross,
174 // and may not even be a complete check.
175 Constant *Op = CE->getOperand(0);
176 const Type *OpTy = Op->getType(), *Ty = CE->getType();
178 // Remember, kids, pointers on x86 can be losslessly converted back and
179 // forth into 32-bit or wider integers, regardless of signedness. :-P
180 assert(((isa<PointerType>(OpTy)
181 && (Ty == Type::LongTy || Ty == Type::ULongTy
182 || Ty == Type::IntTy || Ty == Type::UIntTy))
183 || (isa<PointerType>(Ty)
184 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
185 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
186 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
187 && OpTy->isLosslesslyConvertibleTo(Ty))))
188 && "FIXME: Don't yet support this kind of constant cast expr");
190 emitConstantValueOnly(Op);
194 case Instruction::Add:
196 emitConstantValueOnly(CE->getOperand(0));
198 emitConstantValueOnly(CE->getOperand(1));
202 assert(0 && "Unsupported operator!");
205 assert(0 && "Unknown constant value!");
209 // Print a constant value or values, with the appropriate storage class as a
211 void Printer::emitGlobalConstant(const Constant *CV) {
212 const TargetData &TD = TM.getTargetData();
214 if (CV->isNullValue()) {
215 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
217 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
218 if (CVA->isString()) {
220 printAsCString(O, CVA);
222 } else { // Not a string. Print the values in successive locations
223 const std::vector<Use> &constValues = CVA->getValues();
224 for (unsigned i=0; i < constValues.size(); i++)
225 emitGlobalConstant(cast<Constant>(constValues[i].get()));
228 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
229 // Print the fields in successive locations. Pad to align if needed!
230 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
231 const std::vector<Use>& constValues = CVS->getValues();
232 unsigned sizeSoFar = 0;
233 for (unsigned i=0, N = constValues.size(); i < N; i++) {
234 const Constant* field = cast<Constant>(constValues[i].get());
236 // Check if padding is needed and insert one or more 0s.
237 unsigned fieldSize = TD.getTypeSize(field->getType());
238 unsigned padSize = ((i == N-1? cvsLayout->StructSize
239 : cvsLayout->MemberOffsets[i+1])
240 - cvsLayout->MemberOffsets[i]) - fieldSize;
241 sizeSoFar += fieldSize + padSize;
243 // Now print the actual field value
244 emitGlobalConstant(field);
246 // Insert the field padding unless it's zero bytes...
248 O << "\t.zero\t " << padSize << "\n";
250 assert(sizeSoFar == cvsLayout->StructSize &&
251 "Layout of constant struct may be incorrect!");
253 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
254 // FP Constants are printed as integer constants to avoid losing
256 double Val = CFP->getValue();
257 switch (CFP->getType()->getPrimitiveID()) {
258 default: assert(0 && "Unknown floating point type!");
259 case Type::FloatTyID: {
260 union FU { // Abide by C TBAA rules
265 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
268 case Type::DoubleTyID: {
269 union DU { // Abide by C TBAA rules
274 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
280 const Type *type = CV->getType();
282 switch (type->getPrimitiveID()) {
283 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
286 case Type::UShortTyID: case Type::ShortTyID:
289 case Type::FloatTyID: case Type::PointerTyID:
290 case Type::UIntTyID: case Type::IntTyID:
293 case Type::DoubleTyID:
294 case Type::ULongTyID: case Type::LongTyID:
298 assert (0 && "Can't handle printing this type of thing");
302 emitConstantValueOnly(CV);
306 /// printConstantPool - Print to the current output stream assembly
307 /// representations of the constants in the constant pool MCP. This is
308 /// used to print out constants which have been "spilled to memory" by
309 /// the code generator.
311 void Printer::printConstantPool(MachineConstantPool *MCP) {
312 const std::vector<Constant*> &CP = MCP->getConstants();
313 const TargetData &TD = TM.getTargetData();
315 if (CP.empty()) return;
317 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
318 O << "\t.section .rodata\n";
319 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
321 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
323 emitGlobalConstant(CP[i]);
327 /// runOnMachineFunction - This uses the printMachineInstruction()
328 /// method to print assembly for each instruction.
330 bool Printer::runOnMachineFunction(MachineFunction &MF) {
331 // BBNumber is used here so that a given Printer will never give two
332 // BBs the same name. (If you have a better way, please let me know!)
333 static unsigned BBNumber = 0;
336 // What's my mangled name?
337 CurrentFnName = Mang->getValueName(MF.getFunction());
339 // Print out constants referenced by the function
340 printConstantPool(MF.getConstantPool());
342 // Print out labels for the function.
344 O << "\t.align 16\n";
345 O << "\t.globl\t" << CurrentFnName << "\n";
347 O << "\t.type\t" << CurrentFnName << ", @function\n";
348 O << CurrentFnName << ":\n";
350 // Number each basic block so that we can consistently refer to them
351 // in PC-relative references.
353 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
355 NumberForBB[I->getBasicBlock()] = BBNumber++;
358 // Print out code for the function.
359 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
361 // Print a label for the basic block.
362 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
363 << I->getBasicBlock()->getName() << "\n";
364 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
366 // Print the assembly for the instruction.
368 printMachineInstruction(*II);
372 // We didn't modify anything.
376 static bool isScale(const MachineOperand &MO) {
377 return MO.isImmediate() &&
378 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
379 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
382 static bool isMem(const MachineInstr *MI, unsigned Op) {
383 if (MI->getOperand(Op).isFrameIndex()) return true;
384 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
385 return Op+4 <= MI->getNumOperands() &&
386 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
387 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
392 void Printer::printOp(const MachineOperand &MO,
393 bool elideOffsetKeyword /* = false */) {
394 const MRegisterInfo &RI = *TM.getRegisterInfo();
395 switch (MO.getType()) {
396 case MachineOperand::MO_VirtualRegister:
397 if (Value *V = MO.getVRegValueOrNull()) {
398 O << "<" << V->getName() << ">";
402 case MachineOperand::MO_MachineRegister:
403 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
404 // Bug Workaround: See note in Printer::doInitialization about %.
405 O << "%" << RI.get(MO.getReg()).Name;
407 O << "%reg" << MO.getReg();
410 case MachineOperand::MO_SignExtendedImmed:
411 case MachineOperand::MO_UnextendedImmed:
412 O << (int)MO.getImmedValue();
414 case MachineOperand::MO_PCRelativeDisp: {
415 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
416 assert (i != NumberForBB.end()
417 && "Could not find a BB in the NumberForBB map!");
418 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
421 case MachineOperand::MO_GlobalAddress:
422 if (!elideOffsetKeyword)
424 O << Mang->getValueName(MO.getGlobal());
426 case MachineOperand::MO_ExternalSymbol:
427 O << MO.getSymbolName();
430 O << "<unknown operand type>"; return;
434 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
435 switch (Desc.TSFlags & X86II::ArgMask) {
436 default: assert(0 && "Unknown arg size!");
437 case X86II::Arg8: return "BYTE PTR";
438 case X86II::Arg16: return "WORD PTR";
439 case X86II::Arg32: return "DWORD PTR";
440 case X86II::Arg64: return "QWORD PTR";
441 case X86II::ArgF32: return "DWORD PTR";
442 case X86II::ArgF64: return "QWORD PTR";
443 case X86II::ArgF80: return "XWORD PTR";
447 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
448 assert(isMem(MI, Op) && "Invalid memory reference!");
450 if (MI->getOperand(Op).isFrameIndex()) {
451 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
452 if (MI->getOperand(Op+3).getImmedValue())
453 O << " + " << MI->getOperand(Op+3).getImmedValue();
456 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
457 O << "[.CPI" << CurrentFnName << "_"
458 << MI->getOperand(Op).getConstantPoolIndex();
459 if (MI->getOperand(Op+3).getImmedValue())
460 O << " + " << MI->getOperand(Op+3).getImmedValue();
465 const MachineOperand &BaseReg = MI->getOperand(Op);
466 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
467 const MachineOperand &IndexReg = MI->getOperand(Op+2);
468 int DispVal = MI->getOperand(Op+3).getImmedValue();
471 bool NeedPlus = false;
472 if (BaseReg.getReg()) {
477 if (IndexReg.getReg()) {
478 if (NeedPlus) O << " + ";
480 O << ScaleVal << "*";
498 /// checkImplUses - Emit the implicit-use registers for the
499 /// instruction described by DESC, if its PrintImplUses flag is set.
501 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
502 const MRegisterInfo &RI = *TM.getRegisterInfo();
503 if (Desc.TSFlags & X86II::PrintImplUses) {
504 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
505 // Bug Workaround: See note in Printer::doInitialization about %.
506 O << ", %" << RI.get(*p).Name;
511 /// printMachineInstruction -- Print out a single X86 LLVM instruction
512 /// MI in Intel syntax to the current output stream.
514 void Printer::printMachineInstruction(const MachineInstr *MI) {
515 unsigned Opcode = MI->getOpcode();
516 const TargetInstrInfo &TII = TM.getInstrInfo();
517 const TargetInstrDescriptor &Desc = TII.get(Opcode);
520 switch (Desc.TSFlags & X86II::FormMask) {
522 // Print pseudo-instructions as comments; either they should have been
523 // turned into real instructions by now, or they don't need to be
524 // seen by the assembler (e.g., IMPLICIT_USEs.)
526 if (Opcode == X86::PHI) {
527 printOp(MI->getOperand(0));
529 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
530 if (i != 1) O << ", ";
532 printOp(MI->getOperand(i));
534 printOp(MI->getOperand(i+1));
539 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
540 printOp(MI->getOperand(0));
544 O << TII.getName(MI->getOpcode());
546 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
548 if (MI->getOperand(i).isDef()) O << "*";
549 printOp(MI->getOperand(i));
550 if (MI->getOperand(i).isDef()) O << "*";
557 // The accepted forms of Raw instructions are:
558 // 1. nop - No operand required
559 // 2. jmp foo - PC relative displacement operand
560 // 3. call bar - GlobalAddress Operand or External Symbol Operand
562 assert(MI->getNumOperands() == 0 ||
563 (MI->getNumOperands() == 1 &&
564 (MI->getOperand(0).isPCRelativeDisp() ||
565 MI->getOperand(0).isGlobalAddress() ||
566 MI->getOperand(0).isExternalSymbol())) &&
567 "Illegal raw instruction!");
568 O << TII.getName(MI->getOpcode()) << " ";
570 if (MI->getNumOperands() == 1) {
571 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
576 case X86II::AddRegFrm: {
577 // There are currently two forms of acceptable AddRegFrm instructions.
578 // Either the instruction JUST takes a single register (like inc, dec, etc),
579 // or it takes a register and an immediate of the same size as the register
580 // (move immediate f.e.). Note that this immediate value might be stored as
581 // an LLVM value, to represent, for example, loading the address of a global
582 // into a register. The initial register might be duplicated if this is a
583 // M_2_ADDR_REG instruction
585 assert(MI->getOperand(0).isRegister() &&
586 (MI->getNumOperands() == 1 ||
587 (MI->getNumOperands() == 2 &&
588 (MI->getOperand(1).getVRegValueOrNull() ||
589 MI->getOperand(1).isImmediate() ||
590 MI->getOperand(1).isRegister() ||
591 MI->getOperand(1).isGlobalAddress() ||
592 MI->getOperand(1).isExternalSymbol()))) &&
593 "Illegal form for AddRegFrm instruction!");
595 unsigned Reg = MI->getOperand(0).getReg();
597 O << TII.getName(MI->getOpCode()) << " ";
598 printOp(MI->getOperand(0));
599 if (MI->getNumOperands() == 2 &&
600 (!MI->getOperand(1).isRegister() ||
601 MI->getOperand(1).getVRegValueOrNull() ||
602 MI->getOperand(1).isGlobalAddress() ||
603 MI->getOperand(1).isExternalSymbol())) {
605 printOp(MI->getOperand(1));
611 case X86II::MRMDestReg: {
612 // There are two acceptable forms of MRMDestReg instructions, those with 2,
615 // 2 Operands: this is for things like mov that do not read a second input
617 // 3 Operands: in this form, the first two registers (the destination, and
618 // the first operand) should be the same, post register allocation. The 3rd
619 // operand is an additional input. This should be for things like add
622 // 4 Operands: This form is for instructions which are 3 operands forms, but
623 // have a constant argument as well.
625 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
626 assert(MI->getOperand(0).isRegister() &&
627 (MI->getNumOperands() == 2 ||
628 (isTwoAddr && MI->getOperand(1).isRegister() &&
629 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
630 (MI->getNumOperands() == 3 ||
631 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
632 && "Bad format for MRMDestReg!");
634 O << TII.getName(MI->getOpCode()) << " ";
635 printOp(MI->getOperand(0));
637 printOp(MI->getOperand(1+isTwoAddr));
638 if (MI->getNumOperands() == 4) {
640 printOp(MI->getOperand(3));
646 case X86II::MRMDestMem: {
647 // These instructions are the same as MRMDestReg, but instead of having a
648 // register reference for the mod/rm field, it's a memory reference.
650 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
651 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
653 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
654 printMemReference(MI, 0);
656 printOp(MI->getOperand(4));
661 case X86II::MRMSrcReg: {
662 // There are three forms that are acceptable for MRMSrcReg instructions,
663 // those with 3 and 2 operands:
665 // 3 Operands: in this form, the last register (the second input) is the
666 // ModR/M input. The first two operands should be the same, post register
667 // allocation. This is for things like: add r32, r/m32
669 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
670 // instructions like the IMULri instructions.
672 // 2 Operands: this is for things like mov that do not read a second input
674 assert(MI->getOperand(0).isRegister() &&
675 MI->getOperand(1).isRegister() &&
676 (MI->getNumOperands() == 2 ||
677 (MI->getNumOperands() == 3 &&
678 (MI->getOperand(2).isRegister() ||
679 MI->getOperand(2).isImmediate())))
680 && "Bad format for MRMSrcReg!");
681 if (MI->getNumOperands() == 3 &&
682 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
685 O << TII.getName(MI->getOpCode()) << " ";
686 printOp(MI->getOperand(0));
688 // If this is IMULri* instructions, print the non-two-address operand.
689 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
691 printOp(MI->getOperand(1));
695 printOp(MI->getOperand(MI->getNumOperands()-1));
700 case X86II::MRMSrcMem: {
701 // These instructions are the same as MRMSrcReg, but instead of having a
702 // register reference for the mod/rm field, it's a memory reference.
704 assert(MI->getOperand(0).isRegister() &&
705 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
706 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
708 && "Bad format for MRMDestReg!");
709 if (MI->getNumOperands() == 2+4 &&
710 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
713 O << TII.getName(MI->getOpCode()) << " ";
714 printOp(MI->getOperand(0));
715 O << ", " << sizePtr(Desc) << " ";
716 printMemReference(MI, MI->getNumOperands()-4);
721 case X86II::MRMS0r: case X86II::MRMS1r:
722 case X86II::MRMS2r: case X86II::MRMS3r:
723 case X86II::MRMS4r: case X86II::MRMS5r:
724 case X86II::MRMS6r: case X86II::MRMS7r: {
725 // In this form, the following are valid formats:
727 // 2. cmp reg, immediate
728 // 2. shl rdest, rinput <implicit CL or 1>
729 // 3. sbb rdest, rinput, immediate [rdest = rinput]
731 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
732 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
733 assert((MI->getNumOperands() != 2 ||
734 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
735 "Bad MRMSxR format!");
736 assert((MI->getNumOperands() < 3 ||
737 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
738 "Bad MRMSxR format!");
740 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
741 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
744 O << TII.getName(MI->getOpCode()) << " ";
745 printOp(MI->getOperand(0));
746 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
748 printOp(MI->getOperand(MI->getNumOperands()-1));
756 case X86II::MRMS0m: case X86II::MRMS1m:
757 case X86II::MRMS2m: case X86II::MRMS3m:
758 case X86II::MRMS4m: case X86II::MRMS5m:
759 case X86II::MRMS6m: case X86II::MRMS7m: {
760 // In this form, the following are valid formats:
762 // 2. cmp [m], immediate
763 // 2. shl [m], rinput <implicit CL or 1>
764 // 3. sbb [m], immediate
766 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
767 isMem(MI, 0) && "Bad MRMSxM format!");
768 assert((MI->getNumOperands() != 5 ||
769 (MI->getOperand(4).isImmediate() ||
770 MI->getOperand(4).isGlobalAddress())) &&
771 "Bad MRMSxM format!");
773 const MachineOperand &Op3 = MI->getOperand(3);
775 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
776 // is misassembled by gas in intel_syntax mode as its 32-bit
777 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
778 // opcode bytes instead of the instruction.
779 if (MI->getOpCode() == X86::FSTPr80) {
780 if ((MI->getOperand(0).getReg() == X86::ESP)
781 && (MI->getOperand(1).getImmedValue() == 1)) {
782 if (Op3.isImmediate() &&
783 Op3.getImmedValue() >= -128 && Op3.getImmedValue() <= 127) {
785 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex
786 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
788 O << ".byte 0xdb, 0xbc, 0x24\n\t";
796 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
797 // misassembled by gas in intel_syntax mode as its 32-bit
798 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
799 // opcode bytes instead of the instruction.
800 if (MI->getOpCode() == X86::FLDr80 &&
801 MI->getOperand(0).getReg() == X86::ESP &&
802 MI->getOperand(1).getImmedValue() == 1) {
803 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
804 Op3.getImmedValue() <= 127) { // 1 byte displacement
805 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex
806 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
808 O << ".byte 0xdb, 0xac, 0x24\n\t";
815 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
816 // invalid opcode, saying "64 bit operations are only supported in
817 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
818 // [...]", which is wrong. Workaround: Output the raw opcode bytes
819 // instead of the instruction.
820 if (MI->getOpCode() == X86::FILDr64 &&
821 MI->getOperand(0).getReg() == X86::ESP &&
822 MI->getOperand(1).getImmedValue() == 1) {
823 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
824 Op3.getImmedValue() <= 127) { // 1 byte displacement
825 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex
826 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
828 O << ".byte 0xdf, 0xac, 0x24\n\t";
831 O << std::dec << "\t# ";
835 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
836 // an invalid opcode, saying "64 bit operations are only
837 // supported in 64 bit modes." libopcodes disassembles it as
838 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
839 // "fistpll DWORD PTR " instead, which is what libopcodes is
841 if (MI->getOpCode() == X86::FISTPr64) {
842 O << "fistpll DWORD PTR ";
843 printMemReference(MI, 0);
844 if (MI->getNumOperands() == 5) {
846 printOp(MI->getOperand(4));
851 O << TII.getName(MI->getOpCode()) << " ";
852 O << sizePtr(Desc) << " ";
853 printMemReference(MI, 0);
854 if (MI->getNumOperands() == 5) {
856 printOp(MI->getOperand(4));
863 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
867 bool Printer::doInitialization(Module &M) {
868 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
870 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
871 // instruction as a reference to the register named sp, and if you try to
872 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
873 // before being looked up in the symbol table. This creates spurious
874 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
875 // mode, and decorate all register names with percent signs.
876 O << "\t.intel_syntax\n";
877 Mang = new Mangler(M, EmitCygwin);
878 return false; // success
881 // SwitchSection - Switch to the specified section of the executable if we are
882 // not already in it!
884 static void SwitchSection(std::ostream &OS, std::string &CurSection,
885 const char *NewSection) {
886 if (CurSection != NewSection) {
887 CurSection = NewSection;
888 if (!CurSection.empty())
889 OS << "\t" << NewSection << "\n";
893 bool Printer::doFinalization(Module &M) {
894 const TargetData &TD = TM.getTargetData();
895 std::string CurSection;
897 // Print out module-level global variables here.
898 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
899 if (I->hasInitializer()) { // External global require no code
901 std::string name = Mang->getValueName(I);
902 Constant *C = I->getInitializer();
903 unsigned Size = TD.getTypeSize(C->getType());
904 unsigned Align = TD.getTypeAlignment(C->getType());
906 if (C->isNullValue() &&
907 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
908 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
909 SwitchSection(O, CurSection, ".data");
910 if (I->hasInternalLinkage())
911 O << "\t.local " << name << "\n";
913 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
914 << "," << (unsigned)TD.getTypeAlignment(C->getType());
916 WriteAsOperand(O, I, true, true, &M);
919 switch (I->getLinkage()) {
920 case GlobalValue::LinkOnceLinkage:
921 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
922 // Nonnull linkonce -> weak
923 O << "\t.weak " << name << "\n";
924 SwitchSection(O, CurSection, "");
925 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
928 case GlobalValue::AppendingLinkage:
929 // FIXME: appending linkage variables should go into a section of
930 // their name or something. For now, just emit them as external.
931 case GlobalValue::ExternalLinkage:
932 // If external or appending, declare as a global symbol
933 O << "\t.globl " << name << "\n";
935 case GlobalValue::InternalLinkage:
936 if (C->isNullValue())
937 SwitchSection(O, CurSection, ".bss");
939 SwitchSection(O, CurSection, ".data");
943 O << "\t.align " << Align << "\n";
944 O << "\t.type " << name << ",@object\n";
945 O << "\t.size " << name << "," << Size << "\n";
946 O << name << ":\t\t\t\t# ";
947 WriteAsOperand(O, I, true, true, &M);
949 WriteAsOperand(O, C, false, false, &M);
951 emitGlobalConstant(C);
956 return false; // success
959 } // End llvm namespace