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