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