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