Optimize some common usage patterns of atomic built-ins __sync_add_and_fetch() and...
[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/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Streams.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/Statistic.h"
44 using namespace llvm;
45
46 #include "llvm/Support/CommandLine.h"
47 static cl::opt<bool> AvoidDupAddrCompute("x86-avoid-dup-address", cl::Hidden);
48
49 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
50
51 //===----------------------------------------------------------------------===//
52 //                      Pattern Matcher Implementation
53 //===----------------------------------------------------------------------===//
54
55 namespace {
56   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
57   /// SDValue's instead of register numbers for the leaves of the matched
58   /// tree.
59   struct X86ISelAddressMode {
60     enum {
61       RegBase,
62       FrameIndexBase
63     } BaseType;
64
65     struct {            // This is really a union, discriminated by BaseType!
66       SDValue Reg;
67       int FrameIndex;
68     } Base;
69
70     unsigned Scale;
71     SDValue IndexReg; 
72     int32_t Disp;
73     SDValue Segment;
74     GlobalValue *GV;
75     Constant *CP;
76     const char *ES;
77     int JT;
78     unsigned Align;    // CP alignment.
79     unsigned char SymbolFlags;  // X86II::MO_*
80
81     X86ISelAddressMode()
82       : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
83         Segment(), GV(0), CP(0), ES(0), JT(-1), Align(0), SymbolFlags(0) {
84     }
85
86     bool hasSymbolicDisplacement() const {
87       return GV != 0 || CP != 0 || ES != 0 || JT != -1;
88     }
89     
90     bool hasBaseOrIndexReg() const {
91       return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
92     }
93     
94     /// isRIPRelative - Return true if this addressing mode is already RIP
95     /// relative.
96     bool isRIPRelative() const {
97       if (BaseType != RegBase) return false;
98       if (RegisterSDNode *RegNode =
99             dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
100         return RegNode->getReg() == X86::RIP;
101       return false;
102     }
103     
104     void setBaseReg(SDValue Reg) {
105       BaseType = RegBase;
106       Base.Reg = Reg;
107     }
108
109     void dump() {
110       cerr << "X86ISelAddressMode " << this << "\n";
111       cerr << "Base.Reg ";
112               if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump(); 
113               else cerr << "nul";
114       cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
115       cerr << " Scale" << Scale << "\n";
116       cerr << "IndexReg ";
117               if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
118               else cerr << "nul"; 
119       cerr << " Disp " << Disp << "\n";
120       cerr << "GV "; if (GV) GV->dump(); 
121                      else cerr << "nul";
122       cerr << " CP "; if (CP) CP->dump(); 
123                      else cerr << "nul";
124       cerr << "\n";
125       cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
126       cerr  << " JT" << JT << " Align" << Align << "\n";
127     }
128   };
129 }
130
131 namespace {
132   //===--------------------------------------------------------------------===//
133   /// ISel - X86 specific code to select X86 machine instructions for
134   /// SelectionDAG operations.
135   ///
136   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
137     /// X86Lowering - This object fully describes how to lower LLVM code to an
138     /// X86-specific SelectionDAG.
139     X86TargetLowering &X86Lowering;
140
141     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
142     /// make the right decision when generating code for different targets.
143     const X86Subtarget *Subtarget;
144
145     /// CurBB - Current BB being isel'd.
146     ///
147     MachineBasicBlock *CurBB;
148
149     /// OptForSize - If true, selector should try to optimize for code size
150     /// instead of performance.
151     bool OptForSize;
152
153   public:
154     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
155       : SelectionDAGISel(tm, OptLevel),
156         X86Lowering(*tm.getTargetLowering()),
157         Subtarget(&tm.getSubtarget<X86Subtarget>()),
158         OptForSize(false) {}
159
160     virtual const char *getPassName() const {
161       return "X86 DAG->DAG Instruction Selection";
162     }
163
164     /// InstructionSelect - This callback is invoked by
165     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
166     virtual void InstructionSelect();
167
168     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
169
170     virtual
171       bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
172
173 // Include the pieces autogenerated from the target description.
174 #include "X86GenDAGISel.inc"
175
176   private:
177     SDNode *Select(SDValue N);
178     SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
179     SDNode *SelectAtomicLoadAdd(SDNode *Node, MVT NVT);
180
181     bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
182     bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
183     bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
184     bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
185     bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
186                                  unsigned Depth);
187     bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
188     bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
189                     SDValue &Scale, SDValue &Index, SDValue &Disp,
190                     SDValue &Segment);
191     bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
192                        SDValue &Scale, SDValue &Index, SDValue &Disp);
193     bool SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
194                        SDValue &Scale, SDValue &Index, SDValue &Disp);
195     bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
196                              SDValue N, SDValue &Base, SDValue &Scale,
197                              SDValue &Index, SDValue &Disp,
198                              SDValue &Segment,
199                              SDValue &InChain, SDValue &OutChain);
200     bool TryFoldLoad(SDValue P, SDValue N,
201                      SDValue &Base, SDValue &Scale,
202                      SDValue &Index, SDValue &Disp,
203                      SDValue &Segment);
204     void PreprocessForRMW();
205     void PreprocessForFPConvert();
206
207     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
208     /// inline asm expressions.
209     virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
210                                               char ConstraintCode,
211                                               std::vector<SDValue> &OutOps);
212     
213     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
214
215     inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base, 
216                                    SDValue &Scale, SDValue &Index,
217                                    SDValue &Disp, SDValue &Segment) {
218       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
219         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
220         AM.Base.Reg;
221       Scale = getI8Imm(AM.Scale);
222       Index = AM.IndexReg;
223       // These are 32-bit even in 64-bit mode since RIP relative offset
224       // is 32-bit.
225       if (AM.GV)
226         Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
227                                               AM.SymbolFlags);
228       else if (AM.CP)
229         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
230                                              AM.Align, AM.Disp, AM.SymbolFlags);
231       else if (AM.ES)
232         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
233       else if (AM.JT != -1)
234         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
235       else
236         Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
237
238       if (AM.Segment.getNode())
239         Segment = AM.Segment;
240       else
241         Segment = CurDAG->getRegister(0, MVT::i32);
242     }
243
244     /// getI8Imm - Return a target constant with the specified value, of type
245     /// i8.
246     inline SDValue getI8Imm(unsigned Imm) {
247       return CurDAG->getTargetConstant(Imm, MVT::i8);
248     }
249
250     /// getI16Imm - Return a target constant with the specified value, of type
251     /// i16.
252     inline SDValue getI16Imm(unsigned Imm) {
253       return CurDAG->getTargetConstant(Imm, MVT::i16);
254     }
255
256     /// getI32Imm - Return a target constant with the specified value, of type
257     /// i32.
258     inline SDValue getI32Imm(unsigned Imm) {
259       return CurDAG->getTargetConstant(Imm, MVT::i32);
260     }
261
262     /// getGlobalBaseReg - Return an SDNode that returns the value of
263     /// the global base register. Output instructions required to
264     /// initialize the global base register, if necessary.
265     ///
266     SDNode *getGlobalBaseReg();
267
268     /// getTargetMachine - Return a reference to the TargetMachine, casted
269     /// to the target-specific type.
270     const X86TargetMachine &getTargetMachine() {
271       return static_cast<const X86TargetMachine &>(TM);
272     }
273
274     /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
275     /// to the target-specific type.
276     const X86InstrInfo *getInstrInfo() {
277       return getTargetMachine().getInstrInfo();
278     }
279
280 #ifndef NDEBUG
281     unsigned Indent;
282 #endif
283   };
284 }
285
286
287 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
288                                                  SDNode *Root) const {
289   if (OptLevel == CodeGenOpt::None) return false;
290
291   if (U == Root)
292     switch (U->getOpcode()) {
293     default: break;
294     case ISD::ADD:
295     case ISD::ADDC:
296     case ISD::ADDE:
297     case ISD::AND:
298     case ISD::OR:
299     case ISD::XOR: {
300       SDValue Op1 = U->getOperand(1);
301
302       // If the other operand is a 8-bit immediate we should fold the immediate
303       // instead. This reduces code size.
304       // e.g.
305       // movl 4(%esp), %eax
306       // addl $4, %eax
307       // vs.
308       // movl $4, %eax
309       // addl 4(%esp), %eax
310       // The former is 2 bytes shorter. In case where the increment is 1, then
311       // the saving can be 4 bytes (by using incl %eax).
312       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
313         if (Imm->getAPIntValue().isSignedIntN(8))
314           return false;
315
316       // If the other operand is a TLS address, we should fold it instead.
317       // This produces
318       // movl    %gs:0, %eax
319       // leal    i@NTPOFF(%eax), %eax
320       // instead of
321       // movl    $i@NTPOFF, %eax
322       // addl    %gs:0, %eax
323       // if the block also has an access to a second TLS address this will save
324       // a load.
325       // FIXME: This is probably also true for non TLS addresses.
326       if (Op1.getOpcode() == X86ISD::Wrapper) {
327         SDValue Val = Op1.getOperand(0);
328         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
329           return false;
330       }
331     }
332     }
333
334   // Proceed to 'generic' cycle finder code
335   return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
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 *CurDAG, SDValue Load,
342                                  SDValue Store, SDValue TF) {
343   SmallVector<SDValue, 4> Ops;
344   for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
345     if (Load.getNode() == TF.getOperand(i).getNode())
346       Ops.push_back(Load.getOperand(0));
347     else
348       Ops.push_back(TF.getOperand(i));
349   CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
350   CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
351   CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
352                              Store.getOperand(2), Store.getOperand(3));
353 }
354
355 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
356 /// 
357 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
358                       SDValue &Load) {
359   if (N.getOpcode() == ISD::BIT_CONVERT)
360     N = N.getOperand(0);
361
362   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
363   if (!LD || LD->isVolatile())
364     return false;
365   if (LD->getAddressingMode() != ISD::UNINDEXED)
366     return false;
367
368   ISD::LoadExtType ExtType = LD->getExtensionType();
369   if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
370     return false;
371
372   if (N.hasOneUse() &&
373       N.getOperand(1) == Address &&
374       N.getNode()->isOperandOf(Chain.getNode())) {
375     Load = N;
376     return true;
377   }
378   return false;
379 }
380
381 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
382 /// operand and move load below the call's chain operand.
383 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
384                                   SDValue Call, SDValue CallSeqStart) {
385   SmallVector<SDValue, 8> Ops;
386   SDValue Chain = CallSeqStart.getOperand(0);
387   if (Chain.getNode() == Load.getNode())
388     Ops.push_back(Load.getOperand(0));
389   else {
390     assert(Chain.getOpcode() == ISD::TokenFactor &&
391            "Unexpected CallSeqStart chain operand");
392     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
393       if (Chain.getOperand(i).getNode() == Load.getNode())
394         Ops.push_back(Load.getOperand(0));
395       else
396         Ops.push_back(Chain.getOperand(i));
397     SDValue NewChain =
398       CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
399                       MVT::Other, &Ops[0], Ops.size());
400     Ops.clear();
401     Ops.push_back(NewChain);
402   }
403   for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
404     Ops.push_back(CallSeqStart.getOperand(i));
405   CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
406   CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
407                              Load.getOperand(1), Load.getOperand(2));
408   Ops.clear();
409   Ops.push_back(SDValue(Load.getNode(), 1));
410   for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
411     Ops.push_back(Call.getOperand(i));
412   CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
413 }
414
415 /// isCalleeLoad - Return true if call address is a load and it can be
416 /// moved below CALLSEQ_START and the chains leading up to the call.
417 /// Return the CALLSEQ_START by reference as a second output.
418 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
419   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
420     return false;
421   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
422   if (!LD ||
423       LD->isVolatile() ||
424       LD->getAddressingMode() != ISD::UNINDEXED ||
425       LD->getExtensionType() != ISD::NON_EXTLOAD)
426     return false;
427
428   // Now let's find the callseq_start.
429   while (Chain.getOpcode() != ISD::CALLSEQ_START) {
430     if (!Chain.hasOneUse())
431       return false;
432     Chain = Chain.getOperand(0);
433   }
434   
435   if (Chain.getOperand(0).getNode() == Callee.getNode())
436     return true;
437   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
438       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
439     return true;
440   return false;
441 }
442
443
444 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
445 /// This is only run if not in -O0 mode.
446 /// This allows the instruction selector to pick more read-modify-write
447 /// instructions. This is a common case:
448 ///
449 ///     [Load chain]
450 ///         ^
451 ///         |
452 ///       [Load]
453 ///       ^    ^
454 ///       |    |
455 ///      /      \-
456 ///     /         |
457 /// [TokenFactor] [Op]
458 ///     ^          ^
459 ///     |          |
460 ///      \        /
461 ///       \      /
462 ///       [Store]
463 ///
464 /// The fact the store's chain operand != load's chain will prevent the
465 /// (store (op (load))) instruction from being selected. We can transform it to:
466 ///
467 ///     [Load chain]
468 ///         ^
469 ///         |
470 ///    [TokenFactor]
471 ///         ^
472 ///         |
473 ///       [Load]
474 ///       ^    ^
475 ///       |    |
476 ///       |     \- 
477 ///       |       | 
478 ///       |     [Op]
479 ///       |       ^
480 ///       |       |
481 ///       \      /
482 ///        \    /
483 ///       [Store]
484 void X86DAGToDAGISel::PreprocessForRMW() {
485   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
486          E = CurDAG->allnodes_end(); I != E; ++I) {
487     if (I->getOpcode() == X86ISD::CALL) {
488       /// Also try moving call address load from outside callseq_start to just
489       /// before the call to allow it to be folded.
490       ///
491       ///     [Load chain]
492       ///         ^
493       ///         |
494       ///       [Load]
495       ///       ^    ^
496       ///       |    |
497       ///      /      \--
498       ///     /          |
499       ///[CALLSEQ_START] |
500       ///     ^          |
501       ///     |          |
502       /// [LOAD/C2Reg]   |
503       ///     |          |
504       ///      \        /
505       ///       \      /
506       ///       [CALL]
507       SDValue Chain = I->getOperand(0);
508       SDValue Load  = I->getOperand(1);
509       if (!isCalleeLoad(Load, Chain))
510         continue;
511       MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
512       ++NumLoadMoved;
513       continue;
514     }
515
516     if (!ISD::isNON_TRUNCStore(I))
517       continue;
518     SDValue Chain = I->getOperand(0);
519
520     if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
521       continue;
522
523     SDValue N1 = I->getOperand(1);
524     SDValue N2 = I->getOperand(2);
525     if ((N1.getValueType().isFloatingPoint() &&
526          !N1.getValueType().isVector()) ||
527         !N1.hasOneUse())
528       continue;
529
530     bool RModW = false;
531     SDValue Load;
532     unsigned Opcode = N1.getNode()->getOpcode();
533     switch (Opcode) {
534     case ISD::ADD:
535     case ISD::MUL:
536     case ISD::AND:
537     case ISD::OR:
538     case ISD::XOR:
539     case ISD::ADDC:
540     case ISD::ADDE:
541     case ISD::VECTOR_SHUFFLE: {
542       SDValue N10 = N1.getOperand(0);
543       SDValue N11 = N1.getOperand(1);
544       RModW = isRMWLoad(N10, Chain, N2, Load);
545       if (!RModW)
546         RModW = isRMWLoad(N11, Chain, N2, Load);
547       break;
548     }
549     case ISD::SUB:
550     case ISD::SHL:
551     case ISD::SRA:
552     case ISD::SRL:
553     case ISD::ROTL:
554     case ISD::ROTR:
555     case ISD::SUBC:
556     case ISD::SUBE:
557     case X86ISD::SHLD:
558     case X86ISD::SHRD: {
559       SDValue N10 = N1.getOperand(0);
560       RModW = isRMWLoad(N10, Chain, N2, Load);
561       break;
562     }
563     }
564
565     if (RModW) {
566       MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
567       ++NumLoadMoved;
568     }
569   }
570 }
571
572
573 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
574 /// nodes that target the FP stack to be store and load to the stack.  This is a
575 /// gross hack.  We would like to simply mark these as being illegal, but when
576 /// we do that, legalize produces these when it expands calls, then expands
577 /// these in the same legalize pass.  We would like dag combine to be able to
578 /// hack on these between the call expansion and the node legalization.  As such
579 /// this pass basically does "really late" legalization of these inline with the
580 /// X86 isel pass.
581 void X86DAGToDAGISel::PreprocessForFPConvert() {
582   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
583        E = CurDAG->allnodes_end(); I != E; ) {
584     SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
585     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
586       continue;
587     
588     // If the source and destination are SSE registers, then this is a legal
589     // conversion that should not be lowered.
590     MVT SrcVT = N->getOperand(0).getValueType();
591     MVT DstVT = N->getValueType(0);
592     bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
593     bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
594     if (SrcIsSSE && DstIsSSE)
595       continue;
596
597     if (!SrcIsSSE && !DstIsSSE) {
598       // If this is an FPStack extension, it is a noop.
599       if (N->getOpcode() == ISD::FP_EXTEND)
600         continue;
601       // If this is a value-preserving FPStack truncation, it is a noop.
602       if (N->getConstantOperandVal(1))
603         continue;
604     }
605    
606     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
607     // FPStack has extload and truncstore.  SSE can fold direct loads into other
608     // operations.  Based on this, decide what we want to do.
609     MVT MemVT;
610     if (N->getOpcode() == ISD::FP_ROUND)
611       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
612     else
613       MemVT = SrcIsSSE ? SrcVT : DstVT;
614     
615     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
616     DebugLoc dl = N->getDebugLoc();
617     
618     // FIXME: optimize the case where the src/dest is a load or store?
619     SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
620                                           N->getOperand(0),
621                                           MemTmp, NULL, 0, MemVT);
622     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, 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 (OptLevel != CodeGenOpt::None)
648     PreprocessForRMW();
649
650   // FIXME: This should only happen when not compiled with -O0.
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 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
667 /// the main function.
668 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
669                                              MachineFrameInfo *MFI) {
670   const TargetInstrInfo *TII = TM.getInstrInfo();
671   if (Subtarget->isTargetCygMing())
672     BuildMI(BB, DebugLoc::getUnknownLoc(),
673             TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
674 }
675
676 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
677   // If this is main, emit special code for main.
678   MachineBasicBlock *BB = MF.begin();
679   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
680     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
681 }
682
683
684 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
685                                               X86ISelAddressMode &AM) {
686   assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
687   SDValue Segment = N.getOperand(0);
688
689   if (AM.Segment.getNode() == 0) {
690     AM.Segment = Segment;
691     return false;
692   }
693
694   return true;
695 }
696
697 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
698   // This optimization is valid because the GNU TLS model defines that
699   // gs:0 (or fs:0 on X86-64) contains its own address.
700   // For more information see http://people.redhat.com/drepper/tls.pdf
701
702   SDValue Address = N.getOperand(1);
703   if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
704       !MatchSegmentBaseAddress (Address, AM))
705     return false;
706
707   return true;
708 }
709
710 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
711 /// into an addressing mode.  These wrap things that will resolve down into a
712 /// symbol reference.  If no match is possible, this returns true, otherwise it
713 /// returns false.  
714 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
715   // If the addressing mode already has a symbol as the displacement, we can
716   // never match another symbol.
717   if (AM.hasSymbolicDisplacement())
718     return true;
719
720   SDValue N0 = N.getOperand(0);
721   
722   // Handle X86-64 rip-relative addresses.  We check this before checking direct
723   // folding because RIP is preferable to non-RIP accesses.
724   if (Subtarget->is64Bit() &&
725       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
726       // they cannot be folded into immediate fields.
727       // FIXME: This can be improved for kernel and other models?
728       TM.getCodeModel() == CodeModel::Small &&
729       
730       // Base and index reg must be 0 in order to use %rip as base and lowering
731       // must allow RIP.
732       !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
733   
734     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
735       int64_t Offset = AM.Disp + G->getOffset();
736       if (!isInt32(Offset)) return true;
737       AM.GV = G->getGlobal();
738       AM.Disp = Offset;
739       AM.SymbolFlags = G->getTargetFlags();
740     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
741       int64_t Offset = AM.Disp + CP->getOffset();
742       if (!isInt32(Offset)) return true;
743       AM.CP = CP->getConstVal();
744       AM.Align = CP->getAlignment();
745       AM.Disp = Offset;
746       AM.SymbolFlags = CP->getTargetFlags();
747     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
748       AM.ES = S->getSymbol();
749       AM.SymbolFlags = S->getTargetFlags();
750     } else {
751       JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
752       AM.JT = J->getIndex();
753       AM.SymbolFlags = J->getTargetFlags();
754     }
755   
756     if (N.getOpcode() == X86ISD::WrapperRIP)
757       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
758     return false;
759   }
760
761   // Handle the case when globals fit in our immediate field: This is true for
762   // X86-32 always and X86-64 when in -static -mcmodel=small mode.  In 64-bit
763   // mode, this results in a non-RIP-relative computation.
764   if (!Subtarget->is64Bit() ||
765       (TM.getCodeModel() == CodeModel::Small &&
766        TM.getRelocationModel() == Reloc::Static)) {
767     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
768       AM.GV = G->getGlobal();
769       AM.Disp += G->getOffset();
770       AM.SymbolFlags = G->getTargetFlags();
771     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
772       AM.CP = CP->getConstVal();
773       AM.Align = CP->getAlignment();
774       AM.Disp += CP->getOffset();
775       AM.SymbolFlags = CP->getTargetFlags();
776     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
777       AM.ES = S->getSymbol();
778       AM.SymbolFlags = S->getTargetFlags();
779     } else {
780       JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
781       AM.JT = J->getIndex();
782       AM.SymbolFlags = J->getTargetFlags();
783     }
784     return false;
785   }
786
787   return true;
788 }
789
790 /// MatchAddress - Add the specified node to the specified addressing mode,
791 /// returning true if it cannot be done.  This just pattern matches for the
792 /// addressing mode.
793 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
794   if (MatchAddressRecursively(N, AM, 0))
795     return true;
796
797   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
798   // a smaller encoding and avoids a scaled-index.
799   if (AM.Scale == 2 &&
800       AM.BaseType == X86ISelAddressMode::RegBase &&
801       AM.Base.Reg.getNode() == 0) {
802     AM.Base.Reg = AM.IndexReg;
803     AM.Scale = 1;
804   }
805
806   return false;
807 }
808
809 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
810                                               unsigned Depth) {
811   bool is64Bit = Subtarget->is64Bit();
812   DebugLoc dl = N.getDebugLoc();
813   DOUT << "MatchAddress: "; DEBUG(AM.dump());
814   // Limit recursion.
815   if (Depth > 5)
816     return MatchAddressBase(N, AM);
817   
818   // If this is already a %rip relative address, we can only merge immediates
819   // into it.  Instead of handling this in every case, we handle it here.
820   // RIP relative addressing: %rip + 32-bit displacement!
821   if (AM.isRIPRelative()) {
822     // FIXME: JumpTable and ExternalSymbol address currently don't like
823     // displacements.  It isn't very important, but this should be fixed for
824     // consistency.
825     if (!AM.ES && AM.JT != -1) return true;
826     
827     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
828       int64_t Val = AM.Disp + Cst->getSExtValue();
829       if (isInt32(Val)) {
830         AM.Disp = Val;
831         return false;
832       }
833     }
834     return true;
835   }
836
837   switch (N.getOpcode()) {
838   default: break;
839   case ISD::Constant: {
840     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
841     if (!is64Bit || isInt32(AM.Disp + Val)) {
842       AM.Disp += Val;
843       return false;
844     }
845     break;
846   }
847
848   case X86ISD::SegmentBaseAddress:
849     if (!MatchSegmentBaseAddress(N, AM))
850       return false;
851     break;
852
853   case X86ISD::Wrapper:
854   case X86ISD::WrapperRIP:
855     if (!MatchWrapper(N, AM))
856       return false;
857     break;
858
859   case ISD::LOAD:
860     if (!MatchLoad(N, AM))
861       return false;
862     break;
863
864   case ISD::FrameIndex:
865     if (AM.BaseType == X86ISelAddressMode::RegBase
866         && AM.Base.Reg.getNode() == 0) {
867       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
868       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
869       return false;
870     }
871     break;
872
873   case ISD::SHL:
874     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
875       break;
876       
877     if (ConstantSDNode
878           *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
879       unsigned Val = CN->getZExtValue();
880       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
881       // that the base operand remains free for further matching. If
882       // the base doesn't end up getting used, a post-processing step
883       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
884       if (Val == 1 || Val == 2 || Val == 3) {
885         AM.Scale = 1 << Val;
886         SDValue ShVal = N.getNode()->getOperand(0);
887
888         // Okay, we know that we have a scale by now.  However, if the scaled
889         // value is an add of something and a constant, we can fold the
890         // constant into the disp field here.
891         if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
892             isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
893           AM.IndexReg = ShVal.getNode()->getOperand(0);
894           ConstantSDNode *AddVal =
895             cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
896           uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
897           if (!is64Bit || isInt32(Disp))
898             AM.Disp = Disp;
899           else
900             AM.IndexReg = ShVal;
901         } else {
902           AM.IndexReg = ShVal;
903         }
904         return false;
905       }
906     break;
907     }
908
909   case ISD::SMUL_LOHI:
910   case ISD::UMUL_LOHI:
911     // A mul_lohi where we need the low part can be folded as a plain multiply.
912     if (N.getResNo() != 0) break;
913     // FALL THROUGH
914   case ISD::MUL:
915   case X86ISD::MUL_IMM:
916     // X*[3,5,9] -> X+X*[2,4,8]
917     if (AM.BaseType == X86ISelAddressMode::RegBase &&
918         AM.Base.Reg.getNode() == 0 &&
919         AM.IndexReg.getNode() == 0) {
920       if (ConstantSDNode
921             *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
922         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
923             CN->getZExtValue() == 9) {
924           AM.Scale = unsigned(CN->getZExtValue())-1;
925
926           SDValue MulVal = N.getNode()->getOperand(0);
927           SDValue Reg;
928
929           // Okay, we know that we have a scale by now.  However, if the scaled
930           // value is an add of something and a constant, we can fold the
931           // constant into the disp field here.
932           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
933               isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
934             Reg = MulVal.getNode()->getOperand(0);
935             ConstantSDNode *AddVal =
936               cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
937             uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
938                                       CN->getZExtValue();
939             if (!is64Bit || isInt32(Disp))
940               AM.Disp = Disp;
941             else
942               Reg = N.getNode()->getOperand(0);
943           } else {
944             Reg = N.getNode()->getOperand(0);
945           }
946
947           AM.IndexReg = AM.Base.Reg = Reg;
948           return false;
949         }
950     }
951     break;
952
953   case ISD::SUB: {
954     // Given A-B, if A can be completely folded into the address and
955     // the index field with the index field unused, use -B as the index.
956     // This is a win if a has multiple parts that can be folded into
957     // the address. Also, this saves a mov if the base register has
958     // other uses, since it avoids a two-address sub instruction, however
959     // it costs an additional mov if the index register has other uses.
960
961     // Test if the LHS of the sub can be folded.
962     X86ISelAddressMode Backup = AM;
963     if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
964       AM = Backup;
965       break;
966     }
967     // Test if the index field is free for use.
968     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
969       AM = Backup;
970       break;
971     }
972     int Cost = 0;
973     SDValue RHS = N.getNode()->getOperand(1);
974     // If the RHS involves a register with multiple uses, this
975     // transformation incurs an extra mov, due to the neg instruction
976     // clobbering its operand.
977     if (!RHS.getNode()->hasOneUse() ||
978         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
979         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
980         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
981         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
982          RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
983       ++Cost;
984     // If the base is a register with multiple uses, this
985     // transformation may save a mov.
986     if ((AM.BaseType == X86ISelAddressMode::RegBase &&
987          AM.Base.Reg.getNode() &&
988          !AM.Base.Reg.getNode()->hasOneUse()) ||
989         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
990       --Cost;
991     // If the folded LHS was interesting, this transformation saves
992     // address arithmetic.
993     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
994         ((AM.Disp != 0) && (Backup.Disp == 0)) +
995         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
996       --Cost;
997     // If it doesn't look like it may be an overall win, don't do it.
998     if (Cost >= 0) {
999       AM = Backup;
1000       break;
1001     }
1002
1003     // Ok, the transformation is legal and appears profitable. Go for it.
1004     SDValue Zero = CurDAG->getConstant(0, N.getValueType());
1005     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1006     AM.IndexReg = Neg;
1007     AM.Scale = 1;
1008
1009     // Insert the new nodes into the topological ordering.
1010     if (Zero.getNode()->getNodeId() == -1 ||
1011         Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1012       CurDAG->RepositionNode(N.getNode(), Zero.getNode());
1013       Zero.getNode()->setNodeId(N.getNode()->getNodeId());
1014     }
1015     if (Neg.getNode()->getNodeId() == -1 ||
1016         Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1017       CurDAG->RepositionNode(N.getNode(), Neg.getNode());
1018       Neg.getNode()->setNodeId(N.getNode()->getNodeId());
1019     }
1020     return false;
1021   }
1022
1023   case ISD::ADD: {
1024     X86ISelAddressMode Backup = AM;
1025     if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1) &&
1026         !MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1))
1027       return false;
1028     AM = Backup;
1029     if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1) &&
1030         !MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1))
1031       return false;
1032     AM = Backup;
1033
1034     // If we couldn't fold both operands into the address at the same time,
1035     // see if we can just put each operand into a register and fold at least
1036     // the add.
1037     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1038         !AM.Base.Reg.getNode() &&
1039         !AM.IndexReg.getNode()) {
1040       AM.Base.Reg = N.getNode()->getOperand(0);
1041       AM.IndexReg = N.getNode()->getOperand(1);
1042       AM.Scale = 1;
1043       return false;
1044     }
1045     break;
1046   }
1047
1048   case ISD::OR:
1049     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1050     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1051       X86ISelAddressMode Backup = AM;
1052       uint64_t Offset = CN->getSExtValue();
1053       // Start with the LHS as an addr mode.
1054       if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1055           // Address could not have picked a GV address for the displacement.
1056           AM.GV == NULL &&
1057           // On x86-64, the resultant disp must fit in 32-bits.
1058           (!is64Bit || isInt32(AM.Disp + Offset)) &&
1059           // Check to see if the LHS & C is zero.
1060           CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
1061         AM.Disp += Offset;
1062         return false;
1063       }
1064       AM = Backup;
1065     }
1066     break;
1067       
1068   case ISD::AND: {
1069     // Perform some heroic transforms on an and of a constant-count shift
1070     // with a constant to enable use of the scaled offset field.
1071
1072     SDValue Shift = N.getOperand(0);
1073     if (Shift.getNumOperands() != 2) break;
1074
1075     // Scale must not be used already.
1076     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1077
1078     SDValue X = Shift.getOperand(0);
1079     ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1080     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1081     if (!C1 || !C2) break;
1082
1083     // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1084     // allows us to convert the shift and and into an h-register extract and
1085     // a scaled index.
1086     if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1087       unsigned ScaleLog = 8 - C1->getZExtValue();
1088       if (ScaleLog > 0 && ScaleLog < 4 &&
1089           C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1090         SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1091         SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1092         SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1093                                       X, Eight);
1094         SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1095                                       Srl, Mask);
1096         SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1097         SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1098                                       And, ShlCount);
1099
1100         // Insert the new nodes into the topological ordering.
1101         if (Eight.getNode()->getNodeId() == -1 ||
1102             Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1103           CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1104           Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1105         }
1106         if (Mask.getNode()->getNodeId() == -1 ||
1107             Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1108           CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1109           Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1110         }
1111         if (Srl.getNode()->getNodeId() == -1 ||
1112             Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1113           CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1114           Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1115         }
1116         if (And.getNode()->getNodeId() == -1 ||
1117             And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1118           CurDAG->RepositionNode(N.getNode(), And.getNode());
1119           And.getNode()->setNodeId(N.getNode()->getNodeId());
1120         }
1121         if (ShlCount.getNode()->getNodeId() == -1 ||
1122             ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1123           CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1124           ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1125         }
1126         if (Shl.getNode()->getNodeId() == -1 ||
1127             Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1128           CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1129           Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1130         }
1131         CurDAG->ReplaceAllUsesWith(N, Shl);
1132         AM.IndexReg = And;
1133         AM.Scale = (1 << ScaleLog);
1134         return false;
1135       }
1136     }
1137
1138     // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1139     // allows us to fold the shift into this addressing mode.
1140     if (Shift.getOpcode() != ISD::SHL) break;
1141
1142     // Not likely to be profitable if either the AND or SHIFT node has more
1143     // than one use (unless all uses are for address computation). Besides,
1144     // isel mechanism requires their node ids to be reused.
1145     if (!N.hasOneUse() || !Shift.hasOneUse())
1146       break;
1147     
1148     // Verify that the shift amount is something we can fold.
1149     unsigned ShiftCst = C1->getZExtValue();
1150     if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1151       break;
1152     
1153     // Get the new AND mask, this folds to a constant.
1154     SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1155                                          SDValue(C2, 0), SDValue(C1, 0));
1156     SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X, 
1157                                      NewANDMask);
1158     SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1159                                        NewAND, SDValue(C1, 0));
1160
1161     // Insert the new nodes into the topological ordering.
1162     if (C1->getNodeId() > X.getNode()->getNodeId()) {
1163       CurDAG->RepositionNode(X.getNode(), C1);
1164       C1->setNodeId(X.getNode()->getNodeId());
1165     }
1166     if (NewANDMask.getNode()->getNodeId() == -1 ||
1167         NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1168       CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1169       NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1170     }
1171     if (NewAND.getNode()->getNodeId() == -1 ||
1172         NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1173       CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1174       NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1175     }
1176     if (NewSHIFT.getNode()->getNodeId() == -1 ||
1177         NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1178       CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1179       NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1180     }
1181
1182     CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1183     
1184     AM.Scale = 1 << ShiftCst;
1185     AM.IndexReg = NewAND;
1186     return false;
1187   }
1188   }
1189
1190   return MatchAddressBase(N, AM);
1191 }
1192
1193 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1194 /// specified addressing mode without any further recursion.
1195 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1196   // Is the base register already occupied?
1197   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1198     // If so, check to see if the scale index register is set.
1199     if (AM.IndexReg.getNode() == 0) {
1200       AM.IndexReg = N;
1201       AM.Scale = 1;
1202       return false;
1203     }
1204
1205     // Otherwise, we cannot select it.
1206     return true;
1207   }
1208
1209   // Default, generate it as a register.
1210   AM.BaseType = X86ISelAddressMode::RegBase;
1211   AM.Base.Reg = N;
1212   return false;
1213 }
1214
1215 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1216 /// It returns the operands which make up the maximal addressing mode it can
1217 /// match by reference.
1218 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1219                                  SDValue &Scale, SDValue &Index,
1220                                  SDValue &Disp, SDValue &Segment) {
1221   X86ISelAddressMode AM;
1222   bool Done = false;
1223   if (AvoidDupAddrCompute && !N.hasOneUse()) {
1224     unsigned Opcode = N.getOpcode();
1225     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1226         Opcode != X86ISD::Wrapper && Opcode != X86ISD::WrapperRIP) {
1227       // If we are able to fold N into addressing mode, then we'll allow it even
1228       // if N has multiple uses. In general, addressing computation is used as
1229       // addresses by all of its uses. But watch out for CopyToReg uses, that
1230       // means the address computation is liveout. It will be computed by a LEA
1231       // so we want to avoid computing the address twice.
1232       for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1233              UE = N.getNode()->use_end(); UI != UE; ++UI) {
1234         if (UI->getOpcode() == ISD::CopyToReg) {
1235           MatchAddressBase(N, AM);
1236           Done = true;
1237           break;
1238         }
1239       }
1240     }
1241   }
1242
1243   if (!Done && MatchAddress(N, AM))
1244     return false;
1245
1246   MVT VT = N.getValueType();
1247   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1248     if (!AM.Base.Reg.getNode())
1249       AM.Base.Reg = CurDAG->getRegister(0, VT);
1250   }
1251
1252   if (!AM.IndexReg.getNode())
1253     AM.IndexReg = CurDAG->getRegister(0, VT);
1254
1255   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1256   return true;
1257 }
1258
1259 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
1260 /// match a load whose top elements are either undef or zeros.  The load flavor
1261 /// is derived from the type of N, which is either v4f32 or v2f64.
1262 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1263                                           SDValue N, SDValue &Base,
1264                                           SDValue &Scale, SDValue &Index,
1265                                           SDValue &Disp, SDValue &Segment,
1266                                           SDValue &InChain,
1267                                           SDValue &OutChain) {
1268   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1269     InChain = N.getOperand(0).getValue(1);
1270     if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1271         InChain.getValue(0).hasOneUse() &&
1272         N.hasOneUse() &&
1273         IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1274       LoadSDNode *LD = cast<LoadSDNode>(InChain);
1275       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1276         return false;
1277       OutChain = LD->getChain();
1278       return true;
1279     }
1280   }
1281
1282   // Also handle the case where we explicitly require zeros in the top
1283   // elements.  This is a vector shuffle from the zero vector.
1284   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1285       // Check to see if the top elements are all zeros (or bitcast of zeros).
1286       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 
1287       N.getOperand(0).getNode()->hasOneUse() &&
1288       ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1289       N.getOperand(0).getOperand(0).hasOneUse()) {
1290     // Okay, this is a zero extending load.  Fold it.
1291     LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1292     if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1293       return false;
1294     OutChain = LD->getChain();
1295     InChain = SDValue(LD, 1);
1296     return true;
1297   }
1298   return false;
1299 }
1300
1301
1302 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1303 /// mode it matches can be cost effectively emitted as an LEA instruction.
1304 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1305                                     SDValue &Base, SDValue &Scale,
1306                                     SDValue &Index, SDValue &Disp) {
1307   X86ISelAddressMode AM;
1308
1309   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1310   // segments.
1311   SDValue Copy = AM.Segment;
1312   SDValue T = CurDAG->getRegister(0, MVT::i32);
1313   AM.Segment = T;
1314   if (MatchAddress(N, AM))
1315     return false;
1316   assert (T == AM.Segment);
1317   AM.Segment = Copy;
1318
1319   MVT VT = N.getValueType();
1320   unsigned Complexity = 0;
1321   if (AM.BaseType == X86ISelAddressMode::RegBase)
1322     if (AM.Base.Reg.getNode())
1323       Complexity = 1;
1324     else
1325       AM.Base.Reg = CurDAG->getRegister(0, VT);
1326   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1327     Complexity = 4;
1328
1329   if (AM.IndexReg.getNode())
1330     Complexity++;
1331   else
1332     AM.IndexReg = CurDAG->getRegister(0, VT);
1333
1334   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1335   // a simple shift.
1336   if (AM.Scale > 1)
1337     Complexity++;
1338
1339   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1340   // to a LEA. This is determined with some expermentation but is by no means
1341   // optimal (especially for code size consideration). LEA is nice because of
1342   // its three-address nature. Tweak the cost function again when we can run
1343   // convertToThreeAddress() at register allocation time.
1344   if (AM.hasSymbolicDisplacement()) {
1345     // For X86-64, we should always use lea to materialize RIP relative
1346     // addresses.
1347     if (Subtarget->is64Bit())
1348       Complexity = 4;
1349     else
1350       Complexity += 2;
1351   }
1352
1353   if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1354     Complexity++;
1355
1356   // If it isn't worth using an LEA, reject it.
1357   if (Complexity <= 2)
1358     return false;
1359   
1360   SDValue Segment;
1361   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1362   return true;
1363 }
1364
1365 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1366 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
1367                                         SDValue &Scale, SDValue &Index,
1368                                         SDValue &Disp) {
1369   assert(Op.getOpcode() == X86ISD::TLSADDR);
1370   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1371   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1372   
1373   X86ISelAddressMode AM;
1374   AM.GV = GA->getGlobal();
1375   AM.Disp += GA->getOffset();
1376   AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1377   AM.SymbolFlags = GA->getTargetFlags();
1378
1379   if (N.getValueType() == MVT::i32) {
1380     AM.Scale = 1;
1381     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1382   } else {
1383     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1384   }
1385   
1386   SDValue Segment;
1387   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1388   return true;
1389 }
1390
1391
1392 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1393                                   SDValue &Base, SDValue &Scale,
1394                                   SDValue &Index, SDValue &Disp,
1395                                   SDValue &Segment) {
1396   if (ISD::isNON_EXTLoad(N.getNode()) &&
1397       N.hasOneUse() &&
1398       IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1399     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1400   return false;
1401 }
1402
1403 /// getGlobalBaseReg - Return an SDNode that returns the value of
1404 /// the global base register. Output instructions required to
1405 /// initialize the global base register, if necessary.
1406 ///
1407 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1408   MachineFunction *MF = CurBB->getParent();
1409   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1410   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1411 }
1412
1413 static SDNode *FindCallStartFromCall(SDNode *Node) {
1414   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1415     assert(Node->getOperand(0).getValueType() == MVT::Other &&
1416          "Node doesn't have a token chain argument!");
1417   return FindCallStartFromCall(Node->getOperand(0).getNode());
1418 }
1419
1420 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1421   SDValue Chain = Node->getOperand(0);
1422   SDValue In1 = Node->getOperand(1);
1423   SDValue In2L = Node->getOperand(2);
1424   SDValue In2H = Node->getOperand(3);
1425   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1426   if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1427     return NULL;
1428   SDValue LSI = Node->getOperand(4);    // MemOperand
1429   const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, LSI, Chain};
1430   return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1431                                MVT::i32, MVT::i32, MVT::Other, Ops,
1432                                array_lengthof(Ops));
1433 }
1434
1435 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, MVT NVT) {
1436   if (Node->hasAnyUseOfValue(0))
1437     return 0;
1438
1439   // Optimize common patterns for __sync_add_and_fetch and
1440   // __sync_sub_and_fetch where the result is not used. This allows us
1441   // to use "lock" version of add, sub, inc, dec instructions.
1442   // FIXME: Do not use special instructions but instead add the "lock"
1443   // prefix to the target node somehow. The extra information will then be
1444   // transferred to machine instruction and it denotes the prefix.
1445   SDValue Chain = Node->getOperand(0);
1446   SDValue Ptr = Node->getOperand(1);
1447   SDValue Val = Node->getOperand(2);
1448   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1449   if (!SelectAddr(Ptr, Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1450     return 0;
1451
1452   bool isInc = false, isDec = false, isSub = false, isCN = false;
1453   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1454   if (CN) {
1455     isCN = true;
1456     int64_t CNVal = CN->getSExtValue();
1457     if (CNVal == 1)
1458       isInc = true;
1459     else if (CNVal == -1)
1460       isDec = true;
1461     else if (CNVal >= 0)
1462       Val = CurDAG->getTargetConstant(CNVal, NVT);
1463     else {
1464       isSub = true;
1465       Val = CurDAG->getTargetConstant(-CNVal, NVT);
1466     }
1467   } else if (Val.hasOneUse() &&
1468              Val.getOpcode() == ISD::SUB &&
1469              X86::isZeroNode(Val.getOperand(0))) {
1470     isSub = true;
1471     Val = Val.getOperand(1);
1472   }
1473
1474   unsigned Opc = 0;
1475   switch (NVT.getSimpleVT()) {
1476   default: return 0;
1477   case MVT::i8:
1478     if (isInc)
1479       Opc = X86::LOCK_INC8m;
1480     else if (isDec)
1481       Opc = X86::LOCK_DEC8m;
1482     else if (isSub) {
1483       if (isCN)
1484         Opc = X86::LOCK_SUB8mi;
1485       else
1486         Opc = X86::LOCK_SUB8mr;
1487     } else {
1488       if (isCN)
1489         Opc = X86::LOCK_ADD8mi;
1490       else
1491         Opc = X86::LOCK_ADD8mr;
1492     }
1493     break;
1494   case MVT::i16:
1495     if (isInc)
1496       Opc = X86::LOCK_INC16m;
1497     else if (isDec)
1498       Opc = X86::LOCK_DEC16m;
1499     else if (isSub) {
1500       if (isCN) {
1501         if (Predicate_i16immSExt8(Val.getNode()))
1502           Opc = X86::LOCK_SUB16mi8;
1503         else
1504           Opc = X86::LOCK_SUB16mi;
1505       } else
1506         Opc = X86::LOCK_SUB16mr;
1507     } else {
1508       if (isCN) {
1509         if (Predicate_i16immSExt8(Val.getNode()))
1510           Opc = X86::LOCK_ADD16mi8;
1511         else
1512           Opc = X86::LOCK_ADD16mi;
1513       } else
1514         Opc = X86::LOCK_ADD16mr;
1515     }
1516     break;
1517   case MVT::i32:
1518     if (isInc)
1519       Opc = X86::LOCK_INC32m;
1520     else if (isDec)
1521       Opc = X86::LOCK_DEC32m;
1522     else if (isSub) {
1523       if (isCN) {
1524         if (Predicate_i32immSExt8(Val.getNode()))
1525           Opc = X86::LOCK_SUB32mi8;
1526         else
1527           Opc = X86::LOCK_SUB32mi;
1528       } else
1529         Opc = X86::LOCK_SUB32mr;
1530     } else {
1531       if (isCN) {
1532         if (Predicate_i32immSExt8(Val.getNode()))
1533           Opc = X86::LOCK_ADD32mi8;
1534         else
1535           Opc = X86::LOCK_ADD32mi;
1536       } else
1537         Opc = X86::LOCK_ADD32mr;
1538     }
1539     break;
1540   case MVT::i64:
1541     if (isInc)
1542       Opc = X86::LOCK_INC64m;
1543     else if (isDec)
1544       Opc = X86::LOCK_DEC64m;
1545     else if (isSub) {
1546       Opc = X86::LOCK_SUB64mr;
1547       if (isCN) {
1548         if (Predicate_i64immSExt8(Val.getNode()))
1549           Opc = X86::LOCK_SUB64mi8;
1550         else if (Predicate_i64immSExt32(Val.getNode()))
1551           Opc = X86::LOCK_SUB64mi32;
1552       }
1553     } else {
1554       Opc = X86::LOCK_ADD64mr;
1555       if (isCN) {
1556         if (Predicate_i64immSExt8(Val.getNode()))
1557           Opc = X86::LOCK_ADD64mi8;
1558         else if (Predicate_i64immSExt32(Val.getNode()))
1559           Opc = X86::LOCK_ADD64mi32;
1560       }
1561     }
1562     break;
1563   }
1564
1565   DebugLoc dl = Node->getDebugLoc();
1566   SDValue Undef = SDValue(CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
1567                                                 dl, NVT), 0);
1568   SDValue MemOp = CurDAG->getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
1569   if (isInc || isDec) {
1570     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, MemOp, Chain };
1571     SDValue Ret = SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Other, Ops, 7), 0);
1572     SDValue RetVals[] = { Undef, Ret };
1573     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1574   } else {
1575     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, MemOp, Chain };
1576     SDValue Ret = SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Other, Ops, 8), 0);
1577     SDValue RetVals[] = { Undef, Ret };
1578     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1579   }
1580 }
1581
1582 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1583   SDNode *Node = N.getNode();
1584   MVT NVT = Node->getValueType(0);
1585   unsigned Opc, MOpc;
1586   unsigned Opcode = Node->getOpcode();
1587   DebugLoc dl = Node->getDebugLoc();
1588   
1589 #ifndef NDEBUG
1590   DOUT << std::string(Indent, ' ') << "Selecting: ";
1591   DEBUG(Node->dump(CurDAG));
1592   DOUT << "\n";
1593   Indent += 2;
1594 #endif
1595
1596   if (Node->isMachineOpcode()) {
1597 #ifndef NDEBUG
1598     DOUT << std::string(Indent-2, ' ') << "== ";
1599     DEBUG(Node->dump(CurDAG));
1600     DOUT << "\n";
1601     Indent -= 2;
1602 #endif
1603     return NULL;   // Already selected.
1604   }
1605
1606   switch (Opcode) {
1607     default: break;
1608     case X86ISD::GlobalBaseReg: 
1609       return getGlobalBaseReg();
1610
1611     case X86ISD::ATOMOR64_DAG:
1612       return SelectAtomic64(Node, X86::ATOMOR6432);
1613     case X86ISD::ATOMXOR64_DAG:
1614       return SelectAtomic64(Node, X86::ATOMXOR6432);
1615     case X86ISD::ATOMADD64_DAG:
1616       return SelectAtomic64(Node, X86::ATOMADD6432);
1617     case X86ISD::ATOMSUB64_DAG:
1618       return SelectAtomic64(Node, X86::ATOMSUB6432);
1619     case X86ISD::ATOMNAND64_DAG:
1620       return SelectAtomic64(Node, X86::ATOMNAND6432);
1621     case X86ISD::ATOMAND64_DAG:
1622       return SelectAtomic64(Node, X86::ATOMAND6432);
1623     case X86ISD::ATOMSWAP64_DAG:
1624       return SelectAtomic64(Node, X86::ATOMSWAP6432);
1625
1626     case ISD::ATOMIC_LOAD_ADD: {
1627       SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1628       if (RetVal)
1629         return RetVal;
1630       break;
1631     }
1632
1633     case ISD::SMUL_LOHI:
1634     case ISD::UMUL_LOHI: {
1635       SDValue N0 = Node->getOperand(0);
1636       SDValue N1 = Node->getOperand(1);
1637
1638       bool isSigned = Opcode == ISD::SMUL_LOHI;
1639       if (!isSigned)
1640         switch (NVT.getSimpleVT()) {
1641         default: llvm_unreachable("Unsupported VT!");
1642         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1643         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1644         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1645         case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1646         }
1647       else
1648         switch (NVT.getSimpleVT()) {
1649         default: llvm_unreachable("Unsupported VT!");
1650         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1651         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1652         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1653         case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1654         }
1655
1656       unsigned LoReg, HiReg;
1657       switch (NVT.getSimpleVT()) {
1658       default: llvm_unreachable("Unsupported VT!");
1659       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1660       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1661       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1662       case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1663       }
1664
1665       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1666       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1667       // multiplty is commmutative
1668       if (!foldedLoad) {
1669         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1670         if (foldedLoad)
1671           std::swap(N0, N1);
1672       }
1673
1674       SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1675                                               N0, SDValue()).getValue(1);
1676
1677       if (foldedLoad) {
1678         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1679                           InFlag };
1680         SDNode *CNode =
1681           CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1682                                 array_lengthof(Ops));
1683         InFlag = SDValue(CNode, 1);
1684         // Update the chain.
1685         ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1686       } else {
1687         InFlag =
1688           SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1689       }
1690
1691       // Copy the low half of the result, if it is needed.
1692       if (!N.getValue(0).use_empty()) {
1693         SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1694                                                   LoReg, NVT, InFlag);
1695         InFlag = Result.getValue(2);
1696         ReplaceUses(N.getValue(0), Result);
1697 #ifndef NDEBUG
1698         DOUT << std::string(Indent-2, ' ') << "=> ";
1699         DEBUG(Result.getNode()->dump(CurDAG));
1700         DOUT << "\n";
1701 #endif
1702       }
1703       // Copy the high half of the result, if it is needed.
1704       if (!N.getValue(1).use_empty()) {
1705         SDValue Result;
1706         if (HiReg == X86::AH && Subtarget->is64Bit()) {
1707           // Prevent use of AH in a REX instruction by referencing AX instead.
1708           // Shift it down 8 bits.
1709           Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1710                                           X86::AX, MVT::i16, InFlag);
1711           InFlag = Result.getValue(2);
1712           Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1713                                                  Result,
1714                                      CurDAG->getTargetConstant(8, MVT::i8)), 0);
1715           // Then truncate it down to i8.
1716           SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1717           Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1718                                                    MVT::i8, Result, SRIdx), 0);
1719         } else {
1720           Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1721                                           HiReg, NVT, InFlag);
1722           InFlag = Result.getValue(2);
1723         }
1724         ReplaceUses(N.getValue(1), Result);
1725 #ifndef NDEBUG
1726         DOUT << std::string(Indent-2, ' ') << "=> ";
1727         DEBUG(Result.getNode()->dump(CurDAG));
1728         DOUT << "\n";
1729 #endif
1730       }
1731
1732 #ifndef NDEBUG
1733       Indent -= 2;
1734 #endif
1735
1736       return NULL;
1737     }
1738       
1739     case ISD::SDIVREM:
1740     case ISD::UDIVREM: {
1741       SDValue N0 = Node->getOperand(0);
1742       SDValue N1 = Node->getOperand(1);
1743
1744       bool isSigned = Opcode == ISD::SDIVREM;
1745       if (!isSigned)
1746         switch (NVT.getSimpleVT()) {
1747         default: llvm_unreachable("Unsupported VT!");
1748         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1749         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1750         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1751         case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1752         }
1753       else
1754         switch (NVT.getSimpleVT()) {
1755         default: llvm_unreachable("Unsupported VT!");
1756         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1757         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1758         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1759         case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1760         }
1761
1762       unsigned LoReg, HiReg;
1763       unsigned ClrOpcode, SExtOpcode;
1764       switch (NVT.getSimpleVT()) {
1765       default: llvm_unreachable("Unsupported VT!");
1766       case MVT::i8:
1767         LoReg = X86::AL;  HiReg = X86::AH;
1768         ClrOpcode  = 0;
1769         SExtOpcode = X86::CBW;
1770         break;
1771       case MVT::i16:
1772         LoReg = X86::AX;  HiReg = X86::DX;
1773         ClrOpcode  = X86::MOV16r0;
1774         SExtOpcode = X86::CWD;
1775         break;
1776       case MVT::i32:
1777         LoReg = X86::EAX; HiReg = X86::EDX;
1778         ClrOpcode  = X86::MOV32r0;
1779         SExtOpcode = X86::CDQ;
1780         break;
1781       case MVT::i64:
1782         LoReg = X86::RAX; HiReg = X86::RDX;
1783         ClrOpcode  = ~0U; // NOT USED.
1784         SExtOpcode = X86::CQO;
1785         break;
1786       }
1787
1788       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1789       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1790       bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1791
1792       SDValue InFlag;
1793       if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1794         // Special case for div8, just use a move with zero extension to AX to
1795         // clear the upper 8 bits (AH).
1796         SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1797         if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1798           SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1799           Move =
1800             SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16, 
1801                                           MVT::Other, Ops,
1802                                           array_lengthof(Ops)), 0);
1803           Chain = Move.getValue(1);
1804           ReplaceUses(N0.getValue(1), Chain);
1805         } else {
1806           Move =
1807             SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1808           Chain = CurDAG->getEntryNode();
1809         }
1810         Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1811         InFlag = Chain.getValue(1);
1812       } else {
1813         InFlag =
1814           CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1815                                LoReg, N0, SDValue()).getValue(1);
1816         if (isSigned && !signBitIsZero) {
1817           // Sign extend the low part into the high part.
1818           InFlag =
1819             SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1820         } else {
1821           // Zero out the high part, effectively zero extending the input.
1822           SDValue ClrNode;
1823           
1824           if (NVT.getSimpleVT() == MVT::i64) {
1825             ClrNode = SDValue(CurDAG->getTargetNode(X86::MOV32r0, dl, MVT::i32),
1826                               0);
1827             // We just did a 32-bit clear, insert it into a 64-bit register to
1828             // clear the whole 64-bit reg.
1829             SDValue Undef =
1830               SDValue(CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
1831                                             dl, MVT::i64), 0);
1832             SDValue SubRegNo = 
1833               CurDAG->getTargetConstant(X86::SUBREG_32BIT, MVT::i32);
1834             ClrNode = 
1835               SDValue(CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG, dl,
1836                                             MVT::i64, Undef, ClrNode, SubRegNo),
1837                       0);
1838           } else {
1839             ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT), 0);
1840           }
1841           
1842           InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1843                                         ClrNode, InFlag).getValue(1);
1844         }
1845       }
1846
1847       if (foldedLoad) {
1848         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1849                           InFlag };
1850         SDNode *CNode =
1851           CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1852                                 array_lengthof(Ops));
1853         InFlag = SDValue(CNode, 1);
1854         // Update the chain.
1855         ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1856       } else {
1857         InFlag =
1858           SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1859       }
1860
1861       // Copy the division (low) result, if it is needed.
1862       if (!N.getValue(0).use_empty()) {
1863         SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1864                                                   LoReg, NVT, InFlag);
1865         InFlag = Result.getValue(2);
1866         ReplaceUses(N.getValue(0), Result);
1867 #ifndef NDEBUG
1868         DOUT << std::string(Indent-2, ' ') << "=> ";
1869         DEBUG(Result.getNode()->dump(CurDAG));
1870         DOUT << "\n";
1871 #endif
1872       }
1873       // Copy the remainder (high) result, if it is needed.
1874       if (!N.getValue(1).use_empty()) {
1875         SDValue Result;
1876         if (HiReg == X86::AH && Subtarget->is64Bit()) {
1877           // Prevent use of AH in a REX instruction by referencing AX instead.
1878           // Shift it down 8 bits.
1879           Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1880                                           X86::AX, MVT::i16, InFlag);
1881           InFlag = Result.getValue(2);
1882           Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1883                                         Result,
1884                                         CurDAG->getTargetConstant(8, MVT::i8)), 
1885                            0);
1886           // Then truncate it down to i8.
1887           SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
1888           Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1889                                                    MVT::i8, Result, SRIdx), 0);
1890         } else {
1891           Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1892                                           HiReg, NVT, InFlag);
1893           InFlag = Result.getValue(2);
1894         }
1895         ReplaceUses(N.getValue(1), Result);
1896 #ifndef NDEBUG
1897         DOUT << std::string(Indent-2, ' ') << "=> ";
1898         DEBUG(Result.getNode()->dump(CurDAG));
1899         DOUT << "\n";
1900 #endif
1901       }
1902
1903 #ifndef NDEBUG
1904       Indent -= 2;
1905 #endif
1906
1907       return NULL;
1908     }
1909
1910     case ISD::DECLARE: {
1911       // Handle DECLARE nodes here because the second operand may have been
1912       // wrapped in X86ISD::Wrapper.
1913       SDValue Chain = Node->getOperand(0);
1914       SDValue N1 = Node->getOperand(1);
1915       SDValue N2 = Node->getOperand(2);
1916       FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1917       
1918       // FIXME: We need to handle this for VLAs.
1919       if (!FINode) {
1920         ReplaceUses(N.getValue(0), Chain);
1921         return NULL;
1922       }
1923       
1924       if (N2.getOpcode() == ISD::ADD &&
1925           N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1926         N2 = N2.getOperand(1);
1927       
1928       // If N2 is not Wrapper(decriptor) then the llvm.declare is mangled
1929       // somehow, just ignore it.
1930       if (N2.getOpcode() != X86ISD::Wrapper &&
1931           N2.getOpcode() != X86ISD::WrapperRIP) {
1932         ReplaceUses(N.getValue(0), Chain);
1933         return NULL;
1934       }
1935       GlobalAddressSDNode *GVNode =
1936         dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1937       if (GVNode == 0) {
1938         ReplaceUses(N.getValue(0), Chain);
1939         return NULL;
1940       }
1941       SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1942                                                  TLI.getPointerTy());
1943       SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1944                                                     TLI.getPointerTy());
1945       SDValue Ops[] = { Tmp1, Tmp2, Chain };
1946       return CurDAG->getTargetNode(TargetInstrInfo::DECLARE, dl,
1947                                    MVT::Other, Ops,
1948                                    array_lengthof(Ops));
1949     }
1950   }
1951
1952   SDNode *ResNode = SelectCode(N);
1953
1954 #ifndef NDEBUG
1955   DOUT << std::string(Indent-2, ' ') << "=> ";
1956   if (ResNode == NULL || ResNode == N.getNode())
1957     DEBUG(N.getNode()->dump(CurDAG));
1958   else
1959     DEBUG(ResNode->dump(CurDAG));
1960   DOUT << "\n";
1961   Indent -= 2;
1962 #endif
1963
1964   return ResNode;
1965 }
1966
1967 bool X86DAGToDAGISel::
1968 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1969                              std::vector<SDValue> &OutOps) {
1970   SDValue Op0, Op1, Op2, Op3, Op4;
1971   switch (ConstraintCode) {
1972   case 'o':   // offsetable        ??
1973   case 'v':   // not offsetable    ??
1974   default: return true;
1975   case 'm':   // memory
1976     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3, Op4))
1977       return true;
1978     break;
1979   }
1980   
1981   OutOps.push_back(Op0);
1982   OutOps.push_back(Op1);
1983   OutOps.push_back(Op2);
1984   OutOps.push_back(Op3);
1985   OutOps.push_back(Op4);
1986   return false;
1987 }
1988
1989 /// createX86ISelDag - This pass converts a legalized DAG into a 
1990 /// X86-specific DAG, ready for instruction scheduling.
1991 ///
1992 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1993                                      llvm::CodeGenOpt::Level OptLevel) {
1994   return new X86DAGToDAGISel(TM, OptLevel);
1995 }