Whoops, didn't mean to check this in yet.
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86ISelLowering.h"
21 #include "llvm/GlobalValue.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/SSARegMap.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/Statistic.h"
33 #include <iostream>
34 #include <set>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                      Pattern Matcher Implementation
39 //===----------------------------------------------------------------------===//
40
41 namespace {
42   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
43   /// SDOperand's instead of register numbers for the leaves of the matched
44   /// tree.
45   struct X86ISelAddressMode {
46     enum {
47       RegBase,
48       FrameIndexBase,
49       ConstantPoolBase
50     } BaseType;
51
52     struct {            // This is really a union, discriminated by BaseType!
53       SDOperand Reg;
54       int FrameIndex;
55     } Base;
56
57     unsigned Scale;
58     SDOperand IndexReg; 
59     unsigned Disp;
60     GlobalValue *GV;
61
62     X86ISelAddressMode()
63       : BaseType(RegBase), Scale(1), IndexReg(), Disp(0), GV(0) {
64     }
65   };
66 }
67
68 namespace {
69   Statistic<>
70   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
71
72   //===--------------------------------------------------------------------===//
73   /// ISel - X86 specific code to select X86 machine instructions for
74   /// SelectionDAG operations.
75   ///
76   class X86DAGToDAGISel : public SelectionDAGISel {
77     /// ContainsFPCode - Every instruction we select that uses or defines a FP
78     /// register should set this to true.
79     bool ContainsFPCode;
80
81     /// X86Lowering - This object fully describes how to lower LLVM code to an
82     /// X86-specific SelectionDAG.
83     X86TargetLowering X86Lowering;
84
85     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
86     /// make the right decision when generating code for different targets.
87     const X86Subtarget *Subtarget;
88   public:
89     X86DAGToDAGISel(TargetMachine &TM)
90       : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
91       Subtarget = &TM.getSubtarget<X86Subtarget>();
92     }
93
94     virtual const char *getPassName() const {
95       return "X86 DAG->DAG Instruction Selection";
96     }
97
98     /// InstructionSelectBasicBlock - This callback is invoked by
99     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
100     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
101
102     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
103
104 // Include the pieces autogenerated from the target description.
105 #include "X86GenDAGISel.inc"
106
107   private:
108     void Select(SDOperand &Result, SDOperand N);
109
110     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
111     bool SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
112                     SDOperand &Index, SDOperand &Disp);
113     bool SelectLEAAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
114                        SDOperand &Index, SDOperand &Disp);
115     bool TryFoldLoad(SDOperand P, SDOperand N,
116                      SDOperand &Base, SDOperand &Scale,
117                      SDOperand &Index, SDOperand &Disp);
118
119     inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base, 
120                                    SDOperand &Scale, SDOperand &Index,
121                                    SDOperand &Disp) {
122       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
123         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, MVT::i32) : AM.Base.Reg;
124       Scale = getI8Imm(AM.Scale);
125       Index = AM.IndexReg;
126       Disp  = AM.GV ? CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp)
127         : getI32Imm(AM.Disp);
128     }
129
130     /// getI8Imm - Return a target constant with the specified value, of type
131     /// i8.
132     inline SDOperand getI8Imm(unsigned Imm) {
133       return CurDAG->getTargetConstant(Imm, MVT::i8);
134     }
135
136     /// getI16Imm - Return a target constant with the specified value, of type
137     /// i16.
138     inline SDOperand getI16Imm(unsigned Imm) {
139       return CurDAG->getTargetConstant(Imm, MVT::i16);
140     }
141
142     /// getI32Imm - Return a target constant with the specified value, of type
143     /// i32.
144     inline SDOperand getI32Imm(unsigned Imm) {
145       return CurDAG->getTargetConstant(Imm, MVT::i32);
146     }
147
148 #ifndef NDEBUG
149     unsigned Indent;
150 #endif
151   };
152 }
153
154 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
155 /// when it has created a SelectionDAG for us to codegen.
156 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
157   DEBUG(BB->dump());
158   MachineFunction::iterator FirstMBB = BB;
159
160   // Codegen the basic block.
161 #ifndef NDEBUG
162   DEBUG(std::cerr << "===== Instruction selection begins:\n");
163   Indent = 0;
164 #endif
165   DAG.setRoot(SelectRoot(DAG.getRoot()));
166 #ifndef NDEBUG
167   DEBUG(std::cerr << "===== Instruction selection ends:\n");
168 #endif
169   CodeGenMap.clear();
170   DAG.RemoveDeadNodes();
171
172   // Emit machine code to BB. 
173   ScheduleAndEmitDAG(DAG);
174   
175   // If we are emitting FP stack code, scan the basic block to determine if this
176   // block defines any FP values.  If so, put an FP_REG_KILL instruction before
177   // the terminator of the block.
178   if (!Subtarget->hasSSE2()) {
179     // Note that FP stack instructions *are* used in SSE code when returning
180     // values, but these are not live out of the basic block, so we don't need
181     // an FP_REG_KILL in this case either.
182     bool ContainsFPCode = false;
183     
184     // Scan all of the machine instructions in these MBBs, checking for FP
185     // stores.
186     MachineFunction::iterator MBBI = FirstMBB;
187     do {
188       for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
189            !ContainsFPCode && I != E; ++I) {
190         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
191           if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
192               MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
193               RegMap->getRegClass(I->getOperand(0).getReg()) == 
194                 X86::RFPRegisterClass) {
195             ContainsFPCode = true;
196             break;
197           }
198         }
199       }
200     } while (!ContainsFPCode && &*(MBBI++) != BB);
201     
202     // Check PHI nodes in successor blocks.  These PHI's will be lowered to have
203     // a copy of the input value in this block.
204     if (!ContainsFPCode) {
205       // Final check, check LLVM BB's that are successors to the LLVM BB
206       // corresponding to BB for FP PHI nodes.
207       const BasicBlock *LLVMBB = BB->getBasicBlock();
208       const PHINode *PN;
209       for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
210            !ContainsFPCode && SI != E; ++SI) {
211         for (BasicBlock::const_iterator II = SI->begin();
212              (PN = dyn_cast<PHINode>(II)); ++II) {
213           if (PN->getType()->isFloatingPoint()) {
214             ContainsFPCode = true;
215             break;
216           }
217         }
218       }
219     }
220
221     // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
222     if (ContainsFPCode) {
223       BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
224       ++NumFPKill;
225     }
226   }
227 }
228
229 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
230 /// the main function.
231 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
232                                    MachineFrameInfo *MFI) {
233   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
234   int CWFrameIdx = MFI->CreateStackObject(2, 2);
235   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
236
237   // Set the high part to be 64-bit precision.
238   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
239                     CWFrameIdx, 1).addImm(2);
240
241   // Reload the modified control word now.
242   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
243 }
244
245 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
246   // If this is main, emit special code for main.
247   MachineBasicBlock *BB = MF.begin();
248   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
249     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
250 }
251
252 /// MatchAddress - Add the specified node to the specified addressing mode,
253 /// returning true if it cannot be done.  This just pattern matches for the
254 /// addressing mode
255 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
256                                    bool isRoot) {
257   bool StopHere = false;
258   // If N has already been selected, we may or may not want to fold its
259   // operands into the addressing mode. It will result in code duplication!
260   // FIXME: Right now we do. That is, as long as the selected target node
261   // does not produce a chain. This may require a more sophisticated heuristics.
262   std::map<SDOperand, SDOperand>::iterator CGMI= CodeGenMap.find(N.getValue(0));
263   if (CGMI != CodeGenMap.end()) {
264     if (isRoot)
265       // Stop here if it is a root. It's probably not profitable to go deeper.
266       StopHere = true;
267     else {
268       for (unsigned i = 0, e = CGMI->second.Val->getNumValues(); i != e; ++i) {
269         if (CGMI->second.Val->getValueType(i) == MVT::Other)
270           StopHere = true;
271       }
272     }
273   }
274
275   switch (N.getOpcode()) {
276   default: break;
277   case ISD::FrameIndex:
278     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
279       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
280       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
281       return false;
282     }
283     break;
284
285   case ISD::ConstantPool:
286     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
287       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N)) {
288         AM.BaseType = X86ISelAddressMode::ConstantPoolBase;
289         AM.Base.Reg = CurDAG->getTargetConstantPool(CP->get(), MVT::i32,
290                                                     CP->getAlignment());
291         return false;
292       }
293     }
294     break;
295
296   case ISD::GlobalAddress:
297   case ISD::TargetGlobalAddress:
298     if (AM.GV == 0) {
299       AM.GV = cast<GlobalAddressSDNode>(N)->getGlobal();
300       return false;
301     }
302     break;
303
304   case ISD::Constant:
305     AM.Disp += cast<ConstantSDNode>(N)->getValue();
306     return false;
307
308   case ISD::SHL:
309     if (!StopHere && AM.IndexReg.Val == 0 && AM.Scale == 1)
310       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
311         unsigned Val = CN->getValue();
312         if (Val == 1 || Val == 2 || Val == 3) {
313           AM.Scale = 1 << Val;
314           SDOperand ShVal = N.Val->getOperand(0);
315
316           // Okay, we know that we have a scale by now.  However, if the scaled
317           // value is an add of something and a constant, we can fold the
318           // constant into the disp field here.
319           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
320               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
321             AM.IndexReg = ShVal.Val->getOperand(0);
322             ConstantSDNode *AddVal =
323               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
324             AM.Disp += AddVal->getValue() << Val;
325           } else {
326             AM.IndexReg = ShVal;
327           }
328           return false;
329         }
330       }
331     break;
332
333   case ISD::MUL:
334     // X*[3,5,9] -> X+X*[2,4,8]
335     if (!StopHere && AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
336         AM.Base.Reg.Val == 0)
337       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
338         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
339           AM.Scale = unsigned(CN->getValue())-1;
340
341           SDOperand MulVal = N.Val->getOperand(0);
342           SDOperand Reg;
343
344           // Okay, we know that we have a scale by now.  However, if the scaled
345           // value is an add of something and a constant, we can fold the
346           // constant into the disp field here.
347           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
348               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
349             Reg = MulVal.Val->getOperand(0);
350             ConstantSDNode *AddVal =
351               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
352             AM.Disp += AddVal->getValue() * CN->getValue();
353           } else {
354             Reg = N.Val->getOperand(0);
355           }
356
357           AM.IndexReg = AM.Base.Reg = Reg;
358           return false;
359         }
360     break;
361
362   case ISD::ADD: {
363     if (!StopHere) {
364       X86ISelAddressMode Backup = AM;
365       if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
366           !MatchAddress(N.Val->getOperand(1), AM, false))
367         return false;
368       AM = Backup;
369       if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
370           !MatchAddress(N.Val->getOperand(0), AM, false))
371         return false;
372       AM = Backup;
373     }
374     break;
375   }
376   }
377
378   // Is the base register already occupied?
379   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
380     // If so, check to see if the scale index register is set.
381     if (AM.IndexReg.Val == 0) {
382       AM.IndexReg = N;
383       AM.Scale = 1;
384       return false;
385     }
386
387     // Otherwise, we cannot select it.
388     return true;
389   }
390
391   // Default, generate it as a register.
392   AM.BaseType = X86ISelAddressMode::RegBase;
393   AM.Base.Reg = N;
394   return false;
395 }
396
397 /// SelectAddr - returns true if it is able pattern match an addressing mode.
398 /// It returns the operands which make up the maximal addressing mode it can
399 /// match by reference.
400 bool X86DAGToDAGISel::SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
401                                  SDOperand &Index, SDOperand &Disp) {
402   X86ISelAddressMode AM;
403   if (MatchAddress(N, AM))
404     return false;
405
406   if (AM.BaseType == X86ISelAddressMode::RegBase) {
407     if (!AM.Base.Reg.Val)
408       AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
409   }
410
411   if (!AM.IndexReg.Val)
412     AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
413
414   getAddressOperands(AM, Base, Scale, Index, Disp);
415   return true;
416 }
417
418 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
419                                   SDOperand &Base, SDOperand &Scale,
420                                   SDOperand &Index, SDOperand &Disp) {
421   if (N.getOpcode() == ISD::LOAD &&
422       N.hasOneUse() &&
423       !CodeGenMap.count(N.getValue(0)) &&
424       (P.getNumOperands() == 1 || !isNonImmUse(P.Val, N.Val)))
425     return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp);
426   return false;
427 }
428
429 static bool isRegister0(SDOperand Op) {
430   if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op))
431     return (R->getReg() == 0);
432   return false;
433 }
434
435 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
436 /// mode it matches can be cost effectively emitted as an LEA instruction.
437 /// For X86, it always is unless it's just a (Reg + const).
438 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand N, SDOperand &Base,
439                                     SDOperand &Scale,
440                                     SDOperand &Index, SDOperand &Disp) {
441   X86ISelAddressMode AM;
442   if (!MatchAddress(N, AM)) {
443     bool SelectBase  = false;
444     bool SelectIndex = false;
445     bool Check       = false;
446     if (AM.BaseType == X86ISelAddressMode::RegBase) {
447       if (AM.Base.Reg.Val) {
448         Check      = true;
449         SelectBase = true;
450       } else {
451         AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
452       }
453     }
454
455     if (AM.IndexReg.Val) {
456       SelectIndex = true;
457     } else {
458       AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
459     }
460
461     if (Check) {
462       unsigned Complexity = 0;
463       if (AM.Scale > 1)
464         Complexity++;
465       if (SelectIndex)
466         Complexity++;
467       if (AM.GV)
468         Complexity++;
469       else if (AM.Disp > 1)
470         Complexity++;
471       if (Complexity <= 1)
472         return false;
473     }
474
475     getAddressOperands(AM, Base, Scale, Index, Disp);
476     return true;
477   }
478   return false;
479 }
480
481 void X86DAGToDAGISel::Select(SDOperand &Result, SDOperand N) {
482   SDNode *Node = N.Val;
483   MVT::ValueType NVT = Node->getValueType(0);
484   unsigned Opc, MOpc;
485   unsigned Opcode = Node->getOpcode();
486
487 #ifndef NDEBUG
488   DEBUG(std::cerr << std::string(Indent, ' '));
489   DEBUG(std::cerr << "Selecting: ");
490   DEBUG(Node->dump(CurDAG));
491   DEBUG(std::cerr << "\n");
492   Indent += 2;
493 #endif
494
495   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
496     Result = N;
497 #ifndef NDEBUG
498     DEBUG(std::cerr << std::string(Indent-2, ' '));
499     DEBUG(std::cerr << "== ");
500     DEBUG(Node->dump(CurDAG));
501     DEBUG(std::cerr << "\n");
502     Indent -= 2;
503 #endif
504     return;   // Already selected.
505   }
506
507   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);
508   if (CGMI != CodeGenMap.end()) {
509     Result = CGMI->second;
510 #ifndef NDEBUG
511     DEBUG(std::cerr << std::string(Indent-2, ' '));
512     DEBUG(std::cerr << "== ");
513     DEBUG(Result.Val->dump(CurDAG));
514     DEBUG(std::cerr << "\n");
515     Indent -= 2;
516 #endif
517     return;
518   }
519   
520   switch (Opcode) {
521     default: break;
522     case ISD::MULHU:
523     case ISD::MULHS: {
524       if (Opcode == ISD::MULHU)
525         switch (NVT) {
526         default: assert(0 && "Unsupported VT!");
527         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
528         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
529         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
530         }
531       else
532         switch (NVT) {
533         default: assert(0 && "Unsupported VT!");
534         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
535         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
536         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
537         }
538
539       unsigned LoReg, HiReg;
540       switch (NVT) {
541       default: assert(0 && "Unsupported VT!");
542       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
543       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
544       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
545       }
546
547       SDOperand N0 = Node->getOperand(0);
548       SDOperand N1 = Node->getOperand(1);
549
550       bool foldedLoad = false;
551       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
552       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
553       // MULHU and MULHS are commmutative
554       if (!foldedLoad) {
555         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
556         if (foldedLoad) {
557           N0 = Node->getOperand(1);
558           N1 = Node->getOperand(0);
559         }
560       }
561
562       SDOperand Chain;
563       if (foldedLoad)
564         Select(Chain, N1.getOperand(0));
565       else
566         Chain = CurDAG->getEntryNode();
567
568       SDOperand InFlag(0, 0);
569       Select(N0, N0);
570       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
571                                     N0, InFlag);
572       InFlag = Chain.getValue(1);
573
574       if (foldedLoad) {
575         Select(Tmp0, Tmp0);
576         Select(Tmp1, Tmp1);
577         Select(Tmp2, Tmp2);
578         Select(Tmp3, Tmp3);
579         SDNode *CNode =
580           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
581                                 Tmp2, Tmp3, Chain, InFlag);
582         Chain  = SDOperand(CNode, 0);
583         InFlag = SDOperand(CNode, 1);
584       } else {
585         Select(N1, N1);
586         InFlag =
587           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
588       }
589
590       Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
591       CodeGenMap[N.getValue(0)] = Result;
592       if (foldedLoad) {
593         CodeGenMap[N1.getValue(1)] = Result.getValue(1);
594         AddHandleReplacement(N1.Val, 1, Result.Val, 1);
595       }
596
597 #ifndef NDEBUG
598       DEBUG(std::cerr << std::string(Indent-2, ' '));
599       DEBUG(std::cerr << "== ");
600       DEBUG(Result.Val->dump(CurDAG));
601       DEBUG(std::cerr << "\n");
602       Indent -= 2;
603 #endif
604       return;
605     }
606
607     case ISD::SDIV:
608     case ISD::UDIV:
609     case ISD::SREM:
610     case ISD::UREM: {
611       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
612       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
613       if (!isSigned)
614         switch (NVT) {
615         default: assert(0 && "Unsupported VT!");
616         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
617         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
618         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
619         }
620       else
621         switch (NVT) {
622         default: assert(0 && "Unsupported VT!");
623         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
624         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
625         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
626         }
627
628       unsigned LoReg, HiReg;
629       unsigned ClrOpcode, SExtOpcode;
630       switch (NVT) {
631       default: assert(0 && "Unsupported VT!");
632       case MVT::i8:
633         LoReg = X86::AL;  HiReg = X86::AH;
634         ClrOpcode  = X86::MOV8ri;
635         SExtOpcode = X86::CBW;
636         break;
637       case MVT::i16:
638         LoReg = X86::AX;  HiReg = X86::DX;
639         ClrOpcode  = X86::MOV16ri;
640         SExtOpcode = X86::CWD;
641         break;
642       case MVT::i32:
643         LoReg = X86::EAX; HiReg = X86::EDX;
644         ClrOpcode  = X86::MOV32ri;
645         SExtOpcode = X86::CDQ;
646         break;
647       }
648
649       SDOperand N0 = Node->getOperand(0);
650       SDOperand N1 = Node->getOperand(1);
651
652       bool foldedLoad = false;
653       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
654       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
655       SDOperand Chain;
656       if (foldedLoad)
657         Select(Chain, N1.getOperand(0));
658       else
659         Chain = CurDAG->getEntryNode();
660
661       SDOperand InFlag(0, 0);
662       Select(N0, N0);
663       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
664                                     N0, InFlag);
665       InFlag = Chain.getValue(1);
666
667       if (isSigned) {
668         // Sign extend the low part into the high part.
669         InFlag =
670           SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
671       } else {
672         // Zero out the high part, effectively zero extending the input.
673         SDOperand ClrNode =
674           SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT,
675                                          CurDAG->getTargetConstant(0, NVT)), 0);
676         Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
677                                       ClrNode, InFlag);
678         InFlag = Chain.getValue(1);
679       }
680
681       if (foldedLoad) {
682         Select(Tmp0, Tmp0);
683         Select(Tmp1, Tmp1);
684         Select(Tmp2, Tmp2);
685         Select(Tmp3, Tmp3);
686         SDNode *CNode =
687           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
688                                 Tmp2, Tmp3, Chain, InFlag);
689         Chain  = SDOperand(CNode, 0);
690         InFlag = SDOperand(CNode, 1);
691       } else {
692         Select(N1, N1);
693         InFlag =
694           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
695       }
696
697       Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
698                                       NVT, InFlag);
699       CodeGenMap[N.getValue(0)] = Result;
700       if (foldedLoad) {
701         CodeGenMap[N1.getValue(1)] = Result.getValue(1);
702         AddHandleReplacement(N1.Val, 1, Result.Val, 1);
703       }
704
705 #ifndef NDEBUG
706       DEBUG(std::cerr << std::string(Indent-2, ' '));
707       DEBUG(std::cerr << "== ");
708       DEBUG(Result.Val->dump(CurDAG));
709       DEBUG(std::cerr << "\n");
710       Indent -= 2;
711 #endif
712       return;
713     }
714
715     case ISD::TRUNCATE: {
716       unsigned Reg;
717       MVT::ValueType VT;
718       switch (Node->getOperand(0).getValueType()) {
719         default: assert(0 && "Unknown truncate!");
720         case MVT::i16: Reg = X86::AX;  Opc = X86::MOV16rr; VT = MVT::i16; break;
721         case MVT::i32: Reg = X86::EAX; Opc = X86::MOV32rr; VT = MVT::i32; break;
722       }
723       SDOperand Tmp0, Tmp1;
724       Select(Tmp0, Node->getOperand(0));
725       Select(Tmp1, SDOperand(CurDAG->getTargetNode(Opc, VT, Tmp0), 0));
726       SDOperand InFlag = SDOperand(0,0);
727       Result = CurDAG->getCopyToReg(CurDAG->getEntryNode(), Reg, Tmp1, InFlag);
728       SDOperand Chain = Result.getValue(0);
729       InFlag = Result.getValue(1);
730
731       switch (NVT) {
732         default: assert(0 && "Unknown truncate!");
733         case MVT::i8:  Reg = X86::AL;  Opc = X86::MOV8rr;  VT = MVT::i8;  break;
734         case MVT::i16: Reg = X86::AX;  Opc = X86::MOV16rr; VT = MVT::i16; break;
735       }
736
737       Result = CurDAG->getCopyFromReg(Chain, Reg, VT, InFlag);
738       if (N.Val->hasOneUse())
739         Result = CurDAG->SelectNodeTo(N.Val, Opc, VT, Result);
740       else
741         Result = CodeGenMap[N] =
742           SDOperand(CurDAG->getTargetNode(Opc, VT, Result), 0);
743
744 #ifndef NDEBUG
745       DEBUG(std::cerr << std::string(Indent-2, ' '));
746       DEBUG(std::cerr << "== ");
747       DEBUG(Result.Val->dump(CurDAG));
748       DEBUG(std::cerr << "\n");
749       Indent -= 2;
750 #endif
751       return;
752     }
753   }
754
755   SelectCode(Result, N);
756 #ifndef NDEBUG
757   DEBUG(std::cerr << std::string(Indent-2, ' '));
758   DEBUG(std::cerr << "=> ");
759   DEBUG(Result.Val->dump(CurDAG));
760   DEBUG(std::cerr << "\n");
761   Indent -= 2;
762 #endif
763 }
764
765 /// createX86ISelDag - This pass converts a legalized DAG into a 
766 /// X86-specific DAG, ready for instruction scheduling.
767 ///
768 FunctionPass *llvm::createX86ISelDag(TargetMachine &TM) {
769   return new X86DAGToDAGISel(TM);
770 }