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