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