Added LLVM project notice to the top of every C++ source file.
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
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"
31
32 namespace {
33   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
34
35   // FIXME: This should be automatically picked up by autoconf from the C
36   // frontend
37   cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
38          cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
39
40   struct Printer : public MachineFunctionPass {
41     /// Output stream on which we're printing assembly code.
42     ///
43     std::ostream &O;
44
45     /// Target machine description which we query for reg. names, data
46     /// layout, etc.
47     ///
48     TargetMachine &TM;
49
50     /// Name-mangler for global names.
51     ///
52     Mangler *Mang;
53
54     Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
55
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().
59     ///
60     typedef std::map<const Value *, unsigned> ValueMapTy;
61     ValueMapTy NumberForBB;
62
63     /// Cache of mangled name for current function. This is
64     /// recalculated at the beginning of each call to
65     /// runOnMachineFunction().
66     ///
67     std::string CurrentFnName;
68
69     virtual const char *getPassName() const {
70       return "X86 Assembly Printer";
71     }
72
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     std::string ConstantExprToString(const ConstantExpr* CE);
81     std::string valToExprString(const Value* V);
82     bool doInitialization(Module &M);
83     bool doFinalization(Module &M);
84     void printConstantValueOnly(const Constant* CV);
85     void printSingleConstantValue(const Constant* CV);
86   };
87 } // end of anonymous namespace
88
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.
93 ///
94 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
95   return new Printer(o, tm);
96 }
97
98 /// valToExprString - Helper function for ConstantExprToString().
99 /// Appends result to argument string S.
100 /// 
101 std::string Printer::valToExprString(const Value* V) {
102   std::string S;
103   bool failed = false;
104   if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
105     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
106       S += std::string(CB == ConstantBool::True ? "1" : "0");
107     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
108       S += itostr(CI->getValue());
109     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
110       S += utostr(CI->getValue());
111     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
112       S += ftostr(CFP->getValue());
113     else if (isa<ConstantPointerNull>(CV))
114       S += "0";
115     else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
116       S += valToExprString(CPR->getValue());
117     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
118       S += ConstantExprToString(CE);
119     else
120       failed = true;
121   } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
122     S += Mang->getValueName(GV);
123   }
124   else
125     failed = true;
126
127   if (failed) {
128     assert(0 && "Cannot convert value to string");
129     S += "<illegal-value>";
130   }
131   return S;
132 }
133
134 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
135 /// and return this as a string.
136 ///
137 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
138   const TargetData &TD = TM.getTargetData();
139   switch(CE->getOpcode()) {
140   case Instruction::GetElementPtr:
141     { // generate a symbolic expression for the byte address
142       const Value* ptrVal = CE->getOperand(0);
143       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
144       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
145         return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
146       else
147         return valToExprString(ptrVal);
148     }
149
150   case Instruction::Cast:
151     // Support only non-converting or widening casts for now, that is,
152     // ones that do not involve a change in value.  This assertion is
153     // not a complete check.
154     {
155       Constant *Op = CE->getOperand(0);
156       const Type *OpTy = Op->getType(), *Ty = CE->getType();
157       assert(((isa<PointerType>(OpTy)
158                && (Ty == Type::LongTy || Ty == Type::ULongTy))
159               || (isa<PointerType>(Ty)
160                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
161              || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
162                   && (OpTy->isLosslesslyConvertibleTo(Ty))))
163              && "FIXME: Don't yet support this kind of constant cast expr");
164       return "(" + valToExprString(Op) + ")";
165     }
166
167   case Instruction::Add:
168     return "(" + valToExprString(CE->getOperand(0)) + ") + ("
169                + valToExprString(CE->getOperand(1)) + ")";
170
171   default:
172     assert(0 && "Unsupported operator in ConstantExprToString()");
173     return "";
174   }
175 }
176
177 /// printSingleConstantValue - Print a single constant value.
178 ///
179 void
180 Printer::printSingleConstantValue(const Constant* CV)
181 {
182   assert(CV->getType() != Type::VoidTy &&
183          CV->getType() != Type::TypeTy &&
184          CV->getType() != Type::LabelTy &&
185          "Unexpected type for Constant");
186   
187   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
188          && "Aggregate types should be handled outside this function");
189
190   const Type *type = CV->getType();
191   O << "\t";
192   switch(type->getPrimitiveID())
193     {
194     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
195       O << ".byte";
196       break;
197     case Type::UShortTyID: case Type::ShortTyID:
198       O << ".word";
199       break;
200     case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
201       O << ".long";
202       break;
203     case Type::ULongTyID: case Type::LongTyID:
204       O << ".quad";
205       break;
206     case Type::FloatTyID:
207       O << ".long";
208       break;
209     case Type::DoubleTyID:
210       O << ".quad";
211       break;
212     case Type::ArrayTyID:
213       if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
214           (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
215         O << ".string";
216       else
217         assert (0 && "Can't handle printing this type of array");
218       break;
219     default:
220       assert (0 && "Can't handle printing this type of thing");
221       break;
222     }
223   O << "\t";
224   
225   if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
226     {
227       // Constant expression built from operators, constants, and
228       // symbolic addrs
229       O << ConstantExprToString(CE) << "\n";
230     }
231   else if (type->isPrimitiveType())
232     {
233       if (type->isFloatingPoint()) {
234         // FP Constants are printed as integer constants to avoid losing
235         // precision...
236         double Val = cast<ConstantFP>(CV)->getValue();
237         if (type == Type::FloatTy) {
238           float FVal = (float)Val;
239           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
240           O << *(unsigned int*)ProxyPtr;            
241         } else if (type == Type::DoubleTy) {
242           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
243           O << *(uint64_t*)ProxyPtr;            
244         } else {
245           assert(0 && "Unknown floating point type!");
246         }
247         
248         O << "\t# " << type->getDescription() << " value: " << Val << "\n";
249       } else {
250         WriteAsOperand(O, CV, false, false) << "\n";
251       }
252     }
253   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
254     {
255       // This is a constant address for a global variable or method.
256       // Use the name of the variable or method as the address value.
257       O << Mang->getValueName(CPR->getValue()) << "\n";
258     }
259   else if (isa<ConstantPointerNull>(CV))
260     {
261       // Null pointer value
262       O << "0\n";
263     }
264   else
265     {
266       assert(0 && "Unknown elementary type for constant");
267     }
268 }
269
270 /// isStringCompatible - Can we treat the specified array as a string?
271 /// Only if it is an array of ubytes or non-negative sbytes.
272 ///
273 static bool isStringCompatible(const ConstantArray *CVA) {
274   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
275   if (ETy == Type::UByteTy) return true;
276   if (ETy != Type::SByteTy) return false;
277
278   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
279     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
280       return false;
281
282   return true;
283 }
284
285 /// toOctal - Convert the low order bits of X into an octal digit.
286 ///
287 static inline char toOctal(int X) {
288   return (X&7)+'0';
289 }
290
291 /// getAsCString - Return the specified array as a C compatible
292 /// string, only if the predicate isStringCompatible is true.
293 ///
294 static std::string getAsCString(const ConstantArray *CVA) {
295   assert(isStringCompatible(CVA) && "Array is not string compatible!");
296
297   std::string Result;
298   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
299   Result = "\"";
300   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
301     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
302
303     if (C == '"') {
304       Result += "\\\"";
305     } else if (C == '\\') {
306       Result += "\\\\";
307     } else if (isprint(C)) {
308       Result += C;
309     } else {
310       switch(C) {
311       case '\b': Result += "\\b"; break;
312       case '\f': Result += "\\f"; break;
313       case '\n': Result += "\\n"; break;
314       case '\r': Result += "\\r"; break;
315       case '\t': Result += "\\t"; break;
316       default:
317         Result += '\\';
318         Result += toOctal(C >> 6);
319         Result += toOctal(C >> 3);
320         Result += toOctal(C >> 0);
321         break;
322       }
323     }
324   }
325   Result += "\"";
326   return Result;
327 }
328
329 // Print a constant value or values (it may be an aggregate).
330 // Uses printSingleConstantValue() to print each individual value.
331 void Printer::printConstantValueOnly(const Constant *CV) {  
332   const TargetData &TD = TM.getTargetData();
333
334   if (CV->isNullValue()) {
335     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
336   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
337     if (isStringCompatible(CVA)) {
338       // print the string alone and return
339       O << "\t.ascii\t" << getAsCString(CVA) << "\n";
340     } else { // Not a string.  Print the values in successive locations
341       const std::vector<Use> &constValues = CVA->getValues();
342       for (unsigned i=0; i < constValues.size(); i++)
343         printConstantValueOnly(cast<Constant>(constValues[i].get()));
344     }
345   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
346     // Print the fields in successive locations. Pad to align if needed!
347     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
348     const std::vector<Use>& constValues = CVS->getValues();
349     unsigned sizeSoFar = 0;
350     for (unsigned i=0, N = constValues.size(); i < N; i++) {
351       const Constant* field = cast<Constant>(constValues[i].get());
352
353       // Check if padding is needed and insert one or more 0s.
354       unsigned fieldSize = TD.getTypeSize(field->getType());
355       unsigned padSize = ((i == N-1? cvsLayout->StructSize
356                            : cvsLayout->MemberOffsets[i+1])
357                           - cvsLayout->MemberOffsets[i]) - fieldSize;
358       sizeSoFar += fieldSize + padSize;
359
360       // Now print the actual field value
361       printConstantValueOnly(field);
362
363       // Insert the field padding unless it's zero bytes...
364       if (padSize)
365         O << "\t.zero\t " << padSize << "\n";      
366     }
367     assert(sizeSoFar == cvsLayout->StructSize &&
368            "Layout of constant struct may be incorrect!");
369   } else
370     printSingleConstantValue(CV);
371 }
372
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
377 ///
378 void Printer::printConstantPool(MachineConstantPool *MCP) {
379   const std::vector<Constant*> &CP = MCP->getConstants();
380   const TargetData &TD = TM.getTargetData();
381  
382   if (CP.empty()) return;
383
384   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385     O << "\t.section .rodata\n";
386     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
387       << "\n";
388     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
389       << *CP[i] << "\n";
390     printConstantValueOnly (CP[i]);
391   }
392 }
393
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
396 ///
397 bool Printer::runOnMachineFunction(MachineFunction &MF) {
398   // BBNumber is used here so that a given Printer will never give two
399   // BBs the same name. (If you have a better way, please let me know!)
400   static unsigned BBNumber = 0;
401
402   O << "\n\n";
403   // What's my mangled name?
404   CurrentFnName = Mang->getValueName(MF.getFunction());
405
406   // Print out constants referenced by the function
407   printConstantPool(MF.getConstantPool());
408
409   // Print out labels for the function.
410   O << "\t.text\n";
411   O << "\t.align 16\n";
412   O << "\t.globl\t" << CurrentFnName << "\n";
413   if (!EmitCygwin)
414     O << "\t.type\t" << CurrentFnName << ", @function\n";
415   O << CurrentFnName << ":\n";
416
417   // Number each basic block so that we can consistently refer to them
418   // in PC-relative references.
419   NumberForBB.clear();
420   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
421        I != E; ++I) {
422     NumberForBB[I->getBasicBlock()] = BBNumber++;
423   }
424
425   // Print out code for the function.
426   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
427        I != E; ++I) {
428     // Print a label for the basic block.
429     O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
430       << I->getBasicBlock()->getName() << "\n";
431     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
432          II != E; ++II) {
433       // Print the assembly for the instruction.
434       O << "\t";
435       printMachineInstruction(*II);
436     }
437   }
438
439   // We didn't modify anything.
440   return false;
441 }
442
443 static bool isScale(const MachineOperand &MO) {
444   return MO.isImmediate() &&
445     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
446      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
447 }
448
449 static bool isMem(const MachineInstr *MI, unsigned Op) {
450   if (MI->getOperand(Op).isFrameIndex()) return true;
451   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
452   return Op+4 <= MI->getNumOperands() &&
453     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
454     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
455 }
456
457
458
459 void Printer::printOp(const MachineOperand &MO,
460                       bool elideOffsetKeyword /* = false */) {
461   const MRegisterInfo &RI = *TM.getRegisterInfo();
462   switch (MO.getType()) {
463   case MachineOperand::MO_VirtualRegister:
464     if (Value *V = MO.getVRegValueOrNull()) {
465       O << "<" << V->getName() << ">";
466       return;
467     }
468     // FALLTHROUGH
469   case MachineOperand::MO_MachineRegister:
470     if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
471       // Bug Workaround: See note in Printer::doInitialization about %.
472       O << "%" << RI.get(MO.getReg()).Name;
473     else
474       O << "%reg" << MO.getReg();
475     return;
476
477   case MachineOperand::MO_SignExtendedImmed:
478   case MachineOperand::MO_UnextendedImmed:
479     O << (int)MO.getImmedValue();
480     return;
481   case MachineOperand::MO_PCRelativeDisp: {
482     ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
483     assert (i != NumberForBB.end()
484             && "Could not find a BB in the NumberForBB map!");
485     O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
486     return;
487   }
488   case MachineOperand::MO_GlobalAddress:
489     if (!elideOffsetKeyword)
490       O << "OFFSET ";
491     O << Mang->getValueName(MO.getGlobal());
492     return;
493   case MachineOperand::MO_ExternalSymbol:
494     O << MO.getSymbolName();
495     return;
496   default:
497     O << "<unknown operand type>"; return;    
498   }
499 }
500
501 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
502   switch (Desc.TSFlags & X86II::ArgMask) {
503   default: assert(0 && "Unknown arg size!");
504   case X86II::Arg8:   return "BYTE PTR"; 
505   case X86II::Arg16:  return "WORD PTR"; 
506   case X86II::Arg32:  return "DWORD PTR"; 
507   case X86II::Arg64:  return "QWORD PTR"; 
508   case X86II::ArgF32:  return "DWORD PTR"; 
509   case X86II::ArgF64:  return "QWORD PTR"; 
510   case X86II::ArgF80:  return "XWORD PTR"; 
511   }
512 }
513
514 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
515   assert(isMem(MI, Op) && "Invalid memory reference!");
516
517   if (MI->getOperand(Op).isFrameIndex()) {
518     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
519     if (MI->getOperand(Op+3).getImmedValue())
520       O << " + " << MI->getOperand(Op+3).getImmedValue();
521     O << "]";
522     return;
523   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
524     O << "[.CPI" << CurrentFnName << "_"
525       << MI->getOperand(Op).getConstantPoolIndex();
526     if (MI->getOperand(Op+3).getImmedValue())
527       O << " + " << MI->getOperand(Op+3).getImmedValue();
528     O << "]";
529     return;
530   }
531
532   const MachineOperand &BaseReg  = MI->getOperand(Op);
533   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
534   const MachineOperand &IndexReg = MI->getOperand(Op+2);
535   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
536
537   O << "[";
538   bool NeedPlus = false;
539   if (BaseReg.getReg()) {
540     printOp(BaseReg);
541     NeedPlus = true;
542   }
543
544   if (IndexReg.getReg()) {
545     if (NeedPlus) O << " + ";
546     if (ScaleVal != 1)
547       O << ScaleVal << "*";
548     printOp(IndexReg);
549     NeedPlus = true;
550   }
551
552   if (DispVal) {
553     if (NeedPlus)
554       if (DispVal > 0)
555         O << " + ";
556       else {
557         O << " - ";
558         DispVal = -DispVal;
559       }
560     O << DispVal;
561   }
562   O << "]";
563 }
564
565 /// checkImplUses - Emit the implicit-use registers for the
566 /// instruction described by DESC, if its PrintImplUses flag is set.
567 ///
568 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
569   const MRegisterInfo &RI = *TM.getRegisterInfo();
570   if (Desc.TSFlags & X86II::PrintImplUses) {
571     for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
572       // Bug Workaround: See note in Printer::doInitialization about %.
573       O << ", %" << RI.get(*p).Name;
574     }
575   }
576 }
577
578 /// printMachineInstruction -- Print out a single X86 LLVM instruction
579 /// MI in Intel syntax to the current output stream.
580 ///
581 void Printer::printMachineInstruction(const MachineInstr *MI) {
582   unsigned Opcode = MI->getOpcode();
583   const TargetInstrInfo &TII = TM.getInstrInfo();
584   const TargetInstrDescriptor &Desc = TII.get(Opcode);
585
586   ++EmittedInsts;
587   switch (Desc.TSFlags & X86II::FormMask) {
588   case X86II::Pseudo:
589     // Print pseudo-instructions as comments; either they should have been
590     // turned into real instructions by now, or they don't need to be
591     // seen by the assembler (e.g., IMPLICIT_USEs.)
592     O << "# ";
593     if (Opcode == X86::PHI) {
594       printOp(MI->getOperand(0));
595       O << " = phi ";
596       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
597         if (i != 1) O << ", ";
598         O << "[";
599         printOp(MI->getOperand(i));
600         O << ", ";
601         printOp(MI->getOperand(i+1));
602         O << "]";
603       }
604     } else {
605       unsigned i = 0;
606       if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() || 
607                                    MI->getOperand(0).opIsDefAndUse())) {
608         printOp(MI->getOperand(0));
609         O << " = ";
610         ++i;
611       }
612       O << TII.getName(MI->getOpcode());
613
614       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
615         O << " ";
616         if (MI->getOperand(i).opIsDefOnly() || 
617             MI->getOperand(i).opIsDefAndUse()) O << "*";
618         printOp(MI->getOperand(i));
619         if (MI->getOperand(i).opIsDefOnly() || 
620             MI->getOperand(i).opIsDefAndUse()) O << "*";
621       }
622     }
623     O << "\n";
624     return;
625
626   case X86II::RawFrm:
627     // The accepted forms of Raw instructions are:
628     //   1. nop     - No operand required
629     //   2. jmp foo - PC relative displacement operand
630     //   3. call bar - GlobalAddress Operand or External Symbol Operand
631     //
632     assert(MI->getNumOperands() == 0 ||
633            (MI->getNumOperands() == 1 &&
634             (MI->getOperand(0).isPCRelativeDisp() ||
635              MI->getOperand(0).isGlobalAddress() ||
636              MI->getOperand(0).isExternalSymbol())) &&
637            "Illegal raw instruction!");
638     O << TII.getName(MI->getOpcode()) << " ";
639
640     if (MI->getNumOperands() == 1) {
641       printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
642     }
643     O << "\n";
644     return;
645
646   case X86II::AddRegFrm: {
647     // There are currently two forms of acceptable AddRegFrm instructions.
648     // Either the instruction JUST takes a single register (like inc, dec, etc),
649     // or it takes a register and an immediate of the same size as the register
650     // (move immediate f.e.).  Note that this immediate value might be stored as
651     // an LLVM value, to represent, for example, loading the address of a global
652     // into a register.  The initial register might be duplicated if this is a
653     // M_2_ADDR_REG instruction
654     //
655     assert(MI->getOperand(0).isRegister() &&
656            (MI->getNumOperands() == 1 || 
657             (MI->getNumOperands() == 2 &&
658              (MI->getOperand(1).getVRegValueOrNull() ||
659               MI->getOperand(1).isImmediate() ||
660               MI->getOperand(1).isRegister() ||
661               MI->getOperand(1).isGlobalAddress() ||
662               MI->getOperand(1).isExternalSymbol()))) &&
663            "Illegal form for AddRegFrm instruction!");
664
665     unsigned Reg = MI->getOperand(0).getReg();
666     
667     O << TII.getName(MI->getOpCode()) << " ";
668     printOp(MI->getOperand(0));
669     if (MI->getNumOperands() == 2 &&
670         (!MI->getOperand(1).isRegister() ||
671          MI->getOperand(1).getVRegValueOrNull() ||
672          MI->getOperand(1).isGlobalAddress() ||
673          MI->getOperand(1).isExternalSymbol())) {
674       O << ", ";
675       printOp(MI->getOperand(1));
676     }
677     checkImplUses(Desc);
678     O << "\n";
679     return;
680   }
681   case X86II::MRMDestReg: {
682     // There are two acceptable forms of MRMDestReg instructions, those with 2,
683     // 3 and 4 operands:
684     //
685     // 2 Operands: this is for things like mov that do not read a second input
686     //
687     // 3 Operands: in this form, the first two registers (the destination, and
688     // the first operand) should be the same, post register allocation.  The 3rd
689     // operand is an additional input.  This should be for things like add
690     // instructions.
691     //
692     // 4 Operands: This form is for instructions which are 3 operands forms, but
693     // have a constant argument as well.
694     //
695     bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
696     assert(MI->getOperand(0).isRegister() &&
697            (MI->getNumOperands() == 2 ||
698             (isTwoAddr && MI->getOperand(1).isRegister() &&
699              MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
700              (MI->getNumOperands() == 3 ||
701               (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
702            && "Bad format for MRMDestReg!");
703
704     O << TII.getName(MI->getOpCode()) << " ";
705     printOp(MI->getOperand(0));
706     O << ", ";
707     printOp(MI->getOperand(1+isTwoAddr));
708     if (MI->getNumOperands() == 4) {
709       O << ", ";
710       printOp(MI->getOperand(3));
711     }
712     O << "\n";
713     return;
714   }
715
716   case X86II::MRMDestMem: {
717     // These instructions are the same as MRMDestReg, but instead of having a
718     // register reference for the mod/rm field, it's a memory reference.
719     //
720     assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
721            MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
722
723     O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
724     printMemReference(MI, 0);
725     O << ", ";
726     printOp(MI->getOperand(4));
727     O << "\n";
728     return;
729   }
730
731   case X86II::MRMSrcReg: {
732     // There are three forms that are acceptable for MRMSrcReg instructions,
733     // those with 3 and 2 operands:
734     //
735     // 3 Operands: in this form, the last register (the second input) is the
736     // ModR/M input.  The first two operands should be the same, post register
737     // allocation.  This is for things like: add r32, r/m32
738     //
739     // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
740     // instructions like the IMULri instructions.
741     //
742     // 2 Operands: this is for things like mov that do not read a second input
743     //
744     assert(MI->getOperand(0).isRegister() &&
745            MI->getOperand(1).isRegister() &&
746            (MI->getNumOperands() == 2 || 
747             (MI->getNumOperands() == 3 && 
748              (MI->getOperand(2).isRegister() ||
749               MI->getOperand(2).isImmediate())))
750            && "Bad format for MRMSrcReg!");
751     if (MI->getNumOperands() == 3 &&
752         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
753       O << "**";
754
755     O << TII.getName(MI->getOpCode()) << " ";
756     printOp(MI->getOperand(0));
757
758     // If this is IMULri* instructions, print the non-two-address operand.
759     if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
760       O << ", ";
761       printOp(MI->getOperand(1));
762     }
763
764     O << ", ";
765     printOp(MI->getOperand(MI->getNumOperands()-1));
766     O << "\n";
767     return;
768   }
769
770   case X86II::MRMSrcMem: {
771     // These instructions are the same as MRMSrcReg, but instead of having a
772     // register reference for the mod/rm field, it's a memory reference.
773     //
774     assert(MI->getOperand(0).isRegister() &&
775            (MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
776            (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() && 
777             isMem(MI, 2))
778            && "Bad format for MRMDestReg!");
779     if (MI->getNumOperands() == 2+4 &&
780         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
781       O << "**";
782
783     O << TII.getName(MI->getOpCode()) << " ";
784     printOp(MI->getOperand(0));
785     O << ", " << sizePtr(Desc) << " ";
786     printMemReference(MI, MI->getNumOperands()-4);
787     O << "\n";
788     return;
789   }
790
791   case X86II::MRMS0r: case X86II::MRMS1r:
792   case X86II::MRMS2r: case X86II::MRMS3r:
793   case X86II::MRMS4r: case X86II::MRMS5r:
794   case X86II::MRMS6r: case X86II::MRMS7r: {
795     // In this form, the following are valid formats:
796     //  1. sete r
797     //  2. cmp reg, immediate
798     //  2. shl rdest, rinput  <implicit CL or 1>
799     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
800     //    
801     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
802            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
803     assert((MI->getNumOperands() != 2 ||
804             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
805            "Bad MRMSxR format!");
806     assert((MI->getNumOperands() < 3 ||
807             (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
808            "Bad MRMSxR format!");
809
810     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
811         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
812       O << "**";
813
814     O << TII.getName(MI->getOpCode()) << " ";
815     printOp(MI->getOperand(0));
816     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
817       O << ", ";
818       printOp(MI->getOperand(MI->getNumOperands()-1));
819     }
820     checkImplUses(Desc);
821     O << "\n";
822
823     return;
824   }
825
826   case X86II::MRMS0m: case X86II::MRMS1m:
827   case X86II::MRMS2m: case X86II::MRMS3m:
828   case X86II::MRMS4m: case X86II::MRMS5m:
829   case X86II::MRMS6m: case X86II::MRMS7m: {
830     // In this form, the following are valid formats:
831     //  1. sete [m]
832     //  2. cmp [m], immediate
833     //  2. shl [m], rinput  <implicit CL or 1>
834     //  3. sbb [m], immediate
835     //    
836     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
837            isMem(MI, 0) && "Bad MRMSxM format!");
838     assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
839            "Bad MRMSxM format!");
840     // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
841     // is misassembled by gas in intel_syntax mode as its 32-bit
842     // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
843     // opcode bytes instead of the instruction.
844     if (MI->getOpCode() == X86::FSTPr80) {
845       if ((MI->getOperand(0).getReg() == X86::ESP)
846           && (MI->getOperand(1).getImmedValue() == 1)) {
847         int DispVal = MI->getOperand(3).getImmedValue();
848         if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
849           unsigned int val = (unsigned int) DispVal;
850           O << ".byte 0xdb, 0xbc, 0x24\n\t";
851           O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
852         } else { // 1 byte disp.
853           unsigned char val = (unsigned char) DispVal;
854           O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
855             << std::dec << "\t# ";
856         }
857       }
858     }
859     // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
860     // misassembled by gas in intel_syntax mode as its 32-bit
861     // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
862     // opcode bytes instead of the instruction.
863     if (MI->getOpCode() == X86::FLDr80) {
864       if ((MI->getOperand(0).getReg() == X86::ESP)
865           && (MI->getOperand(1).getImmedValue() == 1)) {
866         int DispVal = MI->getOperand(3).getImmedValue();
867         if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
868           unsigned int val = (unsigned int) DispVal;
869           O << ".byte 0xdb, 0xac, 0x24\n\t";
870           O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
871         } else { // 1 byte disp.
872           unsigned char val = (unsigned char) DispVal;
873           O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
874             << std::dec << "\t# ";
875         }
876       }
877     }
878     // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
879     // invalid opcode, saying "64 bit operations are only supported in
880     // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
881     // [...]", which is wrong. Workaround: Output the raw opcode bytes
882     // instead of the instruction.
883     if (MI->getOpCode() == X86::FILDr64) {
884       if ((MI->getOperand(0).getReg() == X86::ESP)
885           && (MI->getOperand(1).getImmedValue() == 1)) {
886         int DispVal = MI->getOperand(3).getImmedValue();
887         if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
888           unsigned int val = (unsigned int) DispVal;
889           O << ".byte 0xdf, 0xac, 0x24\n\t";
890           O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
891         } else { // 1 byte disp.
892           unsigned char val = (unsigned char) DispVal;
893           O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
894             << std::dec << "\t# ";
895         }
896       }
897     }
898     // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
899     // an invalid opcode, saying "64 bit operations are only
900     // supported in 64 bit modes." libopcodes disassembles it as
901     // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
902     // "fistpll DWORD PTR " instead, which is what libopcodes is
903     // expecting to see.
904     if (MI->getOpCode() == X86::FISTPr64) {
905       O << "fistpll DWORD PTR ";
906       printMemReference(MI, 0);
907       if (MI->getNumOperands() == 5) {
908         O << ", ";
909         printOp(MI->getOperand(4));
910       }
911       O << "\t# ";
912     }
913     
914     O << TII.getName(MI->getOpCode()) << " ";
915     O << sizePtr(Desc) << " ";
916     printMemReference(MI, 0);
917     if (MI->getNumOperands() == 5) {
918       O << ", ";
919       printOp(MI->getOperand(4));
920     }
921     O << "\n";
922     return;
923   }
924
925   default:
926     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
927   }
928 }
929
930 bool Printer::doInitialization(Module &M) {
931   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
932   //
933   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
934   // instruction as a reference to the register named sp, and if you try to
935   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
936   // before being looked up in the symbol table. This creates spurious
937   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
938   // mode, and decorate all register names with percent signs.
939   O << "\t.intel_syntax\n";
940   Mang = new Mangler(M, EmitCygwin);
941   return false; // success
942 }
943
944 // SwitchSection - Switch to the specified section of the executable if we are
945 // not already in it!
946 //
947 static void SwitchSection(std::ostream &OS, std::string &CurSection,
948                           const char *NewSection) {
949   if (CurSection != NewSection) {
950     CurSection = NewSection;
951     if (!CurSection.empty())
952       OS << "\t" << NewSection << "\n";
953   }
954 }
955
956 bool Printer::doFinalization(Module &M) {
957   const TargetData &TD = TM.getTargetData();
958   std::string CurSection;
959
960   // Print out module-level global variables here.
961   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
962     if (I->hasInitializer()) {   // External global require no code
963       O << "\n\n";
964       std::string name = Mang->getValueName(I);
965       Constant *C = I->getInitializer();
966       unsigned Size = TD.getTypeSize(C->getType());
967       unsigned Align = TD.getTypeAlignment(C->getType());
968
969       if (C->isNullValue() && 
970           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
971            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
972         SwitchSection(O, CurSection, ".data");
973         if (I->hasInternalLinkage())
974           O << "\t.local " << name << "\n";
975         
976         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
977           << "," << (unsigned)TD.getTypeAlignment(C->getType());
978         O << "\t\t# ";
979         WriteAsOperand(O, I, true, true, &M);
980         O << "\n";
981       } else {
982         switch (I->getLinkage()) {
983         case GlobalValue::LinkOnceLinkage:
984         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
985           // Nonnull linkonce -> weak
986           O << "\t.weak " << name << "\n";
987           SwitchSection(O, CurSection, "");
988           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
989           break;
990         
991         case GlobalValue::AppendingLinkage:
992           // FIXME: appending linkage variables should go into a section of
993           // their name or something.  For now, just emit them as external.
994         case GlobalValue::ExternalLinkage:
995           // If external or appending, declare as a global symbol
996           O << "\t.globl " << name << "\n";
997           // FALL THROUGH
998         case GlobalValue::InternalLinkage:
999           if (C->isNullValue())
1000             SwitchSection(O, CurSection, ".bss");
1001           else
1002             SwitchSection(O, CurSection, ".data");
1003           break;
1004         }
1005
1006         O << "\t.align " << Align << "\n";
1007         O << "\t.type " << name << ",@object\n";
1008         O << "\t.size " << name << "," << Size << "\n";
1009         O << name << ":\t\t\t\t# ";
1010         WriteAsOperand(O, I, true, true, &M);
1011         O << " = ";
1012         WriteAsOperand(O, C, false, false, &M);
1013         O << "\n";
1014         printConstantValueOnly(C);
1015       }
1016     }
1017
1018   delete Mang;
1019   return false; // success
1020 }