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