Mark re-materializable instructions.
[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 "x86-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/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/ADT/Statistic.h"
38 #include <queue>
39 #include <set>
40 using namespace llvm;
41
42 STATISTIC(NumFPKill   , "Number of FP_REG_KILL instructions added");
43 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
44
45
46 //===----------------------------------------------------------------------===//
47 //                      Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
49
50 namespace {
51   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52   /// SDOperand's instead of register numbers for the leaves of the matched
53   /// tree.
54   struct X86ISelAddressMode {
55     enum {
56       RegBase,
57       FrameIndexBase
58     } BaseType;
59
60     struct {            // This is really a union, discriminated by BaseType!
61       SDOperand Reg;
62       int FrameIndex;
63     } Base;
64
65     bool isRIPRel;     // RIP relative?
66     unsigned Scale;
67     SDOperand IndexReg; 
68     unsigned Disp;
69     GlobalValue *GV;
70     Constant *CP;
71     const char *ES;
72     int JT;
73     unsigned Align;    // CP alignment.
74
75     X86ISelAddressMode()
76       : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
77         GV(0), CP(0), ES(0), JT(-1), Align(0) {
78     }
79   };
80 }
81
82 namespace {
83   //===--------------------------------------------------------------------===//
84   /// ISel - X86 specific code to select X86 machine instructions for
85   /// SelectionDAG operations.
86   ///
87   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
88     /// ContainsFPCode - Every instruction we select that uses or defines a FP
89     /// register should set this to true.
90     bool ContainsFPCode;
91
92     /// FastISel - Enable fast(er) instruction selection.
93     ///
94     bool FastISel;
95
96     /// TM - Keep a reference to X86TargetMachine.
97     ///
98     X86TargetMachine &TM;
99
100     /// X86Lowering - This object fully describes how to lower LLVM code to an
101     /// X86-specific SelectionDAG.
102     X86TargetLowering X86Lowering;
103
104     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
105     /// make the right decision when generating code for different targets.
106     const X86Subtarget *Subtarget;
107
108     /// GlobalBaseReg - keeps track of the virtual register mapped onto global
109     /// base register.
110     unsigned GlobalBaseReg;
111
112   public:
113     X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
114       : SelectionDAGISel(X86Lowering),
115         ContainsFPCode(false), FastISel(fast), TM(tm),
116         X86Lowering(*TM.getTargetLowering()),
117         Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
118
119     virtual bool runOnFunction(Function &Fn) {
120       // Make sure we re-emit a set of the global base reg if necessary
121       GlobalBaseReg = 0;
122       return SelectionDAGISel::runOnFunction(Fn);
123     }
124    
125     virtual const char *getPassName() const {
126       return "X86 DAG->DAG Instruction Selection";
127     }
128
129     /// InstructionSelectBasicBlock - This callback is invoked by
130     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
131     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
132
133     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
134
135     virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root);
136
137 // Include the pieces autogenerated from the target description.
138 #include "X86GenDAGISel.inc"
139
140   private:
141     SDNode *Select(SDOperand N);
142
143     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
144     bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
145                     SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
146     bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
147                        SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
148     bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
149                              SDOperand N, SDOperand &Base, SDOperand &Scale,
150                              SDOperand &Index, SDOperand &Disp,
151                              SDOperand &InChain, SDOperand &OutChain);
152     bool TryFoldLoad(SDOperand P, SDOperand N,
153                      SDOperand &Base, SDOperand &Scale,
154                      SDOperand &Index, SDOperand &Disp);
155     void InstructionSelectPreprocess(SelectionDAG &DAG);
156
157     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
158     /// inline asm expressions.
159     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
160                                               char ConstraintCode,
161                                               std::vector<SDOperand> &OutOps,
162                                               SelectionDAG &DAG);
163     
164     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
165
166     inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base, 
167                                    SDOperand &Scale, SDOperand &Index,
168                                    SDOperand &Disp) {
169       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
170         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
171         AM.Base.Reg;
172       Scale = getI8Imm(AM.Scale);
173       Index = AM.IndexReg;
174       // These are 32-bit even in 64-bit mode since RIP relative offset
175       // is 32-bit.
176       if (AM.GV)
177         Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
178       else if (AM.CP)
179         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
180       else if (AM.ES)
181         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
182       else if (AM.JT != -1)
183         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
184       else
185         Disp = getI32Imm(AM.Disp);
186     }
187
188     /// getI8Imm - Return a target constant with the specified value, of type
189     /// i8.
190     inline SDOperand getI8Imm(unsigned Imm) {
191       return CurDAG->getTargetConstant(Imm, MVT::i8);
192     }
193
194     /// getI16Imm - Return a target constant with the specified value, of type
195     /// i16.
196     inline SDOperand getI16Imm(unsigned Imm) {
197       return CurDAG->getTargetConstant(Imm, MVT::i16);
198     }
199
200     /// getI32Imm - Return a target constant with the specified value, of type
201     /// i32.
202     inline SDOperand getI32Imm(unsigned Imm) {
203       return CurDAG->getTargetConstant(Imm, MVT::i32);
204     }
205
206     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
207     /// base register.  Return the virtual register that holds this value.
208     SDNode *getGlobalBaseReg();
209
210 #ifndef NDEBUG
211     unsigned Indent;
212 #endif
213   };
214 }
215
216 static SDNode *findFlagUse(SDNode *N) {
217   unsigned FlagResNo = N->getNumValues()-1;
218   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
219     SDNode *User = *I;
220     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
221       SDOperand Op = User->getOperand(i);
222       if (Op.Val == N && Op.ResNo == FlagResNo)
223         return User;
224     }
225   }
226   return NULL;
227 }
228
229 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
230                           SDNode *Root, SDNode *Skip, bool &found,
231                           std::set<SDNode *> &Visited) {
232   if (found ||
233       Use->getNodeId() > Def->getNodeId() ||
234       !Visited.insert(Use).second)
235     return;
236
237   for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
238     SDNode *N = Use->getOperand(i).Val;
239     if (N == Skip)
240       continue;
241     if (N == Def) {
242       if (Use == ImmedUse)
243         continue; // Immediate use is ok.
244       if (Use == Root) {
245         assert(Use->getOpcode() == ISD::STORE ||
246                Use->getOpcode() == X86ISD::CMP);
247         continue;
248       }
249       found = true;
250       break;
251     }
252     findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
253   }
254 }
255
256 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
257 /// be reached. Return true if that's the case. However, ignore direct uses
258 /// by ImmedUse (which would be U in the example illustrated in
259 /// CanBeFoldedBy) and by Root (which can happen in the store case).
260 /// FIXME: to be really generic, we should allow direct use by any node
261 /// that is being folded. But realisticly since we only fold loads which
262 /// have one non-chain use, we only need to watch out for load/op/store
263 /// and load/op/cmp case where the root (store / cmp) may reach the load via
264 /// its chain operand.
265 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
266                                SDNode *Skip = NULL) {
267   std::set<SDNode *> Visited;
268   bool found = false;
269   findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
270   return found;
271 }
272
273
274 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) {
275   if (FastISel) return false;
276
277   // If U use can somehow reach N through another path then U can't fold N or
278   // it will create a cycle. e.g. In the following diagram, U can reach N
279   // through X. If N is folded into into U, then X is both a predecessor and
280   // a successor of U.
281   //
282   //         [ N ]
283   //         ^  ^
284   //         |  |
285   //        /   \---
286   //      /        [X]
287   //      |         ^
288   //     [U]--------|
289
290   if (isNonImmUse(Root, N, U))
291     return false;
292
293   // If U produces a flag, then it gets (even more) interesting. Since it
294   // would have been "glued" together with its flag use, we need to check if
295   // it might reach N:
296   //
297   //       [ N ]
298   //        ^ ^
299   //        | |
300   //       [U] \--
301   //        ^   [TF]
302   //        |    ^
303   //        |    |
304   //         \  /
305   //          [FU]
306   //
307   // If FU (flag use) indirectly reach N (the load), and U fold N (call it
308   // NU), then TF is a predecessor of FU and a successor of NU. But since
309   // NU and FU are flagged together, this effectively creates a cycle.
310   bool HasFlagUse = false;
311   MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
312   while ((VT == MVT::Flag && !Root->use_empty())) {
313     SDNode *FU = findFlagUse(Root);
314     if (FU == NULL)
315       break;
316     else {
317       Root = FU;
318       HasFlagUse = true;
319     }
320     VT = Root->getValueType(Root->getNumValues()-1);
321   }
322
323   if (HasFlagUse)
324     return !isNonImmUse(Root, N, Root, U);
325   return true;
326 }
327
328 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
329 /// and move load below the TokenFactor. Replace store's chain operand with
330 /// load's chain result.
331 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
332                                  SDOperand Store, SDOperand TF) {
333   std::vector<SDOperand> Ops;
334   for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
335     if (Load.Val == TF.Val->getOperand(i).Val)
336       Ops.push_back(Load.Val->getOperand(0));
337     else
338       Ops.push_back(TF.Val->getOperand(i));
339   DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
340   DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
341   DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
342                          Store.getOperand(2), Store.getOperand(3));
343 }
344
345 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
346 /// selector to pick more load-modify-store instructions. This is a common
347 /// case:
348 ///
349 ///     [Load chain]
350 ///         ^
351 ///         |
352 ///       [Load]
353 ///       ^    ^
354 ///       |    |
355 ///      /      \-
356 ///     /         |
357 /// [TokenFactor] [Op]
358 ///     ^          ^
359 ///     |          |
360 ///      \        /
361 ///       \      /
362 ///       [Store]
363 ///
364 /// The fact the store's chain operand != load's chain will prevent the
365 /// (store (op (load))) instruction from being selected. We can transform it to:
366 ///
367 ///     [Load chain]
368 ///         ^
369 ///         |
370 ///    [TokenFactor]
371 ///         ^
372 ///         |
373 ///       [Load]
374 ///       ^    ^
375 ///       |    |
376 ///       |     \- 
377 ///       |       | 
378 ///       |     [Op]
379 ///       |       ^
380 ///       |       |
381 ///       \      /
382 ///        \    /
383 ///       [Store]
384 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
385   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
386          E = DAG.allnodes_end(); I != E; ++I) {
387     if (!ISD::isNON_TRUNCStore(I))
388       continue;
389     SDOperand Chain = I->getOperand(0);
390     if (Chain.Val->getOpcode() != ISD::TokenFactor)
391       continue;
392
393     SDOperand N1 = I->getOperand(1);
394     SDOperand N2 = I->getOperand(2);
395     if (MVT::isFloatingPoint(N1.getValueType()) ||
396         MVT::isVector(N1.getValueType()) ||
397         !N1.hasOneUse())
398       continue;
399
400     bool RModW = false;
401     SDOperand Load;
402     unsigned Opcode = N1.Val->getOpcode();
403     switch (Opcode) {
404       case ISD::ADD:
405       case ISD::MUL:
406       case ISD::AND:
407       case ISD::OR:
408       case ISD::XOR:
409       case ISD::ADDC:
410       case ISD::ADDE: {
411         SDOperand N10 = N1.getOperand(0);
412         SDOperand N11 = N1.getOperand(1);
413         if (ISD::isNON_EXTLoad(N10.Val))
414           RModW = true;
415         else if (ISD::isNON_EXTLoad(N11.Val)) {
416           RModW = true;
417           std::swap(N10, N11);
418         }
419         RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
420           (N10.getOperand(1) == N2) &&
421           (N10.Val->getValueType(0) == N1.getValueType());
422         if (RModW)
423           Load = N10;
424         break;
425       }
426       case ISD::SUB:
427       case ISD::SHL:
428       case ISD::SRA:
429       case ISD::SRL:
430       case ISD::ROTL:
431       case ISD::ROTR:
432       case ISD::SUBC:
433       case ISD::SUBE:
434       case X86ISD::SHLD:
435       case X86ISD::SHRD: {
436         SDOperand N10 = N1.getOperand(0);
437         if (ISD::isNON_EXTLoad(N10.Val))
438           RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
439             (N10.getOperand(1) == N2) &&
440             (N10.Val->getValueType(0) == N1.getValueType());
441         if (RModW)
442           Load = N10;
443         break;
444       }
445     }
446
447     if (RModW) {
448       MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
449       ++NumLoadMoved;
450     }
451   }
452 }
453
454 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
455 /// when it has created a SelectionDAG for us to codegen.
456 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
457   DEBUG(BB->dump());
458   MachineFunction::iterator FirstMBB = BB;
459
460   if (!FastISel)
461     InstructionSelectPreprocess(DAG);
462
463   // Codegen the basic block.
464 #ifndef NDEBUG
465   DOUT << "===== Instruction selection begins:\n";
466   Indent = 0;
467 #endif
468   DAG.setRoot(SelectRoot(DAG.getRoot()));
469 #ifndef NDEBUG
470   DOUT << "===== Instruction selection ends:\n";
471 #endif
472
473   DAG.RemoveDeadNodes();
474
475   // Emit machine code to BB. 
476   ScheduleAndEmitDAG(DAG);
477   
478   // If we are emitting FP stack code, scan the basic block to determine if this
479   // block defines any FP values.  If so, put an FP_REG_KILL instruction before
480   // the terminator of the block.
481   if (!Subtarget->hasSSE2()) {
482     // Note that FP stack instructions *are* used in SSE code when returning
483     // values, but these are not live out of the basic block, so we don't need
484     // an FP_REG_KILL in this case either.
485     bool ContainsFPCode = false;
486     
487     // Scan all of the machine instructions in these MBBs, checking for FP
488     // stores.
489     MachineFunction::iterator MBBI = FirstMBB;
490     do {
491       for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
492            !ContainsFPCode && I != E; ++I) {
493         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
494           if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
495               MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
496               RegMap->getRegClass(I->getOperand(0).getReg()) == 
497                 X86::RFPRegisterClass) {
498             ContainsFPCode = true;
499             break;
500           }
501         }
502       }
503     } while (!ContainsFPCode && &*(MBBI++) != BB);
504     
505     // Check PHI nodes in successor blocks.  These PHI's will be lowered to have
506     // a copy of the input value in this block.
507     if (!ContainsFPCode) {
508       // Final check, check LLVM BB's that are successors to the LLVM BB
509       // corresponding to BB for FP PHI nodes.
510       const BasicBlock *LLVMBB = BB->getBasicBlock();
511       const PHINode *PN;
512       for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
513            !ContainsFPCode && SI != E; ++SI) {
514         for (BasicBlock::const_iterator II = SI->begin();
515              (PN = dyn_cast<PHINode>(II)); ++II) {
516           if (PN->getType()->isFloatingPoint()) {
517             ContainsFPCode = true;
518             break;
519           }
520         }
521       }
522     }
523
524     // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
525     if (ContainsFPCode) {
526       BuildMI(*BB, BB->getFirstTerminator(),
527               TM.getInstrInfo()->get(X86::FP_REG_KILL));
528       ++NumFPKill;
529     }
530   }
531 }
532
533 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
534 /// the main function.
535 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
536                                              MachineFrameInfo *MFI) {
537   const TargetInstrInfo *TII = TM.getInstrInfo();
538   if (Subtarget->isTargetCygMing())
539     BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
540
541   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
542   int CWFrameIdx = MFI->CreateStackObject(2, 2);
543   addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
544
545   // Set the high part to be 64-bit precision.
546   addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
547                     CWFrameIdx, 1).addImm(2);
548
549   // Reload the modified control word now.
550   addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
551 }
552
553 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
554   // If this is main, emit special code for main.
555   MachineBasicBlock *BB = MF.begin();
556   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
557     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
558 }
559
560 /// MatchAddress - Add the specified node to the specified addressing mode,
561 /// returning true if it cannot be done.  This just pattern matches for the
562 /// addressing mode
563 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
564                                    bool isRoot) {
565   // RIP relative addressing: %rip + 32-bit displacement!
566   if (AM.isRIPRel) {
567     if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
568       int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
569       if (isInt32(AM.Disp + Val)) {
570         AM.Disp += Val;
571         return false;
572       }
573     }
574     return true;
575   }
576
577   int id = N.Val->getNodeId();
578   bool Available = isSelected(id);
579
580   switch (N.getOpcode()) {
581   default: break;
582   case ISD::Constant: {
583     int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
584     if (isInt32(AM.Disp + Val)) {
585       AM.Disp += Val;
586       return false;
587     }
588     break;
589   }
590
591   case X86ISD::Wrapper: {
592     bool is64Bit = Subtarget->is64Bit();
593     // Under X86-64 non-small code model, GV (and friends) are 64-bits.
594     if (is64Bit && TM.getCodeModel() != CodeModel::Small)
595       break;
596     if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
597       break;
598     // If value is available in a register both base and index components have
599     // been picked, we can't fit the result available in the register in the
600     // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
601     if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
602       bool isStatic = TM.getRelocationModel() == Reloc::Static;
603       SDOperand N0 = N.getOperand(0);
604       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
605         GlobalValue *GV = G->getGlobal();
606         bool isAbs32 = !is64Bit || isStatic;
607         if (isAbs32 || isRoot) {
608           AM.GV = GV;
609           AM.Disp += G->getOffset();
610           AM.isRIPRel = !isAbs32;
611           return false;
612         }
613       } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
614         if (!is64Bit || isStatic || isRoot) {
615           AM.CP = CP->getConstVal();
616           AM.Align = CP->getAlignment();
617           AM.Disp += CP->getOffset();
618           AM.isRIPRel = !isStatic;
619           return false;
620         }
621       } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
622         if (isStatic || isRoot) {
623           AM.ES = S->getSymbol();
624           AM.isRIPRel = !isStatic;
625           return false;
626         }
627       } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
628         if (isStatic || isRoot) {
629           AM.JT = J->getIndex();
630           AM.isRIPRel = !isStatic;
631           return false;
632         }
633       }
634     }
635     break;
636   }
637
638   case ISD::FrameIndex:
639     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
640       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
641       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
642       return false;
643     }
644     break;
645
646   case ISD::SHL:
647     if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
648       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
649         unsigned Val = CN->getValue();
650         if (Val == 1 || Val == 2 || Val == 3) {
651           AM.Scale = 1 << Val;
652           SDOperand ShVal = N.Val->getOperand(0);
653
654           // Okay, we know that we have a scale by now.  However, if the scaled
655           // value is an add of something and a constant, we can fold the
656           // constant into the disp field here.
657           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
658               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
659             AM.IndexReg = ShVal.Val->getOperand(0);
660             ConstantSDNode *AddVal =
661               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
662             uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
663             if (isInt32(Disp))
664               AM.Disp = Disp;
665             else
666               AM.IndexReg = ShVal;
667           } else {
668             AM.IndexReg = ShVal;
669           }
670           return false;
671         }
672       }
673     break;
674
675   case ISD::MUL:
676     // X*[3,5,9] -> X+X*[2,4,8]
677     if (!Available &&
678         AM.BaseType == X86ISelAddressMode::RegBase &&
679         AM.Base.Reg.Val == 0 &&
680         AM.IndexReg.Val == 0) {
681       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
682         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
683           AM.Scale = unsigned(CN->getValue())-1;
684
685           SDOperand MulVal = N.Val->getOperand(0);
686           SDOperand Reg;
687
688           // Okay, we know that we have a scale by now.  However, if the scaled
689           // value is an add of something and a constant, we can fold the
690           // constant into the disp field here.
691           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
692               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
693             Reg = MulVal.Val->getOperand(0);
694             ConstantSDNode *AddVal =
695               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
696             uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
697             if (isInt32(Disp))
698               AM.Disp = Disp;
699             else
700               Reg = N.Val->getOperand(0);
701           } else {
702             Reg = N.Val->getOperand(0);
703           }
704
705           AM.IndexReg = AM.Base.Reg = Reg;
706           return false;
707         }
708     }
709     break;
710
711   case ISD::ADD:
712     if (!Available) {
713       X86ISelAddressMode Backup = AM;
714       if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
715           !MatchAddress(N.Val->getOperand(1), AM, false))
716         return false;
717       AM = Backup;
718       if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
719           !MatchAddress(N.Val->getOperand(0), AM, false))
720         return false;
721       AM = Backup;
722     }
723     break;
724
725   case ISD::OR:
726     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
727     if (!Available) {
728       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
729         X86ISelAddressMode Backup = AM;
730         // Start with the LHS as an addr mode.
731         if (!MatchAddress(N.getOperand(0), AM, false) &&
732             // Address could not have picked a GV address for the displacement.
733             AM.GV == NULL &&
734             // On x86-64, the resultant disp must fit in 32-bits.
735             isInt32(AM.Disp + CN->getSignExtended()) &&
736             // Check to see if the LHS & C is zero.
737             TLI.MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
738           AM.Disp += CN->getValue();
739           return false;
740         }
741         AM = Backup;
742       }
743     }
744     break;
745   }
746
747   // Is the base register already occupied?
748   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
749     // If so, check to see if the scale index register is set.
750     if (AM.IndexReg.Val == 0) {
751       AM.IndexReg = N;
752       AM.Scale = 1;
753       return false;
754     }
755
756     // Otherwise, we cannot select it.
757     return true;
758   }
759
760   // Default, generate it as a register.
761   AM.BaseType = X86ISelAddressMode::RegBase;
762   AM.Base.Reg = N;
763   return false;
764 }
765
766 /// SelectAddr - returns true if it is able pattern match an addressing mode.
767 /// It returns the operands which make up the maximal addressing mode it can
768 /// match by reference.
769 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
770                                  SDOperand &Scale, SDOperand &Index,
771                                  SDOperand &Disp) {
772   X86ISelAddressMode AM;
773   if (MatchAddress(N, AM))
774     return false;
775
776   MVT::ValueType VT = N.getValueType();
777   if (AM.BaseType == X86ISelAddressMode::RegBase) {
778     if (!AM.Base.Reg.Val)
779       AM.Base.Reg = CurDAG->getRegister(0, VT);
780   }
781
782   if (!AM.IndexReg.Val)
783     AM.IndexReg = CurDAG->getRegister(0, VT);
784
785   getAddressOperands(AM, Base, Scale, Index, Disp);
786   return true;
787 }
788
789 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
790 /// constant +0.0.
791 static inline bool isZeroNode(SDOperand Elt) {
792   return ((isa<ConstantSDNode>(Elt) &&
793   cast<ConstantSDNode>(Elt)->getValue() == 0) ||
794   (isa<ConstantFPSDNode>(Elt) &&
795   cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
796 }
797
798
799 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
800 /// match a load whose top elements are either undef or zeros.  The load flavor
801 /// is derived from the type of N, which is either v4f32 or v2f64.
802 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
803                                           SDOperand N, SDOperand &Base,
804                                           SDOperand &Scale, SDOperand &Index,
805                                           SDOperand &Disp, SDOperand &InChain,
806                                           SDOperand &OutChain) {
807   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
808     InChain = N.getOperand(0).getValue(1);
809     if (ISD::isNON_EXTLoad(InChain.Val) &&
810         InChain.getValue(0).hasOneUse() &&
811         N.hasOneUse() &&
812         CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
813       LoadSDNode *LD = cast<LoadSDNode>(InChain);
814       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
815         return false;
816       OutChain = LD->getChain();
817       return true;
818     }
819   }
820
821   // Also handle the case where we explicitly require zeros in the top
822   // elements.  This is a vector shuffle from the zero vector.
823   if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
824       N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
825       N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR && 
826       N.getOperand(1).Val->hasOneUse() &&
827       ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
828       N.getOperand(1).getOperand(0).hasOneUse()) {
829     // Check to see if the BUILD_VECTOR is building a zero vector.
830     SDOperand BV = N.getOperand(0);
831     for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
832       if (!isZeroNode(BV.getOperand(i)) &&
833           BV.getOperand(i).getOpcode() != ISD::UNDEF)
834         return false;  // Not a zero/undef vector.
835     // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
836     // from the LHS.
837     unsigned VecWidth = BV.getNumOperands();
838     SDOperand ShufMask = N.getOperand(2);
839     assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
840     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
841       if (C->getValue() == VecWidth) {
842         for (unsigned i = 1; i != VecWidth; ++i) {
843           if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
844             // ok.
845           } else {
846             ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
847             if (C->getValue() >= VecWidth) return false;
848           }
849         }
850       }
851       
852       // Okay, this is a zero extending load.  Fold it.
853       LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
854       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
855         return false;
856       OutChain = LD->getChain();
857       InChain = SDOperand(LD, 1);
858       return true;
859     }
860   }
861   return false;
862 }
863
864
865 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
866 /// mode it matches can be cost effectively emitted as an LEA instruction.
867 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
868                                     SDOperand &Base, SDOperand &Scale,
869                                     SDOperand &Index, SDOperand &Disp) {
870   X86ISelAddressMode AM;
871   if (MatchAddress(N, AM))
872     return false;
873
874   MVT::ValueType VT = N.getValueType();
875   unsigned Complexity = 0;
876   if (AM.BaseType == X86ISelAddressMode::RegBase)
877     if (AM.Base.Reg.Val)
878       Complexity = 1;
879     else
880       AM.Base.Reg = CurDAG->getRegister(0, VT);
881   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
882     Complexity = 4;
883
884   if (AM.IndexReg.Val)
885     Complexity++;
886   else
887     AM.IndexReg = CurDAG->getRegister(0, VT);
888
889   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
890   // a simple shift.
891   if (AM.Scale > 1)
892     Complexity++;
893
894   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
895   // to a LEA. This is determined with some expermentation but is by no means
896   // optimal (especially for code size consideration). LEA is nice because of
897   // its three-address nature. Tweak the cost function again when we can run
898   // convertToThreeAddress() at register allocation time.
899   if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
900     // For X86-64, we should always use lea to materialize RIP relative
901     // addresses.
902     if (Subtarget->is64Bit())
903       Complexity = 4;
904     else
905       Complexity += 2;
906   }
907
908   if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
909     Complexity++;
910
911   if (Complexity > 2) {
912     getAddressOperands(AM, Base, Scale, Index, Disp);
913     return true;
914   }
915   return false;
916 }
917
918 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
919                                   SDOperand &Base, SDOperand &Scale,
920                                   SDOperand &Index, SDOperand &Disp) {
921   if (ISD::isNON_EXTLoad(N.Val) &&
922       N.hasOneUse() &&
923       CanBeFoldedBy(N.Val, P.Val, P.Val))
924     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
925   return false;
926 }
927
928 /// getGlobalBaseReg - Output the instructions required to put the
929 /// base address to use for accessing globals into a register.
930 ///
931 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
932   assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
933   if (!GlobalBaseReg) {
934     // Insert the set of GlobalBaseReg into the first MBB of the function
935     MachineBasicBlock &FirstMBB = BB->getParent()->front();
936     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
937     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
938     unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
939     
940     const TargetInstrInfo *TII = TM.getInstrInfo();
941     BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
942     BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
943     
944     // If we're using vanilla 'GOT' PIC style, we should use relative addressing
945     // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
946     if (TM.getRelocationModel() == Reloc::PIC_ &&
947         Subtarget->isPICStyleGOT()) {
948       GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
949       BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
950         addReg(PC).
951         addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
952     } else {
953       GlobalBaseReg = PC;
954     }
955     
956   }
957   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
958 }
959
960 static SDNode *FindCallStartFromCall(SDNode *Node) {
961   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
962     assert(Node->getOperand(0).getValueType() == MVT::Other &&
963          "Node doesn't have a token chain argument!");
964   return FindCallStartFromCall(Node->getOperand(0).Val);
965 }
966
967 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
968   SDNode *Node = N.Val;
969   MVT::ValueType NVT = Node->getValueType(0);
970   unsigned Opc, MOpc;
971   unsigned Opcode = Node->getOpcode();
972
973 #ifndef NDEBUG
974   DOUT << std::string(Indent, ' ') << "Selecting: ";
975   DEBUG(Node->dump(CurDAG));
976   DOUT << "\n";
977   Indent += 2;
978 #endif
979
980   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
981 #ifndef NDEBUG
982     DOUT << std::string(Indent-2, ' ') << "== ";
983     DEBUG(Node->dump(CurDAG));
984     DOUT << "\n";
985     Indent -= 2;
986 #endif
987     return NULL;   // Already selected.
988   }
989
990   switch (Opcode) {
991     default: break;
992     case X86ISD::GlobalBaseReg: 
993       return getGlobalBaseReg();
994
995     case ISD::ADD: {
996       // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
997       // code and is matched first so to prevent it from being turned into
998       // LEA32r X+c.
999       // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1000       MVT::ValueType PtrVT = TLI.getPointerTy();
1001       SDOperand N0 = N.getOperand(0);
1002       SDOperand N1 = N.getOperand(1);
1003       if (N.Val->getValueType(0) == PtrVT &&
1004           N0.getOpcode() == X86ISD::Wrapper &&
1005           N1.getOpcode() == ISD::Constant) {
1006         unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1007         SDOperand C(0, 0);
1008         // TODO: handle ExternalSymbolSDNode.
1009         if (GlobalAddressSDNode *G =
1010             dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1011           C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1012                                              G->getOffset() + Offset);
1013         } else if (ConstantPoolSDNode *CP =
1014                    dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1015           C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1016                                             CP->getAlignment(),
1017                                             CP->getOffset()+Offset);
1018         }
1019
1020         if (C.Val) {
1021           if (Subtarget->is64Bit()) {
1022             SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1023                                 CurDAG->getRegister(0, PtrVT), C };
1024             return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1025           } else
1026             return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1027         }
1028       }
1029
1030       // Other cases are handled by auto-generated code.
1031       break;
1032     }
1033
1034     case ISD::MULHU:
1035     case ISD::MULHS: {
1036       if (Opcode == ISD::MULHU)
1037         switch (NVT) {
1038         default: assert(0 && "Unsupported VT!");
1039         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1040         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1041         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1042         case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1043         }
1044       else
1045         switch (NVT) {
1046         default: assert(0 && "Unsupported VT!");
1047         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1048         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1049         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1050         case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1051         }
1052
1053       unsigned LoReg, HiReg;
1054       switch (NVT) {
1055       default: assert(0 && "Unsupported VT!");
1056       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1057       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1058       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1059       case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1060       }
1061
1062       SDOperand N0 = Node->getOperand(0);
1063       SDOperand N1 = Node->getOperand(1);
1064
1065       bool foldedLoad = false;
1066       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1067       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1068       // MULHU and MULHS are commmutative
1069       if (!foldedLoad) {
1070         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1071         if (foldedLoad) {
1072           N0 = Node->getOperand(1);
1073           N1 = Node->getOperand(0);
1074         }
1075       }
1076
1077       SDOperand Chain;
1078       if (foldedLoad) {
1079         Chain = N1.getOperand(0);
1080         AddToISelQueue(Chain);
1081       } else
1082         Chain = CurDAG->getEntryNode();
1083
1084       SDOperand InFlag(0, 0);
1085       AddToISelQueue(N0);
1086       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1087                                     N0, InFlag);
1088       InFlag = Chain.getValue(1);
1089
1090       if (foldedLoad) {
1091         AddToISelQueue(Tmp0);
1092         AddToISelQueue(Tmp1);
1093         AddToISelQueue(Tmp2);
1094         AddToISelQueue(Tmp3);
1095         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1096         SDNode *CNode =
1097           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1098         Chain  = SDOperand(CNode, 0);
1099         InFlag = SDOperand(CNode, 1);
1100       } else {
1101         AddToISelQueue(N1);
1102         InFlag =
1103           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1104       }
1105
1106       SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1107       ReplaceUses(N.getValue(0), Result);
1108       if (foldedLoad)
1109         ReplaceUses(N1.getValue(1), Result.getValue(1));
1110
1111 #ifndef NDEBUG
1112       DOUT << std::string(Indent-2, ' ') << "=> ";
1113       DEBUG(Result.Val->dump(CurDAG));
1114       DOUT << "\n";
1115       Indent -= 2;
1116 #endif
1117       return NULL;
1118     }
1119       
1120     case ISD::SDIV:
1121     case ISD::UDIV:
1122     case ISD::SREM:
1123     case ISD::UREM: {
1124       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1125       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1126       if (!isSigned)
1127         switch (NVT) {
1128         default: assert(0 && "Unsupported VT!");
1129         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1130         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1131         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1132         case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1133         }
1134       else
1135         switch (NVT) {
1136         default: assert(0 && "Unsupported VT!");
1137         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1138         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1139         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1140         case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1141         }
1142
1143       unsigned LoReg, HiReg;
1144       unsigned ClrOpcode, SExtOpcode;
1145       switch (NVT) {
1146       default: assert(0 && "Unsupported VT!");
1147       case MVT::i8:
1148         LoReg = X86::AL;  HiReg = X86::AH;
1149         ClrOpcode  = 0;
1150         SExtOpcode = X86::CBW;
1151         break;
1152       case MVT::i16:
1153         LoReg = X86::AX;  HiReg = X86::DX;
1154         ClrOpcode  = X86::MOV16r0;
1155         SExtOpcode = X86::CWD;
1156         break;
1157       case MVT::i32:
1158         LoReg = X86::EAX; HiReg = X86::EDX;
1159         ClrOpcode  = X86::MOV32r0;
1160         SExtOpcode = X86::CDQ;
1161         break;
1162       case MVT::i64:
1163         LoReg = X86::RAX; HiReg = X86::RDX;
1164         ClrOpcode  = X86::MOV64r0;
1165         SExtOpcode = X86::CQO;
1166         break;
1167       }
1168
1169       SDOperand N0 = Node->getOperand(0);
1170       SDOperand N1 = Node->getOperand(1);
1171       SDOperand InFlag(0, 0);
1172       if (NVT == MVT::i8 && !isSigned) {
1173         // Special case for div8, just use a move with zero extension to AX to
1174         // clear the upper 8 bits (AH).
1175         SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1176         if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1177           SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1178           AddToISelQueue(N0.getOperand(0));
1179           AddToISelQueue(Tmp0);
1180           AddToISelQueue(Tmp1);
1181           AddToISelQueue(Tmp2);
1182           AddToISelQueue(Tmp3);
1183           Move =
1184             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1185                                             Ops, 5), 0);
1186           Chain = Move.getValue(1);
1187           ReplaceUses(N0.getValue(1), Chain);
1188         } else {
1189           AddToISelQueue(N0);
1190           Move =
1191             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1192           Chain = CurDAG->getEntryNode();
1193         }
1194         Chain  = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1195         InFlag = Chain.getValue(1);
1196       } else {
1197         AddToISelQueue(N0);
1198         InFlag =
1199           CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1200                                InFlag).getValue(1);
1201         if (isSigned) {
1202           // Sign extend the low part into the high part.
1203           InFlag =
1204             SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1205         } else {
1206           // Zero out the high part, effectively zero extending the input.
1207           SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1208           InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1209                                         InFlag).getValue(1);
1210         }
1211       }
1212
1213       SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1214       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1215       if (foldedLoad) {
1216         AddToISelQueue(N1.getOperand(0));
1217         AddToISelQueue(Tmp0);
1218         AddToISelQueue(Tmp1);
1219         AddToISelQueue(Tmp2);
1220         AddToISelQueue(Tmp3);
1221         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1222         SDNode *CNode =
1223           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1224         Chain  = SDOperand(CNode, 0);
1225         InFlag = SDOperand(CNode, 1);
1226       } else {
1227         AddToISelQueue(N1);
1228         Chain = CurDAG->getEntryNode();
1229         InFlag =
1230           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1231       }
1232
1233       SDOperand Result =
1234         CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1235       ReplaceUses(N.getValue(0), Result);
1236       if (foldedLoad)
1237         ReplaceUses(N1.getValue(1), Result.getValue(1));
1238
1239 #ifndef NDEBUG
1240       DOUT << std::string(Indent-2, ' ') << "=> ";
1241       DEBUG(Result.Val->dump(CurDAG));
1242       DOUT << "\n";
1243       Indent -= 2;
1244 #endif
1245
1246       return NULL;
1247     }
1248
1249     case ISD::TRUNCATE: {
1250       if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1251         unsigned Opc2;
1252         MVT::ValueType VT;
1253         switch (Node->getOperand(0).getValueType()) {
1254         default: assert(0 && "Unknown truncate!");
1255         case MVT::i16:
1256           Opc = X86::MOV16to16_;
1257           VT = MVT::i16;
1258           Opc2 = X86::TRUNC_16_to8;
1259           break;
1260         case MVT::i32:
1261           Opc = X86::MOV32to32_;
1262           VT = MVT::i32;
1263           Opc2 = X86::TRUNC_32_to8;
1264           break;
1265         }
1266
1267         AddToISelQueue(Node->getOperand(0));
1268         SDOperand Tmp =
1269           SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1270         SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1271       
1272 #ifndef NDEBUG
1273         DOUT << std::string(Indent-2, ' ') << "=> ";
1274         DEBUG(ResNode->dump(CurDAG));
1275         DOUT << "\n";
1276         Indent -= 2;
1277 #endif
1278         return ResNode;
1279       }
1280
1281       break;
1282     }
1283   }
1284
1285   SDNode *ResNode = SelectCode(N);
1286
1287 #ifndef NDEBUG
1288   DOUT << std::string(Indent-2, ' ') << "=> ";
1289   if (ResNode == NULL || ResNode == N.Val)
1290     DEBUG(N.Val->dump(CurDAG));
1291   else
1292     DEBUG(ResNode->dump(CurDAG));
1293   DOUT << "\n";
1294   Indent -= 2;
1295 #endif
1296
1297   return ResNode;
1298 }
1299
1300 bool X86DAGToDAGISel::
1301 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1302                              std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1303   SDOperand Op0, Op1, Op2, Op3;
1304   switch (ConstraintCode) {
1305   case 'o':   // offsetable        ??
1306   case 'v':   // not offsetable    ??
1307   default: return true;
1308   case 'm':   // memory
1309     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1310       return true;
1311     break;
1312   }
1313   
1314   OutOps.push_back(Op0);
1315   OutOps.push_back(Op1);
1316   OutOps.push_back(Op2);
1317   OutOps.push_back(Op3);
1318   AddToISelQueue(Op0);
1319   AddToISelQueue(Op1);
1320   AddToISelQueue(Op2);
1321   AddToISelQueue(Op3);
1322   return false;
1323 }
1324
1325 /// createX86ISelDag - This pass converts a legalized DAG into a 
1326 /// X86-specific DAG, ready for instruction scheduling.
1327 ///
1328 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1329   return new X86DAGToDAGISel(TM, Fast);
1330 }