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