Better implementation of truncate. ISel matches it to a pseudo instruction
[oota-llvm.git] / lib / Target / X86 / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.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 representation
11 // of machine-dependent LLVM code to Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86IntelAsmPrinter.h"
17 #include "X86.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/Mangler.h"
22 #include "llvm/Target/TargetOptions.h"
23 using namespace llvm;
24
25 X86IntelAsmPrinter::X86IntelAsmPrinter(std::ostream &O, X86TargetMachine &TM)
26     : X86SharedAsmPrinter(O, TM) {
27 }
28
29 /// runOnMachineFunction - This uses the printMachineInstruction()
30 /// method to print assembly for each instruction.
31 ///
32 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
33   if (forDarwin) {
34     // Let PassManager know we need debug information and relay
35     // the MachineDebugInfo address on to DwarfWriter.
36     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
37   }
38
39   SetupMachineFunction(MF);
40   O << "\n\n";
41
42   // Print out constants referenced by the function
43   EmitConstantPool(MF.getConstantPool());
44
45   // Print out labels for the function.
46   SwitchSection(".code", MF.getFunction());
47   EmitAlignment(4);
48   if (MF.getFunction()->getLinkage() == GlobalValue::ExternalLinkage)
49     O << "\tpublic " << CurrentFnName << "\n";
50   O << CurrentFnName << "\tproc near\n";
51   
52   if (forDarwin) {
53     // Emit pre-function debug information.
54     DW.BeginFunction(&MF);
55   }
56
57   // Print out code for the function.
58   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
59        I != E; ++I) {
60     // Print a label for the basic block if there are any predecessors.
61     if (I->pred_begin() != I->pred_end()) {
62       printBasicBlockLabel(I, true);
63       O << '\n';
64     }
65     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
66          II != E; ++II) {
67       // Print the assembly for the instruction.
68       O << "\t";
69       printMachineInstruction(II);
70     }
71   }
72
73   if (forDarwin) {
74     // Emit post-function debug information.
75     DW.EndFunction();
76   }
77
78   O << CurrentFnName << "\tendp\n";
79
80   // We didn't modify anything.
81   return false;
82 }
83
84 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
85   unsigned char value = MI->getOperand(Op).getImmedValue();
86   assert(value <= 7 && "Invalid ssecc argument!");
87   switch (value) {
88   case 0: O << "eq"; break;
89   case 1: O << "lt"; break;
90   case 2: O << "le"; break;
91   case 3: O << "unord"; break;
92   case 4: O << "neq"; break;
93   case 5: O << "nlt"; break;
94   case 6: O << "nle"; break;
95   case 7: O << "ord"; break;
96   }
97 }
98
99 void X86IntelAsmPrinter::printOp(const MachineOperand &MO, 
100                                  const char *Modifier) {
101   const MRegisterInfo &RI = *TM.getRegisterInfo();
102   switch (MO.getType()) {
103   case MachineOperand::MO_Register:
104     if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
105       unsigned Reg = MO.getReg();
106       if (Modifier && strncmp(Modifier, "trunc", strlen("trunc")) == 0) {
107         MVT::ValueType VT = (strcmp(Modifier,"trunc16") == 0)
108           ? MVT::i16 : MVT::i32;
109         Reg = getX86SubSuperRegister(Reg, VT);
110       }
111       O << RI.get(Reg).Name;
112     } else
113       O << "reg" << MO.getReg();
114     return;
115
116   case MachineOperand::MO_Immediate:
117     O << (int)MO.getImmedValue();
118     return;
119   case MachineOperand::MO_MachineBasicBlock:
120     printBasicBlockLabel(MO.getMachineBasicBlock());
121     return;
122   case MachineOperand::MO_ConstantPoolIndex: {
123     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
124     if (!isMemOp) O << "OFFSET ";
125     O << "[" << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << "_"
126       << MO.getConstantPoolIndex();
127     if (forDarwin && TM.getRelocationModel() == Reloc::PIC)
128       O << "-\"L" << getFunctionNumber() << "$pb\"";
129     int Offset = MO.getOffset();
130     if (Offset > 0)
131       O << " + " << Offset;
132     else if (Offset < 0)
133       O << Offset;
134     O << "]";
135     return;
136   }
137   case MachineOperand::MO_GlobalAddress: {
138     bool isCallOp = Modifier && !strcmp(Modifier, "call");
139     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
140     if (!isMemOp && !isCallOp) O << "OFFSET ";
141     if (forDarwin && TM.getRelocationModel() != Reloc::Static) {
142       GlobalValue *GV = MO.getGlobal();
143       std::string Name = Mang->getValueName(GV);
144       if (!isMemOp && !isCallOp) O << '$';
145       // Link-once, External, or Weakly-linked global variables need
146       // non-lazily-resolved stubs
147       if (GV->isExternal() || GV->hasWeakLinkage() ||
148           GV->hasLinkOnceLinkage()) {
149         // Dynamically-resolved functions need a stub for the function.
150         if (isCallOp && isa<Function>(GV) && cast<Function>(GV)->isExternal()) {
151           FnStubs.insert(Name);
152           O << "L" << Name << "$stub";
153         } else {
154           GVStubs.insert(Name);
155           O << "L" << Name << "$non_lazy_ptr";
156         }
157       } else {
158         O << Mang->getValueName(GV);
159       }
160       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC)
161         O << "-\"L" << getFunctionNumber() << "$pb\"";
162     } else
163       O << Mang->getValueName(MO.getGlobal());
164     int Offset = MO.getOffset();
165     if (Offset > 0)
166       O << " + " << Offset;
167     else if (Offset < 0)
168       O << Offset;
169     return;
170   }
171   case MachineOperand::MO_ExternalSymbol: {
172     bool isCallOp = Modifier && !strcmp(Modifier, "call");
173     if (isCallOp && forDarwin && TM.getRelocationModel() != Reloc::Static) {
174       std::string Name(GlobalPrefix);
175       Name += MO.getSymbolName();
176       FnStubs.insert(Name);
177       O << "L" << Name << "$stub";
178       return;
179     }
180     if (!isCallOp) O << "OFFSET ";
181     O << GlobalPrefix << MO.getSymbolName();
182     return;
183   }
184   default:
185     O << "<unknown operand type>"; return;
186   }
187 }
188
189 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
190   assert(isMem(MI, Op) && "Invalid memory reference!");
191
192   const MachineOperand &BaseReg  = MI->getOperand(Op);
193   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
194   const MachineOperand &IndexReg = MI->getOperand(Op+2);
195   const MachineOperand &DispSpec = MI->getOperand(Op+3);
196
197   if (BaseReg.isFrameIndex()) {
198     O << "[frame slot #" << BaseReg.getFrameIndex();
199     if (DispSpec.getImmedValue())
200       O << " + " << DispSpec.getImmedValue();
201     O << "]";
202     return;
203   }
204
205   O << "[";
206   bool NeedPlus = false;
207   if (BaseReg.getReg()) {
208     printOp(BaseReg, "mem");
209     NeedPlus = true;
210   }
211
212   if (IndexReg.getReg()) {
213     if (NeedPlus) O << " + ";
214     if (ScaleVal != 1)
215       O << ScaleVal << "*";
216     printOp(IndexReg);
217     NeedPlus = true;
218   }
219
220   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex()) {
221     if (NeedPlus)
222       O << " + ";
223     printOp(DispSpec, "mem");
224   } else {
225     int DispVal = DispSpec.getImmedValue();
226     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
227       if (NeedPlus)
228         if (DispVal > 0)
229           O << " + ";
230         else {
231           O << " - ";
232           DispVal = -DispVal;
233         }
234       O << DispVal;
235     }
236   }
237   O << "]";
238 }
239
240 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
241   O << "\"L" << getFunctionNumber() << "$pb\"\n";
242   O << "\"L" << getFunctionNumber() << "$pb\":";
243 }
244
245 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
246                                            const char Mode) {
247   const MRegisterInfo &RI = *TM.getRegisterInfo();
248   unsigned Reg = MO.getReg();
249   switch (Mode) {
250   default: return true;  // Unknown mode.
251   case 'b': // Print QImode register
252     Reg = getX86SubSuperRegister(Reg, MVT::i8);
253     break;
254   case 'h': // Print QImode high register
255     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
256     break;
257   case 'w': // Print HImode register
258     Reg = getX86SubSuperRegister(Reg, MVT::i16);
259     break;
260   case 'k': // Print SImode register
261     Reg = getX86SubSuperRegister(Reg, MVT::i32);
262     break;
263   }
264
265   O << '%' << RI.get(Reg).Name;
266   return false;
267 }
268
269 /// PrintAsmOperand - Print out an operand for an inline asm expression.
270 ///
271 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
272                                          unsigned AsmVariant, 
273                                          const char *ExtraCode) {
274   // Does this asm operand have a single letter operand modifier?
275   if (ExtraCode && ExtraCode[0]) {
276     if (ExtraCode[1] != 0) return true; // Unknown modifier.
277     
278     switch (ExtraCode[0]) {
279     default: return true;  // Unknown modifier.
280     case 'b': // Print QImode register
281     case 'h': // Print QImode high register
282     case 'w': // Print HImode register
283     case 'k': // Print SImode register
284       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
285     }
286   }
287   
288   printOperand(MI, OpNo);
289   return false;
290 }
291
292 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
293                                                unsigned OpNo,
294                                                unsigned AsmVariant, 
295                                                const char *ExtraCode) {
296   if (ExtraCode && ExtraCode[0])
297     return true; // Unknown modifier.
298   printMemReference(MI, OpNo);
299   return false;
300 }
301
302 /// printMachineInstruction -- Print out a single X86 LLVM instruction
303 /// MI in Intel syntax to the current output stream.
304 ///
305 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
306   ++EmittedInsts;
307
308   // See if a truncate instruction can be turned into a nop.
309   switch (MI->getOpcode()) {
310   default: break;
311   case X86::TRUNC_R32_R16:
312   case X86::TRUNC_R32_R8:
313   case X86::TRUNC_R16_R8: {
314     const MachineOperand &MO0 = MI->getOperand(0);
315     const MachineOperand &MO1 = MI->getOperand(1);
316     unsigned Reg0 = MO0.getReg();
317     unsigned Reg1 = MO1.getReg();
318     if (MI->getOpcode() == X86::TRUNC_R16_R8)
319       Reg0 = getX86SubSuperRegister(Reg0, MVT::i16);
320     else
321       Reg0 = getX86SubSuperRegister(Reg0, MVT::i32);
322     if (Reg0 == Reg1)
323       O << CommentString << " TRUNCATE ";
324     break;
325   }
326   }
327
328   // Call the autogenerated instruction printer routines.
329   printInstruction(MI);
330 }
331
332 bool X86IntelAsmPrinter::doInitialization(Module &M) {
333   X86SharedAsmPrinter::doInitialization(M);
334   CommentString = ";";
335   GlobalPrefix = "_";
336   PrivateGlobalPrefix = "$";
337   AlignDirective = "\talign\t";
338   MLSections = true;
339   ZeroDirective = "\tdb\t";
340   ZeroDirectiveSuffix = " dup(0)";
341   AsciiDirective = "\tdb\t";
342   AscizDirective = 0;
343   Data8bitsDirective = "\t.db\t";
344   Data16bitsDirective = "\t.dw\t";
345   Data32bitsDirective = "\t.dd\t";
346   Data64bitsDirective = "\t.dq\t";
347   HasDotTypeDotSizeDirective = false;
348   Mang->markCharUnacceptable('.');
349
350   O << "\t.686\n\t.model flat\n\n";
351
352   // Emit declarations for external functions.
353   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
354     if (I->isExternal())
355       O << "\textern " << Mang->getValueName(I) << ":near\n";
356
357   // Emit declarations for external globals.
358   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
359        I != E; ++I) {
360     if (I->isExternal())
361       O << "\textern " << Mang->getValueName(I) << ":byte\n";
362     else if (I->getLinkage() == GlobalValue::ExternalLinkage)
363       O << "\tpublic " << Mang->getValueName(I) << "\n";
364   }
365
366   return false;
367 }
368
369 bool X86IntelAsmPrinter::doFinalization(Module &M) {
370   X86SharedAsmPrinter::doFinalization(M);
371   SwitchSection("", 0);
372   O << "\tend\n";
373   return false;
374 }
375
376 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
377   unsigned NumElts = CVA->getNumOperands();
378   if (NumElts) {
379     // ML does not have escape sequences except '' for '.  It also has a maximum
380     // string length of 255.
381     unsigned len = 0;
382     bool inString = false;
383     for (unsigned i = 0; i < NumElts; i++) {
384       int n = cast<ConstantInt>(CVA->getOperand(i))->getRawValue() & 255;
385       if (len == 0)
386         O << "\tdb ";
387
388       if (n >= 32 && n <= 127) {
389         if (!inString) {
390           if (len > 0) {
391             O << ",'";
392             len += 2;
393           } else {
394             O << "'";
395             len++;
396           }
397           inString = true;
398         }
399         if (n == '\'') {
400           O << "'";
401           len++;
402         }
403         O << char(n);
404       } else {
405         if (inString) {
406           O << "'";
407           len++;
408           inString = false;
409         }
410         if (len > 0) {
411           O << ",";
412           len++;
413         }
414         O << n;
415         len += 1 + (n > 9) + (n > 99);
416       }
417
418       if (len > 60) {
419         if (inString) {
420           O << "'";
421           inString = false;
422         }
423         O << "\n";
424         len = 0;
425       }
426     }
427
428     if (len > 0) {
429       if (inString)
430         O << "'";
431       O << "\n";
432     }
433   }
434 }
435
436 // Include the auto-generated portion of the assembly writer.
437 #include "X86GenAsmWriter1.inc"