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"
34 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
36 // FIXME: This should be automatically picked up by autoconf from the C
38 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
39 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
41 struct Printer : public MachineFunctionPass {
42 /// Output stream on which we're printing assembly code.
46 /// Target machine description which we query for reg. names, data
51 /// Name-mangler for global names.
55 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
57 /// We name each basic block in a Function with a unique number, so
58 /// that we can consistently refer to them later. This is cleared
59 /// at the beginning of each call to runOnMachineFunction().
61 typedef std::map<const Value *, unsigned> ValueMapTy;
62 ValueMapTy NumberForBB;
64 /// Cache of mangled name for current function. This is
65 /// recalculated at the beginning of each call to
66 /// runOnMachineFunction().
68 std::string CurrentFnName;
70 virtual const char *getPassName() const {
71 return "X86 Assembly Printer";
74 void checkImplUses (const TargetInstrDescriptor &Desc);
75 void printMachineInstruction(const MachineInstr *MI);
76 void printOp(const MachineOperand &MO,
77 bool elideOffsetKeyword = false);
78 void printMemReference(const MachineInstr *MI, unsigned Op);
79 void printConstantPool(MachineConstantPool *MCP);
80 bool runOnMachineFunction(MachineFunction &F);
81 bool doInitialization(Module &M);
82 bool doFinalization(Module &M);
83 void emitGlobalConstant(const Constant* CV);
84 void emitConstantValueOnly(const Constant *CV);
86 } // end of anonymous namespace
88 /// createX86CodePrinterPass - Returns a pass that prints the X86
89 /// assembly code for a MachineFunction to the given output stream,
90 /// using the given target machine description. This should work
91 /// regardless of whether the function is in SSA form.
93 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
94 return new Printer(o, tm);
97 /// toOctal - Convert the low order bits of X into an octal digit.
99 static inline char toOctal(int X) {
103 /// getAsCString - Return the specified array as a C compatible
104 /// string, only if the predicate isStringCompatible is true.
106 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
107 assert(CVA->isString() && "Array is not string compatible!");
110 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
111 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
115 } else if (C == '\\') {
117 } else if (isprint(C)) {
121 case '\b': O << "\\b"; break;
122 case '\f': O << "\\f"; break;
123 case '\n': O << "\\n"; break;
124 case '\r': O << "\\r"; break;
125 case '\t': O << "\\t"; break;
128 O << toOctal(C >> 6);
129 O << toOctal(C >> 3);
130 O << toOctal(C >> 0);
138 // Print out the specified constant, without a storage class. Only the
139 // constants valid in constant expressions can occur here.
140 void Printer::emitConstantValueOnly(const Constant *CV) {
141 if (CV->isNullValue())
143 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
144 assert(CB == ConstantBool::True);
146 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
147 if (((CI->getValue() << 32) >> 32) == CI->getValue())
150 O << (unsigned long long)CI->getValue();
151 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
153 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
154 // This is a constant address for a global variable or function. Use the
155 // name of the variable or function as the address value.
156 O << Mang->getValueName(CPR->getValue());
157 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
158 const TargetData &TD = TM.getTargetData();
159 switch(CE->getOpcode()) {
160 case Instruction::GetElementPtr: {
161 // generate a symbolic expression for the byte address
162 const Constant *ptrVal = CE->getOperand(0);
163 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
164 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
166 emitConstantValueOnly(ptrVal);
167 O << ") + " << Offset;
169 emitConstantValueOnly(ptrVal);
173 case Instruction::Cast: {
174 // Support only non-converting or widening casts for now, that is, ones
175 // that do not involve a change in value. This assertion is really gross,
176 // and may not even be a complete check.
177 Constant *Op = CE->getOperand(0);
178 const Type *OpTy = Op->getType(), *Ty = CE->getType();
180 // Remember, kids, pointers on x86 can be losslessly converted back and
181 // forth into 32-bit or wider integers, regardless of signedness. :-P
182 assert(((isa<PointerType>(OpTy)
183 && (Ty == Type::LongTy || Ty == Type::ULongTy
184 || Ty == Type::IntTy || Ty == Type::UIntTy))
185 || (isa<PointerType>(Ty)
186 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
187 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
188 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
189 && OpTy->isLosslesslyConvertibleTo(Ty))))
190 && "FIXME: Don't yet support this kind of constant cast expr");
192 emitConstantValueOnly(Op);
196 case Instruction::Add:
198 emitConstantValueOnly(CE->getOperand(0));
200 emitConstantValueOnly(CE->getOperand(1));
204 assert(0 && "Unsupported operator!");
207 assert(0 && "Unknown constant value!");
211 // Print a constant value or values, with the appropriate storage class as a
213 void Printer::emitGlobalConstant(const Constant *CV) {
214 const TargetData &TD = TM.getTargetData();
216 if (CV->isNullValue()) {
217 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
219 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
220 if (CVA->isString()) {
222 printAsCString(O, CVA);
224 } else { // Not a string. Print the values in successive locations
225 const std::vector<Use> &constValues = CVA->getValues();
226 for (unsigned i=0; i < constValues.size(); i++)
227 emitGlobalConstant(cast<Constant>(constValues[i].get()));
230 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
231 // Print the fields in successive locations. Pad to align if needed!
232 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
233 const std::vector<Use>& constValues = CVS->getValues();
234 unsigned sizeSoFar = 0;
235 for (unsigned i=0, N = constValues.size(); i < N; i++) {
236 const Constant* field = cast<Constant>(constValues[i].get());
238 // Check if padding is needed and insert one or more 0s.
239 unsigned fieldSize = TD.getTypeSize(field->getType());
240 unsigned padSize = ((i == N-1? cvsLayout->StructSize
241 : cvsLayout->MemberOffsets[i+1])
242 - cvsLayout->MemberOffsets[i]) - fieldSize;
243 sizeSoFar += fieldSize + padSize;
245 // Now print the actual field value
246 emitGlobalConstant(field);
248 // Insert the field padding unless it's zero bytes...
250 O << "\t.zero\t " << padSize << "\n";
252 assert(sizeSoFar == cvsLayout->StructSize &&
253 "Layout of constant struct may be incorrect!");
255 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
256 // FP Constants are printed as integer constants to avoid losing
258 double Val = CFP->getValue();
259 switch (CFP->getType()->getPrimitiveID()) {
260 default: assert(0 && "Unknown floating point type!");
261 case Type::FloatTyID: {
262 union FU { // Abide by C TBAA rules
267 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
270 case Type::DoubleTyID: {
271 union DU { // Abide by C TBAA rules
276 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
282 const Type *type = CV->getType();
284 switch (type->getPrimitiveID()) {
285 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
288 case Type::UShortTyID: case Type::ShortTyID:
291 case Type::FloatTyID: case Type::PointerTyID:
292 case Type::UIntTyID: case Type::IntTyID:
295 case Type::DoubleTyID:
296 case Type::ULongTyID: case Type::LongTyID:
300 assert (0 && "Can't handle printing this type of thing");
304 emitConstantValueOnly(CV);
308 /// printConstantPool - Print to the current output stream assembly
309 /// representations of the constants in the constant pool MCP. This is
310 /// used to print out constants which have been "spilled to memory" by
311 /// the code generator.
313 void Printer::printConstantPool(MachineConstantPool *MCP) {
314 const std::vector<Constant*> &CP = MCP->getConstants();
315 const TargetData &TD = TM.getTargetData();
317 if (CP.empty()) return;
319 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
320 O << "\t.section .rodata\n";
321 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
323 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
325 emitGlobalConstant(CP[i]);
329 /// runOnMachineFunction - This uses the printMachineInstruction()
330 /// method to print assembly for each instruction.
332 bool Printer::runOnMachineFunction(MachineFunction &MF) {
333 // BBNumber is used here so that a given Printer will never give two
334 // BBs the same name. (If you have a better way, please let me know!)
335 static unsigned BBNumber = 0;
338 // What's my mangled name?
339 CurrentFnName = Mang->getValueName(MF.getFunction());
341 // Print out constants referenced by the function
342 printConstantPool(MF.getConstantPool());
344 // Print out labels for the function.
346 O << "\t.align 16\n";
347 O << "\t.globl\t" << CurrentFnName << "\n";
349 O << "\t.type\t" << CurrentFnName << ", @function\n";
350 O << CurrentFnName << ":\n";
352 // Number each basic block so that we can consistently refer to them
353 // in PC-relative references.
355 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
357 NumberForBB[I->getBasicBlock()] = BBNumber++;
360 // Print out code for the function.
361 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
363 // Print a label for the basic block.
364 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
365 << I->getBasicBlock()->getName() << "\n";
366 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
368 // Print the assembly for the instruction.
370 printMachineInstruction(II);
374 // We didn't modify anything.
378 static bool isScale(const MachineOperand &MO) {
379 return MO.isImmediate() &&
380 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
381 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
384 static bool isMem(const MachineInstr *MI, unsigned Op) {
385 if (MI->getOperand(Op).isFrameIndex()) return true;
386 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
387 return Op+4 <= MI->getNumOperands() &&
388 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
389 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
394 void Printer::printOp(const MachineOperand &MO,
395 bool elideOffsetKeyword /* = false */) {
396 const MRegisterInfo &RI = *TM.getRegisterInfo();
397 switch (MO.getType()) {
398 case MachineOperand::MO_VirtualRegister:
399 if (Value *V = MO.getVRegValueOrNull()) {
400 O << "<" << V->getName() << ">";
404 case MachineOperand::MO_MachineRegister:
405 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
406 // Bug Workaround: See note in Printer::doInitialization about %.
407 O << "%" << RI.get(MO.getReg()).Name;
409 O << "%reg" << MO.getReg();
412 case MachineOperand::MO_SignExtendedImmed:
413 case MachineOperand::MO_UnextendedImmed:
414 O << (int)MO.getImmedValue();
416 case MachineOperand::MO_PCRelativeDisp: {
417 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
418 assert (i != NumberForBB.end()
419 && "Could not find a BB in the NumberForBB map!");
420 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
423 case MachineOperand::MO_GlobalAddress:
424 if (!elideOffsetKeyword)
426 O << Mang->getValueName(MO.getGlobal());
428 case MachineOperand::MO_ExternalSymbol:
429 O << MO.getSymbolName();
432 O << "<unknown operand type>"; return;
436 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
437 switch (Desc.TSFlags & X86II::ArgMask) {
438 default: assert(0 && "Unknown arg size!");
439 case X86II::Arg8: return "BYTE PTR";
440 case X86II::Arg16: return "WORD PTR";
441 case X86II::Arg32: return "DWORD PTR";
442 case X86II::Arg64: return "QWORD PTR";
443 case X86II::ArgF32: return "DWORD PTR";
444 case X86II::ArgF64: return "QWORD PTR";
445 case X86II::ArgF80: return "XWORD PTR";
449 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
450 assert(isMem(MI, Op) && "Invalid memory reference!");
452 if (MI->getOperand(Op).isFrameIndex()) {
453 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
454 if (MI->getOperand(Op+3).getImmedValue())
455 O << " + " << MI->getOperand(Op+3).getImmedValue();
458 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
459 O << "[.CPI" << CurrentFnName << "_"
460 << MI->getOperand(Op).getConstantPoolIndex();
461 if (MI->getOperand(Op+3).getImmedValue())
462 O << " + " << MI->getOperand(Op+3).getImmedValue();
467 const MachineOperand &BaseReg = MI->getOperand(Op);
468 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
469 const MachineOperand &IndexReg = MI->getOperand(Op+2);
470 int DispVal = MI->getOperand(Op+3).getImmedValue();
473 bool NeedPlus = false;
474 if (BaseReg.getReg()) {
479 if (IndexReg.getReg()) {
480 if (NeedPlus) O << " + ";
482 O << ScaleVal << "*";
500 /// checkImplUses - Emit the implicit-use registers for the
501 /// instruction described by DESC, if its PrintImplUses flag is set.
503 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
504 const MRegisterInfo &RI = *TM.getRegisterInfo();
505 if (Desc.TSFlags & X86II::PrintImplUses) {
506 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
507 // Bug Workaround: See note in Printer::doInitialization about %.
508 O << ", %" << RI.get(*p).Name;
513 /// printMachineInstruction -- Print out a single X86 LLVM instruction
514 /// MI in Intel syntax to the current output stream.
516 void Printer::printMachineInstruction(const MachineInstr *MI) {
517 unsigned Opcode = MI->getOpcode();
518 const TargetInstrInfo &TII = TM.getInstrInfo();
519 const TargetInstrDescriptor &Desc = TII.get(Opcode);
522 switch (Desc.TSFlags & X86II::FormMask) {
524 // Print pseudo-instructions as comments; either they should have been
525 // turned into real instructions by now, or they don't need to be
526 // seen by the assembler (e.g., IMPLICIT_USEs.)
528 if (Opcode == X86::PHI) {
529 printOp(MI->getOperand(0));
531 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
532 if (i != 1) O << ", ";
534 printOp(MI->getOperand(i));
536 printOp(MI->getOperand(i+1));
541 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
542 printOp(MI->getOperand(0));
546 O << TII.getName(MI->getOpcode());
548 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
550 if (MI->getOperand(i).isDef()) O << "*";
551 printOp(MI->getOperand(i));
552 if (MI->getOperand(i).isDef()) O << "*";
559 // The accepted forms of Raw instructions are:
560 // 1. nop - No operand required
561 // 2. jmp foo - PC relative displacement operand
562 // 3. call bar - GlobalAddress Operand or External Symbol Operand
564 assert(MI->getNumOperands() == 0 ||
565 (MI->getNumOperands() == 1 &&
566 (MI->getOperand(0).isPCRelativeDisp() ||
567 MI->getOperand(0).isGlobalAddress() ||
568 MI->getOperand(0).isExternalSymbol())) &&
569 "Illegal raw instruction!");
570 O << TII.getName(MI->getOpcode()) << " ";
572 if (MI->getNumOperands() == 1) {
573 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
578 case X86II::AddRegFrm: {
579 // There are currently two forms of acceptable AddRegFrm instructions.
580 // Either the instruction JUST takes a single register (like inc, dec, etc),
581 // or it takes a register and an immediate of the same size as the register
582 // (move immediate f.e.). Note that this immediate value might be stored as
583 // an LLVM value, to represent, for example, loading the address of a global
584 // into a register. The initial register might be duplicated if this is a
585 // M_2_ADDR_REG instruction
587 assert(MI->getOperand(0).isRegister() &&
588 (MI->getNumOperands() == 1 ||
589 (MI->getNumOperands() == 2 &&
590 (MI->getOperand(1).getVRegValueOrNull() ||
591 MI->getOperand(1).isImmediate() ||
592 MI->getOperand(1).isRegister() ||
593 MI->getOperand(1).isGlobalAddress() ||
594 MI->getOperand(1).isExternalSymbol()))) &&
595 "Illegal form for AddRegFrm instruction!");
597 unsigned Reg = MI->getOperand(0).getReg();
599 O << TII.getName(MI->getOpcode()) << " ";
600 printOp(MI->getOperand(0));
601 if (MI->getNumOperands() == 2 &&
602 (!MI->getOperand(1).isRegister() ||
603 MI->getOperand(1).getVRegValueOrNull() ||
604 MI->getOperand(1).isGlobalAddress() ||
605 MI->getOperand(1).isExternalSymbol())) {
607 printOp(MI->getOperand(1));
613 case X86II::MRMDestReg: {
614 // There are three forms of MRMDestReg instructions, those with 2
617 // 2 Operands: this is for things like mov that do not read a
620 // 2 Operands: two address instructions which def&use the first
621 // argument and use the second as input.
623 // 3 Operands: in this form, two address instructions are the same
624 // as in 2 but have a constant argument as well.
626 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
627 assert(MI->getOperand(0).isRegister() &&
628 (MI->getNumOperands() == 2 ||
629 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
630 && "Bad format for MRMDestReg!");
632 O << TII.getName(MI->getOpcode()) << " ";
633 printOp(MI->getOperand(0));
635 printOp(MI->getOperand(1));
636 if (MI->getNumOperands() == 3) {
638 printOp(MI->getOperand(2));
644 case X86II::MRMDestMem: {
645 // These instructions are the same as MRMDestReg, but instead of having a
646 // register reference for the mod/rm field, it's a memory reference.
648 assert(isMem(MI, 0) &&
649 (MI->getNumOperands() == 4+1 ||
650 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
651 && "Bad format for MRMDestMem!");
653 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
654 printMemReference(MI, 0);
656 printOp(MI->getOperand(4));
657 if (MI->getNumOperands() == 4+2) {
659 printOp(MI->getOperand(5));
665 case X86II::MRMSrcReg: {
666 // There are three forms that are acceptable for MRMSrcReg
667 // instructions, those with 2 or 3 operands:
669 // 2 Operands: this is for things like mov that do not read a
672 // 2 Operands: in this form, the last register is the ModR/M
673 // input. The first operand is a def&use. This is for things
674 // like: add r32, r/m32
676 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
677 // for instructions like the IMULrri instructions.
680 assert(MI->getOperand(0).isRegister() &&
681 MI->getOperand(1).isRegister() &&
682 (MI->getNumOperands() == 2 ||
683 (MI->getNumOperands() == 3 &&
684 (MI->getOperand(2).isImmediate())))
685 && "Bad format for MRMSrcReg!");
687 O << TII.getName(MI->getOpcode()) << " ";
688 printOp(MI->getOperand(0));
690 printOp(MI->getOperand(1));
691 if (MI->getNumOperands() == 3) {
693 printOp(MI->getOperand(2));
699 case X86II::MRMSrcMem: {
700 // These instructions are the same as MRMSrcReg, but instead of having a
701 // register reference for the mod/rm field, it's a memory reference.
703 assert(MI->getOperand(0).isRegister() &&
704 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
705 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
706 && "Bad format for MRMSrcMem!");
707 O << TII.getName(MI->getOpcode()) << " ";
708 printOp(MI->getOperand(0));
709 O << ", " << sizePtr(Desc) << " ";
710 printMemReference(MI, 1);
711 if (MI->getNumOperands() == 2+4) {
713 printOp(MI->getOperand(5));
719 case X86II::MRMS0r: case X86II::MRMS1r:
720 case X86II::MRMS2r: case X86II::MRMS3r:
721 case X86II::MRMS4r: case X86II::MRMS5r:
722 case X86II::MRMS6r: case X86II::MRMS7r: {
723 // In this form, the following are valid formats:
725 // 2. cmp reg, immediate
726 // 2. shl rdest, rinput <implicit CL or 1>
727 // 3. sbb rdest, rinput, immediate [rdest = rinput]
729 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
730 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
731 assert((MI->getNumOperands() != 2 ||
732 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
733 "Bad MRMSxR format!");
734 assert((MI->getNumOperands() < 3 ||
735 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
736 "Bad MRMSxR format!");
738 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
739 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
742 O << TII.getName(MI->getOpcode()) << " ";
743 printOp(MI->getOperand(0));
744 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
746 printOp(MI->getOperand(MI->getNumOperands()-1));
754 case X86II::MRMS0m: case X86II::MRMS1m:
755 case X86II::MRMS2m: case X86II::MRMS3m:
756 case X86II::MRMS4m: case X86II::MRMS5m:
757 case X86II::MRMS6m: case X86II::MRMS7m: {
758 // In this form, the following are valid formats:
760 // 2. cmp [m], immediate
761 // 2. shl [m], rinput <implicit CL or 1>
762 // 3. sbb [m], immediate
764 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
765 isMem(MI, 0) && "Bad MRMSxM format!");
766 assert((MI->getNumOperands() != 5 ||
767 (MI->getOperand(4).isImmediate() ||
768 MI->getOperand(4).isGlobalAddress())) &&
769 "Bad MRMSxM format!");
771 const MachineOperand &Op3 = MI->getOperand(3);
773 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
774 // is misassembled by gas in intel_syntax mode as its 32-bit
775 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
776 // opcode bytes instead of the instruction.
777 if (MI->getOpcode() == X86::FSTPr80) {
778 if ((MI->getOperand(0).getReg() == X86::ESP)
779 && (MI->getOperand(1).getImmedValue() == 1)) {
780 if (Op3.isImmediate() &&
781 Op3.getImmedValue() >= -128 && Op3.getImmedValue() <= 127) {
783 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex
784 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
786 O << ".byte 0xdb, 0xbc, 0x24\n\t";
794 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
795 // misassembled by gas in intel_syntax mode as its 32-bit
796 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
797 // opcode bytes instead of the instruction.
798 if (MI->getOpcode() == X86::FLDr80 &&
799 MI->getOperand(0).getReg() == X86::ESP &&
800 MI->getOperand(1).getImmedValue() == 1) {
801 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
802 Op3.getImmedValue() <= 127) { // 1 byte displacement
803 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex
804 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
806 O << ".byte 0xdb, 0xac, 0x24\n\t";
813 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
814 // invalid opcode, saying "64 bit operations are only supported in
815 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
816 // [...]", which is wrong. Workaround: Output the raw opcode bytes
817 // instead of the instruction.
818 if (MI->getOpcode() == X86::FILDr64 &&
819 MI->getOperand(0).getReg() == X86::ESP &&
820 MI->getOperand(1).getImmedValue() == 1) {
821 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
822 Op3.getImmedValue() <= 127) { // 1 byte displacement
823 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex
824 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
826 O << ".byte 0xdf, 0xac, 0x24\n\t";
829 O << std::dec << "\t# ";
833 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
834 // an invalid opcode, saying "64 bit operations are only
835 // supported in 64 bit modes." libopcodes disassembles it as
836 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
837 // "fistpll DWORD PTR " instead, which is what libopcodes is
839 if (MI->getOpcode() == X86::FISTPr64) {
840 O << "fistpll DWORD PTR ";
841 printMemReference(MI, 0);
842 if (MI->getNumOperands() == 5) {
844 printOp(MI->getOperand(4));
849 O << TII.getName(MI->getOpcode()) << " ";
850 O << sizePtr(Desc) << " ";
851 printMemReference(MI, 0);
852 if (MI->getNumOperands() == 5) {
854 printOp(MI->getOperand(4));
861 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
865 bool Printer::doInitialization(Module &M) {
866 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
868 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
869 // instruction as a reference to the register named sp, and if you try to
870 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
871 // before being looked up in the symbol table. This creates spurious
872 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
873 // mode, and decorate all register names with percent signs.
874 O << "\t.intel_syntax\n";
875 Mang = new Mangler(M, EmitCygwin);
876 return false; // success
879 // SwitchSection - Switch to the specified section of the executable if we are
880 // not already in it!
882 static void SwitchSection(std::ostream &OS, std::string &CurSection,
883 const char *NewSection) {
884 if (CurSection != NewSection) {
885 CurSection = NewSection;
886 if (!CurSection.empty())
887 OS << "\t" << NewSection << "\n";
891 bool Printer::doFinalization(Module &M) {
892 const TargetData &TD = TM.getTargetData();
893 std::string CurSection;
895 // Print out module-level global variables here.
896 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
897 if (I->hasInitializer()) { // External global require no code
899 std::string name = Mang->getValueName(I);
900 Constant *C = I->getInitializer();
901 unsigned Size = TD.getTypeSize(C->getType());
902 unsigned Align = TD.getTypeAlignment(C->getType());
904 if (C->isNullValue() &&
905 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
906 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
907 SwitchSection(O, CurSection, ".data");
908 if (I->hasInternalLinkage())
909 O << "\t.local " << name << "\n";
911 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
912 << "," << (unsigned)TD.getTypeAlignment(C->getType());
914 WriteAsOperand(O, I, true, true, &M);
917 switch (I->getLinkage()) {
918 case GlobalValue::LinkOnceLinkage:
919 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
920 // Nonnull linkonce -> weak
921 O << "\t.weak " << name << "\n";
922 SwitchSection(O, CurSection, "");
923 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
926 case GlobalValue::AppendingLinkage:
927 // FIXME: appending linkage variables should go into a section of
928 // their name or something. For now, just emit them as external.
929 case GlobalValue::ExternalLinkage:
930 // If external or appending, declare as a global symbol
931 O << "\t.globl " << name << "\n";
933 case GlobalValue::InternalLinkage:
934 if (C->isNullValue())
935 SwitchSection(O, CurSection, ".bss");
937 SwitchSection(O, CurSection, ".data");
941 O << "\t.align " << Align << "\n";
942 O << "\t.type " << name << ",@object\n";
943 O << "\t.size " << name << "," << Size << "\n";
944 O << name << ":\t\t\t\t# ";
945 WriteAsOperand(O, I, true, true, &M);
947 WriteAsOperand(O, C, false, false, &M);
949 emitGlobalConstant(C);
954 return false; // success