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