Add all implicit defs to FP_REG_KILL mi.
[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   DEBUG(std::cerr << "===== Instruction selection begins:\n");
468   Indent = 0;
469 #endif
470   DAG.setRoot(SelectRoot(DAG.getRoot()));
471 #ifndef NDEBUG
472   DEBUG(std::cerr << "===== 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       const TargetInstrDescriptor &II= TM.getInstrInfo()->get(X86::FP_REG_KILL);
529       MachineInstrBuilder MIB =
530         BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
531       for (const unsigned *ImplicitDefs = II.ImplicitDefs;
532            *ImplicitDefs; ++ImplicitDefs)
533         MIB = MIB.addReg(*ImplicitDefs, true, true);
534       ++NumFPKill;
535     }
536   }
537 }
538
539 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
540 /// the main function.
541 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
542                                              MachineFrameInfo *MFI) {
543   if (Subtarget->isTargetCygwin())
544     BuildMI(BB, X86::CALLpcrel32, 1).addExternalSymbol("__main");
545
546   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
547   int CWFrameIdx = MFI->CreateStackObject(2, 2);
548   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
549
550   // Set the high part to be 64-bit precision.
551   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
552                     CWFrameIdx, 1).addImm(2);
553
554   // Reload the modified control word now.
555   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
556 }
557
558 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
559   // If this is main, emit special code for main.
560   MachineBasicBlock *BB = MF.begin();
561   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
562     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
563 }
564
565 /// MatchAddress - Add the specified node to the specified addressing mode,
566 /// returning true if it cannot be done.  This just pattern matches for the
567 /// addressing mode
568 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
569                                    bool isRoot) {
570   // RIP relative addressing: %rip + 32-bit displacement!
571   if (AM.isRIPRel) {
572     if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
573       int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
574       if (isInt32(AM.Disp + Val)) {
575         AM.Disp += Val;
576         return false;
577       }
578     }
579     return true;
580   }
581
582   int id = N.Val->getNodeId();
583   bool Available = isSelected(id);
584
585   switch (N.getOpcode()) {
586   default: break;
587   case ISD::Constant: {
588     int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
589     if (isInt32(AM.Disp + Val)) {
590       AM.Disp += Val;
591       return false;
592     }
593     break;
594   }
595
596   case X86ISD::Wrapper:
597     // If value is available in a register both base and index components have
598     // been picked, we can't fit the result available in the register in the
599     // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
600
601     // Can't fit GV or CP in addressing mode for X86-64 medium or large code
602     // model since the displacement field is 32-bit. Ok for small code model.
603
604     // For X86-64 PIC code, only allow GV / CP + displacement so we can use RIP
605     // relative addressing mode.
606     if ((!Subtarget->is64Bit() || TM.getCodeModel() == CodeModel::Small) &&
607         (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val))) {
608       bool isRIP = Subtarget->is64Bit();
609       if (isRIP && (AM.Base.Reg.Val || AM.Scale > 1 || AM.IndexReg.Val ||
610                     AM.BaseType == X86ISelAddressMode::FrameIndexBase))
611         break;
612       if (ConstantPoolSDNode *CP =
613           dyn_cast<ConstantPoolSDNode>(N.getOperand(0))) {
614         if (AM.CP == 0) {
615           AM.CP = CP->getConstVal();
616           AM.Align = CP->getAlignment();
617           AM.Disp += CP->getOffset();
618           if (isRIP)
619             AM.isRIPRel = true;
620           return false;
621         }
622       } else if (GlobalAddressSDNode *G =
623                  dyn_cast<GlobalAddressSDNode>(N.getOperand(0))) {
624         if (AM.GV == 0) {
625           AM.GV = G->getGlobal();
626           AM.Disp += G->getOffset();
627           if (isRIP)
628             AM.isRIPRel = true;
629           return false;
630         }
631       } else if (isRoot && isRIP) {
632         if (ExternalSymbolSDNode *S =
633             dyn_cast<ExternalSymbolSDNode>(N.getOperand(0))) {
634           AM.ES = S->getSymbol();
635           AM.isRIPRel = true;
636           return false;
637         } else if (JumpTableSDNode *J =
638                    dyn_cast<JumpTableSDNode>(N.getOperand(0))) {
639           AM.JT = J->getIndex();
640           AM.isRIPRel = true;
641           return false;
642         }
643       }
644     }
645     break;
646
647   case ISD::FrameIndex:
648     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
649       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
650       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
651       return false;
652     }
653     break;
654
655   case ISD::SHL:
656     if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
657       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
658         unsigned Val = CN->getValue();
659         if (Val == 1 || Val == 2 || Val == 3) {
660           AM.Scale = 1 << Val;
661           SDOperand ShVal = N.Val->getOperand(0);
662
663           // Okay, we know that we have a scale by now.  However, if the scaled
664           // value is an add of something and a constant, we can fold the
665           // constant into the disp field here.
666           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
667               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
668             AM.IndexReg = ShVal.Val->getOperand(0);
669             ConstantSDNode *AddVal =
670               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
671             uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
672             if (isInt32(Disp))
673               AM.Disp = Disp;
674             else
675               AM.IndexReg = ShVal;
676           } else {
677             AM.IndexReg = ShVal;
678           }
679           return false;
680         }
681       }
682     break;
683
684   case ISD::MUL:
685     // X*[3,5,9] -> X+X*[2,4,8]
686     if (!Available &&
687         AM.BaseType == X86ISelAddressMode::RegBase &&
688         AM.Base.Reg.Val == 0 &&
689         AM.IndexReg.Val == 0)
690       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
691         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
692           AM.Scale = unsigned(CN->getValue())-1;
693
694           SDOperand MulVal = N.Val->getOperand(0);
695           SDOperand Reg;
696
697           // Okay, we know that we have a scale by now.  However, if the scaled
698           // value is an add of something and a constant, we can fold the
699           // constant into the disp field here.
700           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
701               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
702             Reg = MulVal.Val->getOperand(0);
703             ConstantSDNode *AddVal =
704               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
705             uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
706             if (isInt32(Disp))
707               AM.Disp = Disp;
708             else
709               Reg = N.Val->getOperand(0);
710           } else {
711             Reg = N.Val->getOperand(0);
712           }
713
714           AM.IndexReg = AM.Base.Reg = Reg;
715           return false;
716         }
717     break;
718
719   case ISD::ADD: {
720     if (!Available) {
721       X86ISelAddressMode Backup = AM;
722       if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
723           !MatchAddress(N.Val->getOperand(1), AM, false))
724         return false;
725       AM = Backup;
726       if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
727           !MatchAddress(N.Val->getOperand(0), AM, false))
728         return false;
729       AM = Backup;
730     }
731     break;
732   }
733
734   case ISD::OR: {
735     if (!Available) {
736       X86ISelAddressMode Backup = AM;
737       // Look for (x << c1) | c2 where (c2 < c1)
738       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(0));
739       if (CN && !MatchAddress(N.Val->getOperand(1), AM, false)) {
740         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
741           AM.Disp = CN->getValue();
742           return false;
743         }
744       }
745       AM = Backup;
746       CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1));
747       if (CN && !MatchAddress(N.Val->getOperand(0), AM, false)) {
748         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
749           AM.Disp = CN->getValue();
750           return false;
751         }
752       }
753       AM = Backup;
754     }
755     break;
756   }
757   }
758
759   // Is the base register already occupied?
760   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
761     // If so, check to see if the scale index register is set.
762     if (AM.IndexReg.Val == 0) {
763       AM.IndexReg = N;
764       AM.Scale = 1;
765       return false;
766     }
767
768     // Otherwise, we cannot select it.
769     return true;
770   }
771
772   // Default, generate it as a register.
773   AM.BaseType = X86ISelAddressMode::RegBase;
774   AM.Base.Reg = N;
775   return false;
776 }
777
778 /// SelectAddr - returns true if it is able pattern match an addressing mode.
779 /// It returns the operands which make up the maximal addressing mode it can
780 /// match by reference.
781 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
782                                  SDOperand &Scale, SDOperand &Index,
783                                  SDOperand &Disp) {
784   X86ISelAddressMode AM;
785   if (MatchAddress(N, AM))
786     return false;
787
788   MVT::ValueType VT = N.getValueType();
789   if (AM.BaseType == X86ISelAddressMode::RegBase) {
790     if (!AM.Base.Reg.Val)
791       AM.Base.Reg = CurDAG->getRegister(0, VT);
792   }
793
794   if (!AM.IndexReg.Val)
795     AM.IndexReg = CurDAG->getRegister(0, VT);
796
797   getAddressOperands(AM, Base, Scale, Index, Disp);
798   return true;
799 }
800
801 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
802 /// constant +0.0.
803 static inline bool isZeroNode(SDOperand Elt) {
804   return ((isa<ConstantSDNode>(Elt) &&
805   cast<ConstantSDNode>(Elt)->getValue() == 0) ||
806   (isa<ConstantFPSDNode>(Elt) &&
807   cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
808 }
809
810
811 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
812 /// match a load whose top elements are either undef or zeros.  The load flavor
813 /// is derived from the type of N, which is either v4f32 or v2f64.
814 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
815                                           SDOperand N, SDOperand &Base,
816                                           SDOperand &Scale, SDOperand &Index,
817                                           SDOperand &Disp, SDOperand &InChain,
818                                           SDOperand &OutChain) {
819   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
820     InChain = N.getOperand(0).getValue(1);
821     if (ISD::isNON_EXTLoad(InChain.Val) &&
822         InChain.getValue(0).hasOneUse() &&
823         N.hasOneUse() &&
824         CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
825       LoadSDNode *LD = cast<LoadSDNode>(InChain);
826       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
827         return false;
828       OutChain = LD->getChain();
829       return true;
830     }
831   }
832
833   // Also handle the case where we explicitly require zeros in the top
834   // elements.  This is a vector shuffle from the zero vector.
835   if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
836       N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
837       N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR && 
838       N.getOperand(1).Val->hasOneUse() &&
839       ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
840       N.getOperand(1).getOperand(0).hasOneUse()) {
841     // Check to see if the BUILD_VECTOR is building a zero vector.
842     SDOperand BV = N.getOperand(0);
843     for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
844       if (!isZeroNode(BV.getOperand(i)) &&
845           BV.getOperand(i).getOpcode() != ISD::UNDEF)
846         return false;  // Not a zero/undef vector.
847     // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
848     // from the LHS.
849     unsigned VecWidth = BV.getNumOperands();
850     SDOperand ShufMask = N.getOperand(2);
851     assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
853       if (C->getValue() == VecWidth) {
854         for (unsigned i = 1; i != VecWidth; ++i) {
855           if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
856             // ok.
857           } else {
858             ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
859             if (C->getValue() >= VecWidth) return false;
860           }
861         }
862       }
863       
864       // Okay, this is a zero extending load.  Fold it.
865       LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
866       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
867         return false;
868       OutChain = LD->getChain();
869       InChain = SDOperand(LD, 1);
870       return true;
871     }
872   }
873   return false;
874 }
875
876
877 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
878 /// mode it matches can be cost effectively emitted as an LEA instruction.
879 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
880                                     SDOperand &Base, SDOperand &Scale,
881                                     SDOperand &Index, SDOperand &Disp) {
882   X86ISelAddressMode AM;
883   if (MatchAddress(N, AM))
884     return false;
885
886   MVT::ValueType VT = N.getValueType();
887   unsigned Complexity = 0;
888   if (AM.BaseType == X86ISelAddressMode::RegBase)
889     if (AM.Base.Reg.Val)
890       Complexity = 1;
891     else
892       AM.Base.Reg = CurDAG->getRegister(0, VT);
893   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
894     Complexity = 4;
895
896   if (AM.IndexReg.Val)
897     Complexity++;
898   else
899     AM.IndexReg = CurDAG->getRegister(0, VT);
900
901   if (AM.Scale > 2) 
902     Complexity += 2;
903   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg
904   else if (AM.Scale > 1)
905     Complexity++;
906
907   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
908   // to a LEA. This is determined with some expermentation but is by no means
909   // optimal (especially for code size consideration). LEA is nice because of
910   // its three-address nature. Tweak the cost function again when we can run
911   // convertToThreeAddress() at register allocation time.
912   if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
913     // For X86-64, we should always use lea to materialize RIP relative
914     // addresses.
915     if (Subtarget->is64Bit())
916       Complexity = 4;
917     else
918       Complexity += 2;
919   }
920
921   if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
922     Complexity++;
923
924   if (Complexity > 2) {
925     getAddressOperands(AM, Base, Scale, Index, Disp);
926     return true;
927   }
928   return false;
929 }
930
931 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
932                                   SDOperand &Base, SDOperand &Scale,
933                                   SDOperand &Index, SDOperand &Disp) {
934   if (ISD::isNON_EXTLoad(N.Val) &&
935       N.hasOneUse() &&
936       CanBeFoldedBy(N.Val, P.Val, P.Val))
937     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
938   return false;
939 }
940
941 /// getGlobalBaseReg - Output the instructions required to put the
942 /// base address to use for accessing globals into a register.
943 ///
944 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
945   assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
946   if (!GlobalBaseReg) {
947     // Insert the set of GlobalBaseReg into the first MBB of the function
948     MachineBasicBlock &FirstMBB = BB->getParent()->front();
949     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
950     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
951     // FIXME: when we get to LP64, we will need to create the appropriate
952     // type of register here.
953     GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
954     BuildMI(FirstMBB, MBBI, X86::MovePCtoStack, 0);
955     BuildMI(FirstMBB, MBBI, X86::POP32r, 1, GlobalBaseReg);
956   }
957   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
958 }
959
960 static SDNode *FindCallStartFromCall(SDNode *Node) {
961   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
962     assert(Node->getOperand(0).getValueType() == MVT::Other &&
963          "Node doesn't have a token chain argument!");
964   return FindCallStartFromCall(Node->getOperand(0).Val);
965 }
966
967 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
968   SDNode *Node = N.Val;
969   MVT::ValueType NVT = Node->getValueType(0);
970   unsigned Opc, MOpc;
971   unsigned Opcode = Node->getOpcode();
972
973 #ifndef NDEBUG
974   DEBUG(std::cerr << std::string(Indent, ' '));
975   DEBUG(std::cerr << "Selecting: ");
976   DEBUG(Node->dump(CurDAG));
977   DEBUG(std::cerr << "\n");
978   Indent += 2;
979 #endif
980
981   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
982 #ifndef NDEBUG
983     DEBUG(std::cerr << std::string(Indent-2, ' '));
984     DEBUG(std::cerr << "== ");
985     DEBUG(Node->dump(CurDAG));
986     DEBUG(std::cerr << "\n");
987     Indent -= 2;
988 #endif
989     return NULL;   // Already selected.
990   }
991
992   switch (Opcode) {
993     default: break;
994     case X86ISD::GlobalBaseReg: 
995       return getGlobalBaseReg();
996
997     case ISD::ADD: {
998       // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
999       // code and is matched first so to prevent it from being turned into
1000       // LEA32r X+c.
1001       // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1002       MVT::ValueType PtrVT = TLI.getPointerTy();
1003       SDOperand N0 = N.getOperand(0);
1004       SDOperand N1 = N.getOperand(1);
1005       if (N.Val->getValueType(0) == PtrVT &&
1006           N0.getOpcode() == X86ISD::Wrapper &&
1007           N1.getOpcode() == ISD::Constant) {
1008         unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1009         SDOperand C(0, 0);
1010         // TODO: handle ExternalSymbolSDNode.
1011         if (GlobalAddressSDNode *G =
1012             dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1013           C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1014                                              G->getOffset() + Offset);
1015         } else if (ConstantPoolSDNode *CP =
1016                    dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1017           C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1018                                             CP->getAlignment(),
1019                                             CP->getOffset()+Offset);
1020         }
1021
1022         if (C.Val) {
1023           if (Subtarget->is64Bit()) {
1024             SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1025                                 CurDAG->getRegister(0, PtrVT), C };
1026             return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1027           } else
1028             return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1029         }
1030       }
1031
1032       // Other cases are handled by auto-generated code.
1033       break;
1034     }
1035
1036     case ISD::MULHU:
1037     case ISD::MULHS: {
1038       if (Opcode == ISD::MULHU)
1039         switch (NVT) {
1040         default: assert(0 && "Unsupported VT!");
1041         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1042         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1043         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1044         case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1045         }
1046       else
1047         switch (NVT) {
1048         default: assert(0 && "Unsupported VT!");
1049         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1050         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1051         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1052         case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1053         }
1054
1055       unsigned LoReg, HiReg;
1056       switch (NVT) {
1057       default: assert(0 && "Unsupported VT!");
1058       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1059       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1060       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1061       case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1062       }
1063
1064       SDOperand N0 = Node->getOperand(0);
1065       SDOperand N1 = Node->getOperand(1);
1066
1067       bool foldedLoad = false;
1068       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1069       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1070       // MULHU and MULHS are commmutative
1071       if (!foldedLoad) {
1072         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1073         if (foldedLoad) {
1074           N0 = Node->getOperand(1);
1075           N1 = Node->getOperand(0);
1076         }
1077       }
1078
1079       SDOperand Chain;
1080       if (foldedLoad) {
1081         Chain = N1.getOperand(0);
1082         AddToISelQueue(Chain);
1083       } else
1084         Chain = CurDAG->getEntryNode();
1085
1086       SDOperand InFlag(0, 0);
1087       AddToISelQueue(N0);
1088       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1089                                     N0, InFlag);
1090       InFlag = Chain.getValue(1);
1091
1092       if (foldedLoad) {
1093         AddToISelQueue(Tmp0);
1094         AddToISelQueue(Tmp1);
1095         AddToISelQueue(Tmp2);
1096         AddToISelQueue(Tmp3);
1097         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1098         SDNode *CNode =
1099           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1100         Chain  = SDOperand(CNode, 0);
1101         InFlag = SDOperand(CNode, 1);
1102       } else {
1103         AddToISelQueue(N1);
1104         InFlag =
1105           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1106       }
1107
1108       SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1109       ReplaceUses(N.getValue(0), Result);
1110       if (foldedLoad)
1111         ReplaceUses(N1.getValue(1), Result.getValue(1));
1112
1113 #ifndef NDEBUG
1114       DEBUG(std::cerr << std::string(Indent-2, ' '));
1115       DEBUG(std::cerr << "=> ");
1116       DEBUG(Result.Val->dump(CurDAG));
1117       DEBUG(std::cerr << "\n");
1118       Indent -= 2;
1119 #endif
1120       return NULL;
1121     }
1122       
1123     case ISD::SDIV:
1124     case ISD::UDIV:
1125     case ISD::SREM:
1126     case ISD::UREM: {
1127       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1128       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1129       if (!isSigned)
1130         switch (NVT) {
1131         default: assert(0 && "Unsupported VT!");
1132         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1133         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1134         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1135         case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1136         }
1137       else
1138         switch (NVT) {
1139         default: assert(0 && "Unsupported VT!");
1140         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1141         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1142         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1143         case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1144         }
1145
1146       unsigned LoReg, HiReg;
1147       unsigned ClrOpcode, SExtOpcode;
1148       switch (NVT) {
1149       default: assert(0 && "Unsupported VT!");
1150       case MVT::i8:
1151         LoReg = X86::AL;  HiReg = X86::AH;
1152         ClrOpcode  = X86::MOV8r0;
1153         SExtOpcode = X86::CBW;
1154         break;
1155       case MVT::i16:
1156         LoReg = X86::AX;  HiReg = X86::DX;
1157         ClrOpcode  = X86::MOV16r0;
1158         SExtOpcode = X86::CWD;
1159         break;
1160       case MVT::i32:
1161         LoReg = X86::EAX; HiReg = X86::EDX;
1162         ClrOpcode  = X86::MOV32r0;
1163         SExtOpcode = X86::CDQ;
1164         break;
1165       case MVT::i64:
1166         LoReg = X86::RAX; HiReg = X86::RDX;
1167         ClrOpcode  = X86::MOV64r0;
1168         SExtOpcode = X86::CQO;
1169         break;
1170       }
1171
1172       SDOperand N0 = Node->getOperand(0);
1173       SDOperand N1 = Node->getOperand(1);
1174
1175       bool foldedLoad = false;
1176       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1177       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1178       SDOperand Chain;
1179       if (foldedLoad) {
1180         Chain = N1.getOperand(0);
1181         AddToISelQueue(Chain);
1182       } else
1183         Chain = CurDAG->getEntryNode();
1184
1185       SDOperand InFlag(0, 0);
1186       AddToISelQueue(N0);
1187       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1188                                     N0, InFlag);
1189       InFlag = Chain.getValue(1);
1190
1191       if (isSigned) {
1192         // Sign extend the low part into the high part.
1193         InFlag =
1194           SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1195       } else {
1196         // Zero out the high part, effectively zero extending the input.
1197         SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1198         Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
1199                                       ClrNode, InFlag);
1200         InFlag = Chain.getValue(1);
1201       }
1202
1203       if (foldedLoad) {
1204         AddToISelQueue(Tmp0);
1205         AddToISelQueue(Tmp1);
1206         AddToISelQueue(Tmp2);
1207         AddToISelQueue(Tmp3);
1208         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1209         SDNode *CNode =
1210           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1211         Chain  = SDOperand(CNode, 0);
1212         InFlag = SDOperand(CNode, 1);
1213       } else {
1214         AddToISelQueue(N1);
1215         InFlag =
1216           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1217       }
1218
1219       SDOperand Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
1220                                                 NVT, InFlag);
1221       ReplaceUses(N.getValue(0), Result);
1222       if (foldedLoad)
1223         ReplaceUses(N1.getValue(1), Result.getValue(1));
1224
1225 #ifndef NDEBUG
1226       DEBUG(std::cerr << std::string(Indent-2, ' '));
1227       DEBUG(std::cerr << "=> ");
1228       DEBUG(Result.Val->dump(CurDAG));
1229       DEBUG(std::cerr << "\n");
1230       Indent -= 2;
1231 #endif
1232
1233       return NULL;
1234     }
1235
1236     case ISD::TRUNCATE: {
1237       if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1238         unsigned Opc2;
1239         MVT::ValueType VT;
1240         switch (Node->getOperand(0).getValueType()) {
1241         default: assert(0 && "Unknown truncate!");
1242         case MVT::i16:
1243           Opc = X86::MOV16to16_;
1244           VT = MVT::i16;
1245           Opc2 = X86::TRUNC_16_to8;
1246           break;
1247         case MVT::i32:
1248           Opc = X86::MOV32to32_;
1249           VT = MVT::i32;
1250           Opc2 = X86::TRUNC_32_to8;
1251           break;
1252         }
1253
1254         AddToISelQueue(Node->getOperand(0));
1255         SDOperand Tmp =
1256           SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1257         SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1258       
1259 #ifndef NDEBUG
1260         DEBUG(std::cerr << std::string(Indent-2, ' '));
1261         DEBUG(std::cerr << "=> ");
1262         DEBUG(ResNode->dump(CurDAG));
1263         DEBUG(std::cerr << "\n");
1264         Indent -= 2;
1265 #endif
1266         return ResNode;
1267       }
1268
1269       break;
1270     }
1271   }
1272
1273   SDNode *ResNode = SelectCode(N);
1274
1275 #ifndef NDEBUG
1276   DEBUG(std::cerr << std::string(Indent-2, ' '));
1277   DEBUG(std::cerr << "=> ");
1278   if (ResNode == NULL || ResNode == N.Val)
1279     DEBUG(N.Val->dump(CurDAG));
1280   else
1281     DEBUG(ResNode->dump(CurDAG));
1282   DEBUG(std::cerr << "\n");
1283   Indent -= 2;
1284 #endif
1285
1286   return ResNode;
1287 }
1288
1289 bool X86DAGToDAGISel::
1290 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1291                              std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1292   SDOperand Op0, Op1, Op2, Op3;
1293   switch (ConstraintCode) {
1294   case 'o':   // offsetable        ??
1295   case 'v':   // not offsetable    ??
1296   default: return true;
1297   case 'm':   // memory
1298     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1299       return true;
1300     break;
1301   }
1302   
1303   OutOps.push_back(Op0);
1304   OutOps.push_back(Op1);
1305   OutOps.push_back(Op2);
1306   OutOps.push_back(Op3);
1307   AddToISelQueue(Op0);
1308   AddToISelQueue(Op1);
1309   AddToISelQueue(Op2);
1310   AddToISelQueue(Op3);
1311   return false;
1312 }
1313
1314 /// createX86ISelDag - This pass converts a legalized DAG into a 
1315 /// X86-specific DAG, ready for instruction scheduling.
1316 ///
1317 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1318   return new X86DAGToDAGISel(TM, Fast);
1319 }