Factor topological order code to SelectionDAG. Clean up.
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Visibility.h"
35 #include "llvm/ADT/Statistic.h"
36 #include <deque>
37 #include <iostream>
38 #include <set>
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 //                      Pattern Matcher Implementation
43 //===----------------------------------------------------------------------===//
44
45 namespace {
46   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
47   /// SDOperand's instead of register numbers for the leaves of the matched
48   /// tree.
49   struct X86ISelAddressMode {
50     enum {
51       RegBase,
52       FrameIndexBase
53     } BaseType;
54
55     struct {            // This is really a union, discriminated by BaseType!
56       SDOperand Reg;
57       int FrameIndex;
58     } Base;
59
60     unsigned Scale;
61     SDOperand IndexReg; 
62     unsigned Disp;
63     GlobalValue *GV;
64     Constant *CP;
65     unsigned Align;    // CP alignment.
66
67     X86ISelAddressMode()
68       : BaseType(RegBase), Scale(1), IndexReg(), Disp(0), GV(0),
69         CP(0), Align(0) {
70     }
71   };
72 }
73
74 namespace {
75   Statistic<>
76   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
77
78   //===--------------------------------------------------------------------===//
79   /// ISel - X86 specific code to select X86 machine instructions for
80   /// SelectionDAG operations.
81   ///
82   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
83     /// ContainsFPCode - Every instruction we select that uses or defines a FP
84     /// register should set this to true.
85     bool ContainsFPCode;
86
87     /// X86Lowering - This object fully describes how to lower LLVM code to an
88     /// X86-specific SelectionDAG.
89     X86TargetLowering X86Lowering;
90
91     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
92     /// make the right decision when generating code for different targets.
93     const X86Subtarget *Subtarget;
94
95     unsigned GlobalBaseReg;
96
97   public:
98     X86DAGToDAGISel(X86TargetMachine &TM)
99       : SelectionDAGISel(X86Lowering),
100         X86Lowering(*TM.getTargetLowering()),
101         Subtarget(&TM.getSubtarget<X86Subtarget>()),
102         DAGSize(0) {}
103
104     virtual bool runOnFunction(Function &Fn) {
105       // Make sure we re-emit a set of the global base reg if necessary
106       GlobalBaseReg = 0;
107       return SelectionDAGISel::runOnFunction(Fn);
108     }
109    
110     virtual const char *getPassName() const {
111       return "X86 DAG->DAG Instruction Selection";
112     }
113
114     /// InstructionSelectBasicBlock - This callback is invoked by
115     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
116     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
117
118     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
119
120     virtual bool CanBeFoldedBy(SDNode *N, SDNode *U);
121
122 // Include the pieces autogenerated from the target description.
123 #include "X86GenDAGISel.inc"
124
125   private:
126     void DetermineReachability(SDNode *f, SDNode *t);
127
128     void Select(SDOperand &Result, SDOperand N);
129
130     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
131     bool SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
132                     SDOperand &Index, SDOperand &Disp);
133     bool SelectLEAAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
134                        SDOperand &Index, SDOperand &Disp);
135     bool TryFoldLoad(SDOperand P, SDOperand N,
136                      SDOperand &Base, SDOperand &Scale,
137                      SDOperand &Index, SDOperand &Disp);
138     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
139     /// inline asm expressions.
140     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
141                                               char ConstraintCode,
142                                               std::vector<SDOperand> &OutOps,
143                                               SelectionDAG &DAG);
144     
145     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
146
147     inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base, 
148                                    SDOperand &Scale, SDOperand &Index,
149                                    SDOperand &Disp) {
150       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
151         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, MVT::i32) : AM.Base.Reg;
152       Scale = getI8Imm(AM.Scale);
153       Index = AM.IndexReg;
154       Disp  = AM.GV ? CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp)
155         : (AM.CP ?
156            CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp)
157            : getI32Imm(AM.Disp));
158     }
159
160     /// getI8Imm - Return a target constant with the specified value, of type
161     /// i8.
162     inline SDOperand getI8Imm(unsigned Imm) {
163       return CurDAG->getTargetConstant(Imm, MVT::i8);
164     }
165
166     /// getI16Imm - Return a target constant with the specified value, of type
167     /// i16.
168     inline SDOperand getI16Imm(unsigned Imm) {
169       return CurDAG->getTargetConstant(Imm, MVT::i16);
170     }
171
172     /// getI32Imm - Return a target constant with the specified value, of type
173     /// i32.
174     inline SDOperand getI32Imm(unsigned Imm) {
175       return CurDAG->getTargetConstant(Imm, MVT::i32);
176     }
177
178     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
179     /// base register.  Return the virtual register that holds this value.
180     SDOperand getGlobalBaseReg();
181
182     /// DAGSize - Number of nodes in the DAG.
183     ///
184     unsigned DAGSize;
185
186     /// TopOrder - Topological ordering of all nodes in the DAG.
187     ///
188     std::vector<SDNode*> TopOrder;
189
190     /// ReachabilityMatrix - A N x N matrix representing all pairs reachability
191     /// information. One bit per potential edge.
192     std::vector<bool> ReachabilityMatrix;
193
194     /// RMRange - The range of reachability information available for the
195     /// particular source node.
196     std::vector<unsigned> ReachMatrixRange;
197
198     inline void setReachable(SDNode *f, SDNode *t) {
199       unsigned Idx = f->getNodeId() * DAGSize + t->getNodeId();
200       ReachabilityMatrix[Idx] = true;
201     }
202
203     inline bool isReachable(SDNode *f, SDNode *t) {
204       unsigned Idx = f->getNodeId() * DAGSize + t->getNodeId();
205       return ReachabilityMatrix[Idx];
206     }
207
208     /// UnfoldableSet - An boolean array representing nodes which have been
209     /// folded into addressing modes and therefore should not be folded in
210     /// another operation.
211     std::vector<bool> UnfoldableSet;
212
213     inline void setUnfoldable(SDNode *N) {
214       UnfoldableSet[N->getNodeId()] = true;
215     }
216
217     inline bool isUnfoldable(SDNode *N) {
218       return UnfoldableSet[N->getNodeId()];
219     }
220
221 #ifndef NDEBUG
222     unsigned Indent;
223 #endif
224   };
225 }
226
227 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U) {
228   // Is it already folded by SelectAddr / SelectLEAAddr?
229   if (isUnfoldable(N))
230     return false;
231
232   // If U use can somehow reach N through another path then U can't fold N or
233   // it will create a cycle. e.g. In the following diagram, U can reach N
234   // through X. If N is folded into into U, then X is both a predecessor and
235   // a successor of U.
236   //
237   //         [ N ]
238   //         ^  ^
239   //         |  |
240   //        /   \---
241   //      /        [X]
242   //      |         ^
243   //     [U]--------|
244   DetermineReachability(U, N);
245   assert(isReachable(U, N) && "Attempting to fold a non-operand node?");
246   for (SDNode::op_iterator I = U->op_begin(), E = U->op_end(); I != E; ++I) {
247     SDNode *P = I->Val;
248     if (P != N && isReachable(P, N))
249       return false;
250   }
251   return true;
252 }
253
254 /// DetermineReachability - Determine reachability between all pairs of nodes
255 /// between f and t in topological order.
256 void X86DAGToDAGISel::DetermineReachability(SDNode *f, SDNode *t) {
257   unsigned Orderf = f->getNodeId();
258   unsigned Ordert = t->getNodeId();
259   unsigned Range = ReachMatrixRange[Orderf];
260   if (Range >= Ordert)
261     return;
262   if (Range < Orderf)
263     Range = Orderf;
264
265   for (unsigned i = Range; i < Ordert; ++i) {
266     SDNode *N = TopOrder[i];
267     setReachable(N, N);
268     // If N is a leaf node, there is nothing more to do.
269     if (N->getNumOperands() == 0)
270       continue;
271
272     for (unsigned i2 = Orderf; ; ++i2) {
273       SDNode *M = TopOrder[i2];
274       if (isReachable(M, N)) {
275         // Update reachability from M to N's operands.
276         for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E;++I)
277           setReachable(M, I->Val);
278       }
279       if (M == N) break;
280     }
281   }
282
283   ReachMatrixRange[Orderf] = Ordert;
284 }
285
286 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
287 /// when it has created a SelectionDAG for us to codegen.
288 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
289   DEBUG(BB->dump());
290   MachineFunction::iterator FirstMBB = BB;
291
292   TopOrder = DAG.AssignTopologicalOrder();
293   DAGSize = TopOrder.size();
294   ReachabilityMatrix.assign(DAGSize*DAGSize, false);
295   ReachMatrixRange.assign(DAGSize, 0);
296   UnfoldableSet.assign(DAGSize, false);
297
298   // Codegen the basic block.
299 #ifndef NDEBUG
300   DEBUG(std::cerr << "===== Instruction selection begins:\n");
301   Indent = 0;
302 #endif
303   DAG.setRoot(SelectRoot(DAG.getRoot()));
304 #ifndef NDEBUG
305   DEBUG(std::cerr << "===== Instruction selection ends:\n");
306 #endif
307
308   CodeGenMap.clear();
309   HandleMap.clear();
310   ReplaceMap.clear();
311   DAG.RemoveDeadNodes();
312
313   // Emit machine code to BB. 
314   ScheduleAndEmitDAG(DAG);
315   
316   // If we are emitting FP stack code, scan the basic block to determine if this
317   // block defines any FP values.  If so, put an FP_REG_KILL instruction before
318   // the terminator of the block.
319   if (!Subtarget->hasSSE2()) {
320     // Note that FP stack instructions *are* used in SSE code when returning
321     // values, but these are not live out of the basic block, so we don't need
322     // an FP_REG_KILL in this case either.
323     bool ContainsFPCode = false;
324     
325     // Scan all of the machine instructions in these MBBs, checking for FP
326     // stores.
327     MachineFunction::iterator MBBI = FirstMBB;
328     do {
329       for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
330            !ContainsFPCode && I != E; ++I) {
331         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
332           if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
333               MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
334               RegMap->getRegClass(I->getOperand(0).getReg()) == 
335                 X86::RFPRegisterClass) {
336             ContainsFPCode = true;
337             break;
338           }
339         }
340       }
341     } while (!ContainsFPCode && &*(MBBI++) != BB);
342     
343     // Check PHI nodes in successor blocks.  These PHI's will be lowered to have
344     // a copy of the input value in this block.
345     if (!ContainsFPCode) {
346       // Final check, check LLVM BB's that are successors to the LLVM BB
347       // corresponding to BB for FP PHI nodes.
348       const BasicBlock *LLVMBB = BB->getBasicBlock();
349       const PHINode *PN;
350       for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
351            !ContainsFPCode && SI != E; ++SI) {
352         for (BasicBlock::const_iterator II = SI->begin();
353              (PN = dyn_cast<PHINode>(II)); ++II) {
354           if (PN->getType()->isFloatingPoint()) {
355             ContainsFPCode = true;
356             break;
357           }
358         }
359       }
360     }
361
362     // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
363     if (ContainsFPCode) {
364       BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
365       ++NumFPKill;
366     }
367   }
368 }
369
370 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
371 /// the main function.
372 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
373                                              MachineFrameInfo *MFI) {
374   if (Subtarget->TargetType == X86Subtarget::isCygwin)
375     BuildMI(BB, X86::CALLpcrel32, 1).addExternalSymbol("__main");
376
377   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
378   int CWFrameIdx = MFI->CreateStackObject(2, 2);
379   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
380
381   // Set the high part to be 64-bit precision.
382   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
383                     CWFrameIdx, 1).addImm(2);
384
385   // Reload the modified control word now.
386   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
387 }
388
389 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
390   // If this is main, emit special code for main.
391   MachineBasicBlock *BB = MF.begin();
392   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
393     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
394 }
395
396 /// MatchAddress - Add the specified node to the specified addressing mode,
397 /// returning true if it cannot be done.  This just pattern matches for the
398 /// addressing mode
399 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
400                                    bool isRoot) {
401   bool Available = false;
402   // If N has already been selected, reuse the result unless in some very
403   // specific cases.
404   std::map<SDOperand, SDOperand>::iterator CGMI= CodeGenMap.find(N.getValue(0));
405   if (CGMI != CodeGenMap.end()) {
406     Available = true;
407   }
408
409   switch (N.getOpcode()) {
410   default: break;
411   case ISD::Constant:
412     AM.Disp += cast<ConstantSDNode>(N)->getValue();
413     return false;
414
415   case X86ISD::Wrapper:
416     // If both base and index components have been picked, we can't fit
417     // the result available in the register in the addressing mode. Duplicate
418     // GlobalAddress or ConstantPool as displacement.
419     if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
420       if (ConstantPoolSDNode *CP =
421           dyn_cast<ConstantPoolSDNode>(N.getOperand(0))) {
422         if (AM.CP == 0) {
423           AM.CP = CP->get();
424           AM.Align = CP->getAlignment();
425           AM.Disp += CP->getOffset();
426           return false;
427         }
428       } else if (GlobalAddressSDNode *G =
429                  dyn_cast<GlobalAddressSDNode>(N.getOperand(0))) {
430         if (AM.GV == 0) {
431           AM.GV = G->getGlobal();
432           AM.Disp += G->getOffset();
433           return false;
434         }
435       }
436     }
437     break;
438
439   case ISD::FrameIndex:
440     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
441       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
442       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
443       return false;
444     }
445     break;
446
447   case ISD::SHL:
448     if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
449       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
450         unsigned Val = CN->getValue();
451         if (Val == 1 || Val == 2 || Val == 3) {
452           AM.Scale = 1 << Val;
453           SDOperand ShVal = N.Val->getOperand(0);
454
455           // Okay, we know that we have a scale by now.  However, if the scaled
456           // value is an add of something and a constant, we can fold the
457           // constant into the disp field here.
458           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
459               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
460             AM.IndexReg = ShVal.Val->getOperand(0);
461             ConstantSDNode *AddVal =
462               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
463             AM.Disp += AddVal->getValue() << Val;
464           } else {
465             AM.IndexReg = ShVal;
466           }
467           return false;
468         }
469       }
470     break;
471
472   case ISD::MUL:
473     // X*[3,5,9] -> X+X*[2,4,8]
474     if (!Available &&
475         AM.BaseType == X86ISelAddressMode::RegBase &&
476         AM.Base.Reg.Val == 0 &&
477         AM.IndexReg.Val == 0)
478       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
479         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
480           AM.Scale = unsigned(CN->getValue())-1;
481
482           SDOperand MulVal = N.Val->getOperand(0);
483           SDOperand Reg;
484
485           // Okay, we know that we have a scale by now.  However, if the scaled
486           // value is an add of something and a constant, we can fold the
487           // constant into the disp field here.
488           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
489               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
490             Reg = MulVal.Val->getOperand(0);
491             ConstantSDNode *AddVal =
492               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
493             AM.Disp += AddVal->getValue() * CN->getValue();
494           } else {
495             Reg = N.Val->getOperand(0);
496           }
497
498           AM.IndexReg = AM.Base.Reg = Reg;
499           return false;
500         }
501     break;
502
503   case ISD::ADD: {
504     if (!Available) {
505       X86ISelAddressMode Backup = AM;
506       if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
507           !MatchAddress(N.Val->getOperand(1), AM, false))
508         return false;
509       AM = Backup;
510       if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
511           !MatchAddress(N.Val->getOperand(0), AM, false))
512         return false;
513       AM = Backup;
514     }
515     break;
516   }
517
518   case ISD::OR: {
519     if (!Available) {
520       X86ISelAddressMode Backup = AM;
521       // Look for (x << c1) | c2 where (c2 < c1)
522       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(0));
523       if (CN && !MatchAddress(N.Val->getOperand(1), AM, false)) {
524         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
525           AM.Disp = CN->getValue();
526           return false;
527         }
528       }
529       AM = Backup;
530       CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1));
531       if (CN && !MatchAddress(N.Val->getOperand(0), AM, false)) {
532         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
533           AM.Disp = CN->getValue();
534           return false;
535         }
536       }
537       AM = Backup;
538     }
539     break;
540   }
541   }
542
543   // Is the base register already occupied?
544   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
545     // If so, check to see if the scale index register is set.
546     if (AM.IndexReg.Val == 0) {
547       AM.IndexReg = N;
548       AM.Scale = 1;
549       return false;
550     }
551
552     // Otherwise, we cannot select it.
553     return true;
554   }
555
556   // Default, generate it as a register.
557   AM.BaseType = X86ISelAddressMode::RegBase;
558   AM.Base.Reg = N;
559   return false;
560 }
561
562 /// SelectAddr - returns true if it is able pattern match an addressing mode.
563 /// It returns the operands which make up the maximal addressing mode it can
564 /// match by reference.
565 bool X86DAGToDAGISel::SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
566                                  SDOperand &Index, SDOperand &Disp) {
567   X86ISelAddressMode AM;
568   if (MatchAddress(N, AM))
569     return false;
570
571   if (AM.BaseType == X86ISelAddressMode::RegBase) {
572     if (!AM.Base.Reg.Val)
573       AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
574   }
575
576   if (!AM.IndexReg.Val)
577     AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
578
579   getAddressOperands(AM, Base, Scale, Index, Disp);
580
581   int Id = Base.Val ? Base.Val->getNodeId() : -1;
582   if (Id != -1)
583     setUnfoldable(Base.Val);
584   Id = Index.Val ? Index.Val->getNodeId() : -1;
585   if (Id != -1)
586     setUnfoldable(Index.Val);
587
588   return true;
589 }
590
591 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
592 /// mode it matches can be cost effectively emitted as an LEA instruction.
593 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand N, SDOperand &Base,
594                                     SDOperand &Scale,
595                                     SDOperand &Index, SDOperand &Disp) {
596   X86ISelAddressMode AM;
597   if (MatchAddress(N, AM))
598     return false;
599
600   unsigned Complexity = 0;
601   if (AM.BaseType == X86ISelAddressMode::RegBase)
602     if (AM.Base.Reg.Val)
603       Complexity = 1;
604     else
605       AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
606   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
607     Complexity = 4;
608
609   if (AM.IndexReg.Val)
610     Complexity++;
611   else
612     AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
613
614   if (AM.Scale > 2) 
615     Complexity += 2;
616   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg
617   else if (AM.Scale > 1)
618     Complexity++;
619
620   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
621   // to a LEA. This is determined with some expermentation but is by no means
622   // optimal (especially for code size consideration). LEA is nice because of
623   // its three-address nature. Tweak the cost function again when we can run
624   // convertToThreeAddress() at register allocation time.
625   if (AM.GV || AM.CP)
626     Complexity += 2;
627
628   if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
629     Complexity++;
630
631   if (Complexity > 2) {
632     getAddressOperands(AM, Base, Scale, Index, Disp);
633     return true;
634   }
635
636   int Id = Base.Val ? Base.Val->getNodeId() : -1;
637   if (Id != -1)
638     setUnfoldable(Base.Val);
639   Id = Index.Val ? Index.Val->getNodeId() : -1;
640   if (Id != -1)
641     setUnfoldable(Index.Val);
642
643   return false;
644 }
645
646 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
647                                   SDOperand &Base, SDOperand &Scale,
648                                   SDOperand &Index, SDOperand &Disp) {
649   if (N.getOpcode() == ISD::LOAD &&
650       N.hasOneUse() &&
651       !CodeGenMap.count(N.getValue(0)) &&
652       !CanBeFoldedBy(N.Val, P.Val))
653     return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp);
654   return false;
655 }
656
657 static bool isRegister0(SDOperand Op) {
658   if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op))
659     return (R->getReg() == 0);
660   return false;
661 }
662
663 /// getGlobalBaseReg - Output the instructions required to put the
664 /// base address to use for accessing globals into a register.
665 ///
666 SDOperand X86DAGToDAGISel::getGlobalBaseReg() {
667   if (!GlobalBaseReg) {
668     // Insert the set of GlobalBaseReg into the first MBB of the function
669     MachineBasicBlock &FirstMBB = BB->getParent()->front();
670     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
671     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
672     // FIXME: when we get to LP64, we will need to create the appropriate
673     // type of register here.
674     GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
675     BuildMI(FirstMBB, MBBI, X86::MovePCtoStack, 0);
676     BuildMI(FirstMBB, MBBI, X86::POP32r, 1, GlobalBaseReg);
677   }
678   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
679 }
680
681 static SDNode *FindCallStartFromCall(SDNode *Node) {
682   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
683     assert(Node->getOperand(0).getValueType() == MVT::Other &&
684          "Node doesn't have a token chain argument!");
685   return FindCallStartFromCall(Node->getOperand(0).Val);
686 }
687
688 void X86DAGToDAGISel::Select(SDOperand &Result, SDOperand N) {
689   SDNode *Node = N.Val;
690   MVT::ValueType NVT = Node->getValueType(0);
691   unsigned Opc, MOpc;
692   unsigned Opcode = Node->getOpcode();
693
694 #ifndef NDEBUG
695   DEBUG(std::cerr << std::string(Indent, ' '));
696   DEBUG(std::cerr << "Selecting: ");
697   DEBUG(Node->dump(CurDAG));
698   DEBUG(std::cerr << "\n");
699   Indent += 2;
700 #endif
701
702   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
703     Result = N;
704 #ifndef NDEBUG
705     DEBUG(std::cerr << std::string(Indent-2, ' '));
706     DEBUG(std::cerr << "== ");
707     DEBUG(Node->dump(CurDAG));
708     DEBUG(std::cerr << "\n");
709     Indent -= 2;
710 #endif
711     return;   // Already selected.
712   }
713
714   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);
715   if (CGMI != CodeGenMap.end()) {
716     Result = CGMI->second;
717 #ifndef NDEBUG
718     DEBUG(std::cerr << std::string(Indent-2, ' '));
719     DEBUG(std::cerr << "== ");
720     DEBUG(Result.Val->dump(CurDAG));
721     DEBUG(std::cerr << "\n");
722     Indent -= 2;
723 #endif
724     return;
725   }
726   
727   switch (Opcode) {
728     default: break;
729     case X86ISD::GlobalBaseReg: 
730       Result = getGlobalBaseReg();
731       return;
732
733     case ISD::ADD: {
734       // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
735       // code and is matched first so to prevent it from being turned into
736       // LEA32r X+c.
737       SDOperand N0 = N.getOperand(0);
738       SDOperand N1 = N.getOperand(1);
739       if (N.Val->getValueType(0) == MVT::i32 &&
740           N0.getOpcode() == X86ISD::Wrapper &&
741           N1.getOpcode() == ISD::Constant) {
742         unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
743         SDOperand C(0, 0);
744         // TODO: handle ExternalSymbolSDNode.
745         if (GlobalAddressSDNode *G =
746             dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
747           C = CurDAG->getTargetGlobalAddress(G->getGlobal(), MVT::i32,
748                                              G->getOffset() + Offset);
749         } else if (ConstantPoolSDNode *CP =
750                    dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
751           C = CurDAG->getTargetConstantPool(CP->get(), MVT::i32,
752                                             CP->getAlignment(),
753                                             CP->getOffset()+Offset);
754         }
755
756         if (C.Val) {
757           if (N.Val->hasOneUse()) {
758             Result = CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, MVT::i32, C);
759           } else {
760             SDNode *ResNode = CurDAG->getTargetNode(X86::MOV32ri, MVT::i32, C);
761             Result = CodeGenMap[N] = SDOperand(ResNode, 0);
762           }
763           return;
764         }
765       }
766
767       // Other cases are handled by auto-generated code.
768       break;
769     }
770
771     case ISD::MULHU:
772     case ISD::MULHS: {
773       if (Opcode == ISD::MULHU)
774         switch (NVT) {
775         default: assert(0 && "Unsupported VT!");
776         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
777         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
778         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
779         }
780       else
781         switch (NVT) {
782         default: assert(0 && "Unsupported VT!");
783         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
784         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
785         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
786         }
787
788       unsigned LoReg, HiReg;
789       switch (NVT) {
790       default: assert(0 && "Unsupported VT!");
791       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
792       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
793       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
794       }
795
796       SDOperand N0 = Node->getOperand(0);
797       SDOperand N1 = Node->getOperand(1);
798
799       bool foldedLoad = false;
800       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
801       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
802       // MULHU and MULHS are commmutative
803       if (!foldedLoad) {
804         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
805         if (foldedLoad) {
806           N0 = Node->getOperand(1);
807           N1 = Node->getOperand(0);
808         }
809       }
810
811       SDOperand Chain;
812       if (foldedLoad)
813         Select(Chain, N1.getOperand(0));
814       else
815         Chain = CurDAG->getEntryNode();
816
817       SDOperand InFlag(0, 0);
818       Select(N0, N0);
819       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
820                                     N0, InFlag);
821       InFlag = Chain.getValue(1);
822
823       if (foldedLoad) {
824         Select(Tmp0, Tmp0);
825         Select(Tmp1, Tmp1);
826         Select(Tmp2, Tmp2);
827         Select(Tmp3, Tmp3);
828         SDNode *CNode =
829           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
830                                 Tmp2, Tmp3, Chain, InFlag);
831         Chain  = SDOperand(CNode, 0);
832         InFlag = SDOperand(CNode, 1);
833       } else {
834         Select(N1, N1);
835         InFlag =
836           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
837       }
838
839       Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
840       CodeGenMap[N.getValue(0)] = Result;
841       if (foldedLoad) {
842         CodeGenMap[N1.getValue(1)] = Result.getValue(1);
843         AddHandleReplacement(N1.Val, 1, Result.Val, 1);
844       }
845
846 #ifndef NDEBUG
847       DEBUG(std::cerr << std::string(Indent-2, ' '));
848       DEBUG(std::cerr << "== ");
849       DEBUG(Result.Val->dump(CurDAG));
850       DEBUG(std::cerr << "\n");
851       Indent -= 2;
852 #endif
853       return;
854     }
855       
856     case ISD::SDIV:
857     case ISD::UDIV:
858     case ISD::SREM:
859     case ISD::UREM: {
860       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
861       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
862       if (!isSigned)
863         switch (NVT) {
864         default: assert(0 && "Unsupported VT!");
865         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
866         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
867         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
868         }
869       else
870         switch (NVT) {
871         default: assert(0 && "Unsupported VT!");
872         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
873         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
874         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
875         }
876
877       unsigned LoReg, HiReg;
878       unsigned ClrOpcode, SExtOpcode;
879       switch (NVT) {
880       default: assert(0 && "Unsupported VT!");
881       case MVT::i8:
882         LoReg = X86::AL;  HiReg = X86::AH;
883         ClrOpcode  = X86::MOV8r0;
884         SExtOpcode = X86::CBW;
885         break;
886       case MVT::i16:
887         LoReg = X86::AX;  HiReg = X86::DX;
888         ClrOpcode  = X86::MOV16r0;
889         SExtOpcode = X86::CWD;
890         break;
891       case MVT::i32:
892         LoReg = X86::EAX; HiReg = X86::EDX;
893         ClrOpcode  = X86::MOV32r0;
894         SExtOpcode = X86::CDQ;
895         break;
896       }
897
898       SDOperand N0 = Node->getOperand(0);
899       SDOperand N1 = Node->getOperand(1);
900
901       bool foldedLoad = false;
902       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
903       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
904       SDOperand Chain;
905       if (foldedLoad)
906         Select(Chain, N1.getOperand(0));
907       else
908         Chain = CurDAG->getEntryNode();
909
910       SDOperand InFlag(0, 0);
911       Select(N0, N0);
912       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
913                                     N0, InFlag);
914       InFlag = Chain.getValue(1);
915
916       if (isSigned) {
917         // Sign extend the low part into the high part.
918         InFlag =
919           SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
920       } else {
921         // Zero out the high part, effectively zero extending the input.
922         SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
923         Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
924                                       ClrNode, InFlag);
925         InFlag = Chain.getValue(1);
926       }
927
928       if (foldedLoad) {
929         Select(Tmp0, Tmp0);
930         Select(Tmp1, Tmp1);
931         Select(Tmp2, Tmp2);
932         Select(Tmp3, Tmp3);
933         SDNode *CNode =
934           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
935                                 Tmp2, Tmp3, Chain, InFlag);
936         Chain  = SDOperand(CNode, 0);
937         InFlag = SDOperand(CNode, 1);
938       } else {
939         Select(N1, N1);
940         InFlag =
941           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
942       }
943
944       Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
945                                       NVT, InFlag);
946       CodeGenMap[N.getValue(0)] = Result;
947       if (foldedLoad) {
948         CodeGenMap[N1.getValue(1)] = Result.getValue(1);
949         AddHandleReplacement(N1.Val, 1, Result.Val, 1);
950       }
951
952 #ifndef NDEBUG
953       DEBUG(std::cerr << std::string(Indent-2, ' '));
954       DEBUG(std::cerr << "== ");
955       DEBUG(Result.Val->dump(CurDAG));
956       DEBUG(std::cerr << "\n");
957       Indent -= 2;
958 #endif
959       return;
960     }
961
962     case ISD::TRUNCATE: {
963       if (NVT == MVT::i8) {
964         unsigned Opc2;
965         MVT::ValueType VT;
966         switch (Node->getOperand(0).getValueType()) {
967         default: assert(0 && "Unknown truncate!");
968         case MVT::i16:
969           Opc = X86::MOV16to16_;
970           VT = MVT::i16;
971           Opc2 = X86::TRUNC_GR16_GR8;
972           break;
973         case MVT::i32:
974           Opc = X86::MOV32to32_;
975           VT = MVT::i32;
976           Opc2 = X86::TRUNC_GR32_GR8;
977           break;
978         }
979
980         SDOperand Tmp0, Tmp1;
981         Select(Tmp0, Node->getOperand(0));
982         Tmp1 = SDOperand(CurDAG->getTargetNode(Opc, VT, Tmp0), 0);
983         Result = CodeGenMap[N] =
984           SDOperand(CurDAG->getTargetNode(Opc2, NVT, Tmp1), 0);
985       
986 #ifndef NDEBUG
987         DEBUG(std::cerr << std::string(Indent-2, ' '));
988         DEBUG(std::cerr << "== ");
989         DEBUG(Result.Val->dump(CurDAG));
990         DEBUG(std::cerr << "\n");
991         Indent -= 2;
992 #endif
993         return;
994       }
995
996       break;
997     }
998   }
999
1000   SelectCode(Result, N);
1001 #ifndef NDEBUG
1002   DEBUG(std::cerr << std::string(Indent-2, ' '));
1003   DEBUG(std::cerr << "=> ");
1004   DEBUG(Result.Val->dump(CurDAG));
1005   DEBUG(std::cerr << "\n");
1006   Indent -= 2;
1007 #endif
1008 }
1009
1010 bool X86DAGToDAGISel::
1011 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1012                              std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1013   SDOperand Op0, Op1, Op2, Op3;
1014   switch (ConstraintCode) {
1015   case 'o':   // offsetable        ??
1016   case 'v':   // not offsetable    ??
1017   default: return true;
1018   case 'm':   // memory
1019     if (!SelectAddr(Op, Op0, Op1, Op2, Op3))
1020       return true;
1021     break;
1022   }
1023   
1024   OutOps.resize(4);
1025   Select(OutOps[0], Op0);
1026   Select(OutOps[1], Op1);
1027   Select(OutOps[2], Op2);
1028   Select(OutOps[3], Op3);
1029   return false;
1030 }
1031
1032 /// createX86ISelDag - This pass converts a legalized DAG into a 
1033 /// X86-specific DAG, ready for instruction scheduling.
1034 ///
1035 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM) {
1036   return new X86DAGToDAGISel(TM);
1037 }