1 //===-- X86AsmPrinter.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 representation
11 // of machine-dependent LLVM code to Intel-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
33 #include "Support/CommandLine.h"
37 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39 // FIXME: This should be automatically picked up by autoconf from the C
41 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
42 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
44 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
45 GasBugWorkaroundEmitter(std::ostream& o)
46 : O(o), OldFlags(O.flags()), firstByte(true) {
50 ~GasBugWorkaroundEmitter() {
55 virtual void emitByte(unsigned char B) {
56 if (!firstByte) O << "\n\t";
58 O << ".byte 0x" << (unsigned) B;
61 // These should never be called
62 virtual void emitWord(unsigned W) { assert(0); }
63 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
64 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
65 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
66 virtual uint64_t getCurrentPCValue() { abort(); }
67 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
71 std::ios::fmtflags OldFlags;
75 struct X86AsmPrinter : public MachineFunctionPass {
76 /// Output stream on which we're printing assembly code.
80 /// Target machine description which we query for reg. names, data
85 /// Name-mangler for global names.
89 X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
91 /// Cache of mangled name for current function. This is
92 /// recalculated at the beginning of each call to
93 /// runOnMachineFunction().
95 std::string CurrentFnName;
97 virtual const char *getPassName() const {
98 return "X86 Assembly Printer";
101 /// printInstruction - This method is automatically generated by tablegen
102 /// from the instruction set description. This method returns true if the
103 /// machine instruction was sufficiently described to print it, otherwise it
105 bool printInstruction(const MachineInstr *MI);
107 // This method is used by the tablegen'erated instruction printer.
108 void printOperand(const MachineOperand &MO, MVT::ValueType VT) {
109 if (MO.getType() == MachineOperand::MO_MachineRegister) {
110 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
111 // Bug Workaround: See note in Printer::doInitialization about %.
112 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
118 void printImplUsesBefore(const TargetInstrDescriptor &Desc);
119 bool printImplDefsBefore(const TargetInstrDescriptor &Desc);
120 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
121 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
122 void printMachineInstruction(const MachineInstr *MI);
123 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
124 void printMemReference(const MachineInstr *MI, unsigned Op);
125 void printConstantPool(MachineConstantPool *MCP);
126 bool runOnMachineFunction(MachineFunction &F);
127 bool doInitialization(Module &M);
128 bool doFinalization(Module &M);
129 void emitGlobalConstant(const Constant* CV);
130 void emitConstantValueOnly(const Constant *CV);
132 } // end of anonymous namespace
134 /// createX86CodePrinterPass - Returns a pass that prints the X86
135 /// assembly code for a MachineFunction to the given output stream,
136 /// using the given target machine description. This should work
137 /// regardless of whether the function is in SSA form.
139 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
140 return new X86AsmPrinter(o, tm);
144 // Include the auto-generated portion of the assembly writer.
145 #include "X86GenAsmWriter.inc"
148 /// toOctal - Convert the low order bits of X into an octal digit.
150 static inline char toOctal(int X) {
154 /// getAsCString - Return the specified array as a C compatible
155 /// string, only if the predicate isStringCompatible is true.
157 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
158 assert(CVA->isString() && "Array is not string compatible!");
161 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
162 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
166 } else if (C == '\\') {
168 } else if (isprint(C)) {
172 case '\b': O << "\\b"; break;
173 case '\f': O << "\\f"; break;
174 case '\n': O << "\\n"; break;
175 case '\r': O << "\\r"; break;
176 case '\t': O << "\\t"; break;
179 O << toOctal(C >> 6);
180 O << toOctal(C >> 3);
181 O << toOctal(C >> 0);
189 // Print out the specified constant, without a storage class. Only the
190 // constants valid in constant expressions can occur here.
191 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
192 if (CV->isNullValue())
194 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
195 assert(CB == ConstantBool::True);
197 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
198 if (((CI->getValue() << 32) >> 32) == CI->getValue())
201 O << (unsigned long long)CI->getValue();
202 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
204 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
205 // This is a constant address for a global variable or function. Use the
206 // name of the variable or function as the address value.
207 O << Mang->getValueName(GV);
208 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
209 const TargetData &TD = TM.getTargetData();
210 switch(CE->getOpcode()) {
211 case Instruction::GetElementPtr: {
212 // generate a symbolic expression for the byte address
213 const Constant *ptrVal = CE->getOperand(0);
214 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
215 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
217 emitConstantValueOnly(ptrVal);
218 O << ") + " << Offset;
220 emitConstantValueOnly(ptrVal);
224 case Instruction::Cast: {
225 // Support only non-converting or widening casts for now, that is, ones
226 // that do not involve a change in value. This assertion is really gross,
227 // and may not even be a complete check.
228 Constant *Op = CE->getOperand(0);
229 const Type *OpTy = Op->getType(), *Ty = CE->getType();
231 // Remember, kids, pointers on x86 can be losslessly converted back and
232 // forth into 32-bit or wider integers, regardless of signedness. :-P
233 assert(((isa<PointerType>(OpTy)
234 && (Ty == Type::LongTy || Ty == Type::ULongTy
235 || Ty == Type::IntTy || Ty == Type::UIntTy))
236 || (isa<PointerType>(Ty)
237 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
238 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
239 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
240 && OpTy->isLosslesslyConvertibleTo(Ty))))
241 && "FIXME: Don't yet support this kind of constant cast expr");
243 emitConstantValueOnly(Op);
247 case Instruction::Add:
249 emitConstantValueOnly(CE->getOperand(0));
251 emitConstantValueOnly(CE->getOperand(1));
255 assert(0 && "Unsupported operator!");
258 assert(0 && "Unknown constant value!");
262 // Print a constant value or values, with the appropriate storage class as a
264 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
265 const TargetData &TD = TM.getTargetData();
267 if (CV->isNullValue()) {
268 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
270 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
271 if (CVA->isString()) {
273 printAsCString(O, CVA);
275 } else { // Not a string. Print the values in successive locations
276 const std::vector<Use> &constValues = CVA->getValues();
277 for (unsigned i=0; i < constValues.size(); i++)
278 emitGlobalConstant(cast<Constant>(constValues[i].get()));
281 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
282 // Print the fields in successive locations. Pad to align if needed!
283 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
284 const std::vector<Use>& constValues = CVS->getValues();
285 unsigned sizeSoFar = 0;
286 for (unsigned i=0, N = constValues.size(); i < N; i++) {
287 const Constant* field = cast<Constant>(constValues[i].get());
289 // Check if padding is needed and insert one or more 0s.
290 unsigned fieldSize = TD.getTypeSize(field->getType());
291 unsigned padSize = ((i == N-1? cvsLayout->StructSize
292 : cvsLayout->MemberOffsets[i+1])
293 - cvsLayout->MemberOffsets[i]) - fieldSize;
294 sizeSoFar += fieldSize + padSize;
296 // Now print the actual field value
297 emitGlobalConstant(field);
299 // Insert the field padding unless it's zero bytes...
301 O << "\t.zero\t " << padSize << "\n";
303 assert(sizeSoFar == cvsLayout->StructSize &&
304 "Layout of constant struct may be incorrect!");
306 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
307 // FP Constants are printed as integer constants to avoid losing
309 double Val = CFP->getValue();
310 switch (CFP->getType()->getTypeID()) {
311 default: assert(0 && "Unknown floating point type!");
312 case Type::FloatTyID: {
313 union FU { // Abide by C TBAA rules
318 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
321 case Type::DoubleTyID: {
322 union DU { // Abide by C TBAA rules
327 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
333 const Type *type = CV->getType();
335 switch (type->getTypeID()) {
336 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
339 case Type::UShortTyID: case Type::ShortTyID:
342 case Type::FloatTyID: case Type::PointerTyID:
343 case Type::UIntTyID: case Type::IntTyID:
346 case Type::DoubleTyID:
347 case Type::ULongTyID: case Type::LongTyID:
351 assert (0 && "Can't handle printing this type of thing");
355 emitConstantValueOnly(CV);
359 /// printConstantPool - Print to the current output stream assembly
360 /// representations of the constants in the constant pool MCP. This is
361 /// used to print out constants which have been "spilled to memory" by
362 /// the code generator.
364 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
365 const std::vector<Constant*> &CP = MCP->getConstants();
366 const TargetData &TD = TM.getTargetData();
368 if (CP.empty()) return;
370 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
371 O << "\t.section .rodata\n";
372 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
374 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
376 emitGlobalConstant(CP[i]);
380 /// runOnMachineFunction - This uses the printMachineInstruction()
381 /// method to print assembly for each instruction.
383 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
385 // What's my mangled name?
386 CurrentFnName = Mang->getValueName(MF.getFunction());
388 // Print out constants referenced by the function
389 printConstantPool(MF.getConstantPool());
391 // Print out labels for the function.
393 O << "\t.align 16\n";
394 O << "\t.globl\t" << CurrentFnName << "\n";
396 O << "\t.type\t" << CurrentFnName << ", @function\n";
397 O << CurrentFnName << ":\n";
399 // Print out code for the function.
400 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
402 // Print a label for the basic block.
403 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
404 << I->getBasicBlock()->getName() << "\n";
405 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
407 // Print the assembly for the instruction.
409 printMachineInstruction(II);
413 // We didn't modify anything.
417 static bool isScale(const MachineOperand &MO) {
418 return MO.isImmediate() &&
419 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
420 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
423 static bool isMem(const MachineInstr *MI, unsigned Op) {
424 if (MI->getOperand(Op).isFrameIndex()) return true;
425 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
426 return Op+4 <= MI->getNumOperands() &&
427 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
428 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
433 void X86AsmPrinter::printOp(const MachineOperand &MO,
434 bool elideOffsetKeyword /* = false */) {
435 const MRegisterInfo &RI = *TM.getRegisterInfo();
436 switch (MO.getType()) {
437 case MachineOperand::MO_VirtualRegister:
438 if (Value *V = MO.getVRegValueOrNull()) {
439 O << "<" << V->getName() << ">";
443 case MachineOperand::MO_MachineRegister:
444 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
445 // Bug Workaround: See note in Printer::doInitialization about %.
446 O << "%" << RI.get(MO.getReg()).Name;
448 O << "%reg" << MO.getReg();
451 case MachineOperand::MO_SignExtendedImmed:
452 case MachineOperand::MO_UnextendedImmed:
453 O << (int)MO.getImmedValue();
455 case MachineOperand::MO_MachineBasicBlock: {
456 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
457 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
458 << "_" << MBBOp->getNumber () << "\t# "
459 << MBBOp->getBasicBlock ()->getName ();
462 case MachineOperand::MO_PCRelativeDisp:
463 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
466 case MachineOperand::MO_GlobalAddress:
467 if (!elideOffsetKeyword)
469 O << Mang->getValueName(MO.getGlobal());
471 case MachineOperand::MO_ExternalSymbol:
472 O << MO.getSymbolName();
475 O << "<unknown operand type>"; return;
479 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
480 switch (Desc.TSFlags & X86II::MemMask) {
481 default: assert(0 && "Unknown arg size!");
482 case X86II::Mem8: return "BYTE PTR";
483 case X86II::Mem16: return "WORD PTR";
484 case X86II::Mem32: return "DWORD PTR";
485 case X86II::Mem64: return "QWORD PTR";
486 case X86II::Mem80: return "XWORD PTR";
490 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
491 assert(isMem(MI, Op) && "Invalid memory reference!");
493 if (MI->getOperand(Op).isFrameIndex()) {
494 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
495 if (MI->getOperand(Op+3).getImmedValue())
496 O << " + " << MI->getOperand(Op+3).getImmedValue();
499 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
500 O << "[.CPI" << CurrentFnName << "_"
501 << MI->getOperand(Op).getConstantPoolIndex();
502 if (MI->getOperand(Op+3).getImmedValue())
503 O << " + " << MI->getOperand(Op+3).getImmedValue();
508 const MachineOperand &BaseReg = MI->getOperand(Op);
509 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
510 const MachineOperand &IndexReg = MI->getOperand(Op+2);
511 int DispVal = MI->getOperand(Op+3).getImmedValue();
514 bool NeedPlus = false;
515 if (BaseReg.getReg()) {
520 if (IndexReg.getReg()) {
521 if (NeedPlus) O << " + ";
523 O << ScaleVal << "*";
542 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
543 /// described by DESC, if its PrintImplUsesBefore flag is set.
545 void X86AsmPrinter::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
546 const MRegisterInfo &RI = *TM.getRegisterInfo();
547 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
548 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
549 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
550 O << "%" << RI.get(*p).Name << ", ";
555 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
556 /// described by DESC, if its PrintImplUsesBefore flag is set. Return true if
557 /// we printed any registers.
559 bool X86AsmPrinter::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
560 bool Printed = false;
561 const MRegisterInfo &RI = *TM.getRegisterInfo();
562 if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
563 const unsigned *p = Desc.ImplicitDefs;
565 O << (Printed ? ", %" : "%") << RI.get (*p).Name;
570 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
571 O << ", %" << RI.get(*p).Name;
579 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
580 /// described by DESC, if its PrintImplUsesAfter flag is set.
583 /// Comma - List of registers will need a leading comma.
584 /// Desc - Description of the Instruction.
587 /// true - Emitted one or more registers.
588 /// false - Emitted no registers.
590 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
591 const bool Comma = true) {
592 const MRegisterInfo &RI = *TM.getRegisterInfo();
593 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
594 bool emitted = false;
595 const unsigned *p = Desc.ImplicitUses;
597 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
602 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
603 O << ", %" << RI.get(*p).Name;
611 /// printImplDefsAfter - Emit the implicit-definition registers for the
612 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
615 /// Comma - List of registers will need a leading comma.
616 /// Desc - Description of the Instruction
619 /// true - Emitted one or more registers.
620 /// false - Emitted no registers.
622 bool X86AsmPrinter::printImplDefsAfter(const TargetInstrDescriptor &Desc,
623 const bool Comma = true) {
624 const MRegisterInfo &RI = *TM.getRegisterInfo();
625 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
626 bool emitted = false;
627 const unsigned *p = Desc.ImplicitDefs;
629 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
634 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
635 O << ", %" << RI.get(*p).Name;
643 /// printMachineInstruction -- Print out a single X86 LLVM instruction
644 /// MI in Intel syntax to the current output stream.
646 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
648 if (printInstruction(MI))
649 return; // Printer was automatically generated
651 unsigned Opcode = MI->getOpcode();
652 const TargetInstrInfo &TII = *TM.getInstrInfo();
653 const TargetInstrDescriptor &Desc = TII.get(Opcode);
655 switch (Desc.TSFlags & X86II::FormMask) {
657 // Print pseudo-instructions as comments; either they should have been
658 // turned into real instructions by now, or they don't need to be
659 // seen by the assembler (e.g., IMPLICIT_USEs.)
661 if (Opcode == X86::PHI) {
662 printOp(MI->getOperand(0));
664 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
665 if (i != 1) O << ", ";
667 printOp(MI->getOperand(i));
669 printOp(MI->getOperand(i+1));
674 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
675 printOp(MI->getOperand(0));
679 O << TII.getName(MI->getOpcode());
681 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
683 if (MI->getOperand(i).isDef()) O << "*";
684 printOp(MI->getOperand(i));
685 if (MI->getOperand(i).isDef()) O << "*";
693 // The accepted forms of Raw instructions are:
694 // 1. jmp foo - MachineBasicBlock operand
695 // 2. call bar - GlobalAddress Operand or External Symbol Operand
696 // 3. in AL, imm - Immediate operand
698 assert(MI->getNumOperands() == 1 &&
699 (MI->getOperand(0).isMachineBasicBlock() ||
700 MI->getOperand(0).isGlobalAddress() ||
701 MI->getOperand(0).isExternalSymbol() ||
702 MI->getOperand(0).isImmediate()) &&
703 "Illegal raw instruction!");
704 O << TII.getName(MI->getOpcode()) << " ";
706 bool LeadingComma = printImplDefsBefore(Desc);
708 if (MI->getNumOperands() == 1) {
709 if (LeadingComma) O << ", ";
710 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
713 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
714 printImplUsesAfter(Desc, LeadingComma);
719 case X86II::AddRegFrm: {
720 // There are currently two forms of acceptable AddRegFrm instructions.
721 // Either the instruction JUST takes a single register (like inc, dec, etc),
722 // or it takes a register and an immediate of the same size as the register
723 // (move immediate f.e.). Note that this immediate value might be stored as
724 // an LLVM value, to represent, for example, loading the address of a global
725 // into a register. The initial register might be duplicated if this is a
726 // M_2_ADDR_REG instruction
728 assert(MI->getOperand(0).isRegister() &&
729 (MI->getNumOperands() == 1 ||
730 (MI->getNumOperands() == 2 &&
731 (MI->getOperand(1).getVRegValueOrNull() ||
732 MI->getOperand(1).isImmediate() ||
733 MI->getOperand(1).isRegister() ||
734 MI->getOperand(1).isGlobalAddress() ||
735 MI->getOperand(1).isExternalSymbol()))) &&
736 "Illegal form for AddRegFrm instruction!");
738 unsigned Reg = MI->getOperand(0).getReg();
740 O << TII.getName(MI->getOpcode()) << " ";
742 printImplUsesBefore(Desc); // fcmov*
744 printOp(MI->getOperand(0));
745 if (MI->getNumOperands() == 2 &&
746 (!MI->getOperand(1).isRegister() ||
747 MI->getOperand(1).getVRegValueOrNull() ||
748 MI->getOperand(1).isGlobalAddress() ||
749 MI->getOperand(1).isExternalSymbol())) {
751 printOp(MI->getOperand(1));
753 printImplUsesAfter(Desc);
757 case X86II::MRMDestReg: {
758 // There are three forms of MRMDestReg instructions, those with 2
761 // 2 Operands: this is for things like mov that do not read a
764 // 2 Operands: two address instructions which def&use the first
765 // argument and use the second as input.
767 // 3 Operands: in this form, two address instructions are the same
768 // as in 2 but have a constant argument as well.
770 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
771 assert(MI->getOperand(0).isRegister() &&
772 (MI->getNumOperands() == 2 ||
773 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
774 && "Bad format for MRMDestReg!");
776 O << TII.getName(MI->getOpcode()) << " ";
777 printOp(MI->getOperand(0));
779 printOp(MI->getOperand(1));
780 if (MI->getNumOperands() == 3) {
782 printOp(MI->getOperand(2));
784 printImplUsesAfter(Desc);
789 case X86II::MRMDestMem: {
790 // These instructions are the same as MRMDestReg, but instead of having a
791 // register reference for the mod/rm field, it's a memory reference.
793 assert(isMem(MI, 0) &&
794 (MI->getNumOperands() == 4+1 ||
795 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
796 && "Bad format for MRMDestMem!");
798 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
799 printMemReference(MI, 0);
801 printOp(MI->getOperand(4));
802 if (MI->getNumOperands() == 4+2) {
804 printOp(MI->getOperand(5));
806 printImplUsesAfter(Desc);
811 case X86II::MRMSrcReg: {
812 // There are three forms that are acceptable for MRMSrcReg
813 // instructions, those with 2 or 3 operands:
815 // 2 Operands: this is for things like mov that do not read a
818 // 2 Operands: in this form, the last register is the ModR/M
819 // input. The first operand is a def&use. This is for things
820 // like: add r32, r/m32
822 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
823 // for instructions like the IMULrri instructions.
826 assert(MI->getOperand(0).isRegister() &&
827 MI->getOperand(1).isRegister() &&
828 (MI->getNumOperands() == 2 ||
829 (MI->getNumOperands() == 3 &&
830 (MI->getOperand(2).isImmediate())))
831 && "Bad format for MRMSrcReg!");
833 O << TII.getName(MI->getOpcode()) << " ";
834 printOp(MI->getOperand(0));
836 printOp(MI->getOperand(1));
837 if (MI->getNumOperands() == 3) {
839 printOp(MI->getOperand(2));
845 case X86II::MRMSrcMem: {
846 // These instructions are the same as MRMSrcReg, but instead of having a
847 // register reference for the mod/rm field, it's a memory reference.
849 assert(MI->getOperand(0).isRegister() &&
850 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
851 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
853 && "Bad format for MRMSrcMem!");
854 O << TII.getName(MI->getOpcode()) << " ";
855 printOp(MI->getOperand(0));
856 O << ", " << sizePtr(Desc) << " ";
857 printMemReference(MI, 1);
858 if (MI->getNumOperands() == 2+4) {
860 printOp(MI->getOperand(5));
866 case X86II::MRM0r: case X86II::MRM1r:
867 case X86II::MRM2r: case X86II::MRM3r:
868 case X86II::MRM4r: case X86II::MRM5r:
869 case X86II::MRM6r: case X86II::MRM7r: {
870 // In this form, the following are valid formats:
872 // 2. cmp reg, immediate
873 // 2. shl rdest, rinput <implicit CL or 1>
874 // 3. sbb rdest, rinput, immediate [rdest = rinput]
876 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
877 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
878 assert((MI->getNumOperands() != 2 ||
879 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
880 "Bad MRMSxR format!");
881 assert((MI->getNumOperands() < 3 ||
882 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
883 "Bad MRMSxR format!");
885 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
886 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
889 O << TII.getName(MI->getOpcode()) << " ";
890 printOp(MI->getOperand(0));
891 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
893 printOp(MI->getOperand(MI->getNumOperands()-1));
895 printImplUsesAfter(Desc);
901 case X86II::MRM0m: case X86II::MRM1m:
902 case X86II::MRM2m: case X86II::MRM3m:
903 case X86II::MRM4m: case X86II::MRM5m:
904 case X86II::MRM6m: case X86II::MRM7m: {
905 // In this form, the following are valid formats:
907 // 2. cmp [m], immediate
908 // 2. shl [m], rinput <implicit CL or 1>
909 // 3. sbb [m], immediate
911 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
912 isMem(MI, 0) && "Bad MRMSxM format!");
913 assert((MI->getNumOperands() != 5 ||
914 (MI->getOperand(4).isImmediate() ||
915 MI->getOperand(4).isGlobalAddress())) &&
916 "Bad MRMSxM format!");
918 const MachineOperand &Op3 = MI->getOperand(3);
922 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
923 // is misassembled by gas in intel_syntax mode as its 32-bit
924 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
925 // opcode bytes instead of the instruction.
927 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
928 // misassembled by gas in intel_syntax mode as its 32-bit
929 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
930 // opcode bytes instead of the instruction.
932 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
933 // invalid opcode, saying "64 bit operations are only supported in
934 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
935 // [...]", which is wrong. Workaround: Output the raw opcode bytes
936 // instead of the instruction.
938 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
939 // invalid opcode, saying "64 bit operations are only supported in
940 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
941 // [...]", which is wrong. Workaround: Output the raw opcode bytes
942 // instead of the instruction.
943 if (MI->getOpcode() == X86::FSTP80m ||
944 MI->getOpcode() == X86::FLD80m ||
945 MI->getOpcode() == X86::FILD64m ||
946 MI->getOpcode() == X86::FISTP64m) {
947 GasBugWorkaroundEmitter gwe(O);
948 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
951 O << TII.getName(MI->getOpcode()) << " ";
952 O << sizePtr(Desc) << " ";
953 printMemReference(MI, 0);
954 if (MI->getNumOperands() == 5) {
956 printOp(MI->getOperand(4));
958 printImplUsesAfter(Desc);
963 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
967 bool X86AsmPrinter::doInitialization(Module &M) {
968 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
970 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
971 // instruction as a reference to the register named sp, and if you try to
972 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
973 // before being looked up in the symbol table. This creates spurious
974 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
975 // mode, and decorate all register names with percent signs.
976 O << "\t.intel_syntax\n";
977 Mang = new Mangler(M, EmitCygwin);
978 return false; // success
981 // SwitchSection - Switch to the specified section of the executable if we are
982 // not already in it!
984 static void SwitchSection(std::ostream &OS, std::string &CurSection,
985 const char *NewSection) {
986 if (CurSection != NewSection) {
987 CurSection = NewSection;
988 if (!CurSection.empty())
989 OS << "\t" << NewSection << "\n";
993 bool X86AsmPrinter::doFinalization(Module &M) {
994 const TargetData &TD = TM.getTargetData();
995 std::string CurSection;
997 // Print out module-level global variables here.
998 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
999 if (I->hasInitializer()) { // External global require no code
1001 std::string name = Mang->getValueName(I);
1002 Constant *C = I->getInitializer();
1003 unsigned Size = TD.getTypeSize(C->getType());
1004 unsigned Align = TD.getTypeAlignment(C->getType());
1006 if (C->isNullValue() &&
1007 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
1008 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
1009 SwitchSection(O, CurSection, ".data");
1010 if (I->hasInternalLinkage())
1011 O << "\t.local " << name << "\n";
1013 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
1014 << "," << (unsigned)TD.getTypeAlignment(C->getType());
1016 WriteAsOperand(O, I, true, true, &M);
1019 switch (I->getLinkage()) {
1020 case GlobalValue::LinkOnceLinkage:
1021 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
1022 // Nonnull linkonce -> weak
1023 O << "\t.weak " << name << "\n";
1024 SwitchSection(O, CurSection, "");
1025 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
1028 case GlobalValue::AppendingLinkage:
1029 // FIXME: appending linkage variables should go into a section of
1030 // their name or something. For now, just emit them as external.
1031 case GlobalValue::ExternalLinkage:
1032 // If external or appending, declare as a global symbol
1033 O << "\t.globl " << name << "\n";
1035 case GlobalValue::InternalLinkage:
1036 if (C->isNullValue())
1037 SwitchSection(O, CurSection, ".bss");
1039 SwitchSection(O, CurSection, ".data");
1043 O << "\t.align " << Align << "\n";
1044 O << "\t.type " << name << ",@object\n";
1045 O << "\t.size " << name << "," << Size << "\n";
1046 O << name << ":\t\t\t\t# ";
1047 WriteAsOperand(O, I, true, true, &M);
1049 WriteAsOperand(O, C, false, false, &M);
1051 emitGlobalConstant(C);
1056 return false; // success