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