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