Revert r77654, it appears to be causing llvm-gcc bootstrap failures, and many
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
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 implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetFrameInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <algorithm>
55 using namespace llvm;
56
57 static cl::opt<bool>
58 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
59 static cl::opt<bool>
60 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
61           cl::desc("Enable verbose messages in the \"fast\" "
62                    "instruction selector"));
63 static cl::opt<bool>
64 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
65           cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 static cl::opt<bool>
67 SchedLiveInCopies("schedule-livein-copies",
68                   cl::desc("Schedule copies of livein registers"),
69                   cl::init(false));
70
71 #ifndef NDEBUG
72 static cl::opt<bool>
73 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
74           cl::desc("Pop up a window to show dags before the first "
75                    "dag combine pass"));
76 static cl::opt<bool>
77 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
78           cl::desc("Pop up a window to show dags before legalize types"));
79 static cl::opt<bool>
80 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
81           cl::desc("Pop up a window to show dags before legalize"));
82 static cl::opt<bool>
83 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
84           cl::desc("Pop up a window to show dags before the second "
85                    "dag combine pass"));
86 static cl::opt<bool>
87 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
88           cl::desc("Pop up a window to show dags before the post legalize types"
89                    " dag combine pass"));
90 static cl::opt<bool>
91 ViewISelDAGs("view-isel-dags", cl::Hidden,
92           cl::desc("Pop up a window to show isel dags as they are selected"));
93 static cl::opt<bool>
94 ViewSchedDAGs("view-sched-dags", cl::Hidden,
95           cl::desc("Pop up a window to show sched dags as they are processed"));
96 static cl::opt<bool>
97 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
98       cl::desc("Pop up a window to show SUnit dags after they are processed"));
99 #else
100 static const bool ViewDAGCombine1 = false,
101                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
102                   ViewDAGCombine2 = false,
103                   ViewDAGCombineLT = false,
104                   ViewISelDAGs = false, ViewSchedDAGs = false,
105                   ViewSUnitDAGs = false;
106 #endif
107
108 //===---------------------------------------------------------------------===//
109 ///
110 /// RegisterScheduler class - Track the registration of instruction schedulers.
111 ///
112 //===---------------------------------------------------------------------===//
113 MachinePassRegistry RegisterScheduler::Registry;
114
115 //===---------------------------------------------------------------------===//
116 ///
117 /// ISHeuristic command line option for instruction schedulers.
118 ///
119 //===---------------------------------------------------------------------===//
120 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
121                RegisterPassParser<RegisterScheduler> >
122 ISHeuristic("pre-RA-sched",
123             cl::init(&createDefaultScheduler),
124             cl::desc("Instruction schedulers available (before register"
125                      " allocation):"));
126
127 static RegisterScheduler
128 defaultListDAGScheduler("default", "Best scheduler for the target",
129                         createDefaultScheduler);
130
131 namespace llvm {
132   //===--------------------------------------------------------------------===//
133   /// createDefaultScheduler - This creates an instruction scheduler appropriate
134   /// for the target.
135   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
136                                              CodeGenOpt::Level OptLevel) {
137     const TargetLowering &TLI = IS->getTargetLowering();
138
139     if (OptLevel == CodeGenOpt::None)
140       return createFastDAGScheduler(IS, OptLevel);
141     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
142       return createTDListDAGScheduler(IS, OptLevel);
143     assert(TLI.getSchedulingPreference() ==
144          TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
145     return createBURRListDAGScheduler(IS, OptLevel);
146   }
147 }
148
149 // EmitInstrWithCustomInserter - This method should be implemented by targets
150 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
151 // instructions are special in various ways, which require special support to
152 // insert.  The specified MachineInstr is created but not inserted into any
153 // basic blocks, and the scheduler passes ownership of it to this method.
154 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
155                                                  MachineBasicBlock *MBB) const {
156 #ifndef NDEBUG
157   cerr << "If a target marks an instruction with "
158           "'usesCustomDAGSchedInserter', it must implement "
159           "TargetLowering::EmitInstrWithCustomInserter!";
160 #endif
161   llvm_unreachable(0);
162   return 0;  
163 }
164
165 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
166 /// physical register has only a single copy use, then coalesced the copy
167 /// if possible.
168 static void EmitLiveInCopy(MachineBasicBlock *MBB,
169                            MachineBasicBlock::iterator &InsertPos,
170                            unsigned VirtReg, unsigned PhysReg,
171                            const TargetRegisterClass *RC,
172                            DenseMap<MachineInstr*, unsigned> &CopyRegMap,
173                            const MachineRegisterInfo &MRI,
174                            const TargetRegisterInfo &TRI,
175                            const TargetInstrInfo &TII) {
176   unsigned NumUses = 0;
177   MachineInstr *UseMI = NULL;
178   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
179          UE = MRI.use_end(); UI != UE; ++UI) {
180     UseMI = &*UI;
181     if (++NumUses > 1)
182       break;
183   }
184
185   // If the number of uses is not one, or the use is not a move instruction,
186   // don't coalesce. Also, only coalesce away a virtual register to virtual
187   // register copy.
188   bool Coalesced = false;
189   unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
190   if (NumUses == 1 &&
191       TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
192       TargetRegisterInfo::isVirtualRegister(DstReg)) {
193     VirtReg = DstReg;
194     Coalesced = true;
195   }
196
197   // Now find an ideal location to insert the copy.
198   MachineBasicBlock::iterator Pos = InsertPos;
199   while (Pos != MBB->begin()) {
200     MachineInstr *PrevMI = prior(Pos);
201     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
202     // copyRegToReg might emit multiple instructions to do a copy.
203     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
204     if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
205       // This is what the BB looks like right now:
206       // r1024 = mov r0
207       // ...
208       // r1    = mov r1024
209       //
210       // We want to insert "r1025 = mov r1". Inserting this copy below the
211       // move to r1024 makes it impossible for that move to be coalesced.
212       //
213       // r1025 = mov r1
214       // r1024 = mov r0
215       // ...
216       // r1    = mov 1024
217       // r2    = mov 1025
218       break; // Woot! Found a good location.
219     --Pos;
220   }
221
222   bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
223   assert(Emitted && "Unable to issue a live-in copy instruction!\n");
224   (void) Emitted;
225   
226 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
227   if (Coalesced) {
228     if (&*InsertPos == UseMI) ++InsertPos;
229     MBB->erase(UseMI);
230   }
231 }
232
233 /// EmitLiveInCopies - If this is the first basic block in the function,
234 /// and if it has live ins that need to be copied into vregs, emit the
235 /// copies into the block.
236 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
237                              const MachineRegisterInfo &MRI,
238                              const TargetRegisterInfo &TRI,
239                              const TargetInstrInfo &TII) {
240   if (SchedLiveInCopies) {
241     // Emit the copies at a heuristically-determined location in the block.
242     DenseMap<MachineInstr*, unsigned> CopyRegMap;
243     MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
244     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
245            E = MRI.livein_end(); LI != E; ++LI)
246       if (LI->second) {
247         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
248         EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
249                        RC, CopyRegMap, MRI, TRI, TII);
250       }
251   } else {
252     // Emit the copies into the top of the block.
253     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
254            E = MRI.livein_end(); LI != E; ++LI)
255       if (LI->second) {
256         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
257         bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
258                                         LI->second, LI->first, RC, RC);
259         assert(Emitted && "Unable to issue a live-in copy instruction!\n");
260         (void) Emitted;
261       }
262   }
263 }
264
265 //===----------------------------------------------------------------------===//
266 // SelectionDAGISel code
267 //===----------------------------------------------------------------------===//
268
269 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
270   FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
271   FuncInfo(new FunctionLoweringInfo(TLI)),
272   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
273   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
274   GFI(),
275   OptLevel(OL),
276   DAGSize(0)
277 {}
278
279 SelectionDAGISel::~SelectionDAGISel() {
280   delete SDL;
281   delete CurDAG;
282   delete FuncInfo;
283 }
284
285 unsigned SelectionDAGISel::MakeReg(MVT VT) {
286   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
287 }
288
289 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
290   AU.addRequired<AliasAnalysis>();
291   AU.addRequired<GCModuleInfo>();
292   AU.addRequired<DwarfWriter>();
293   AU.setPreservesAll();
294 }
295
296 bool SelectionDAGISel::runOnFunction(Function &Fn) {
297   // Do some sanity-checking on the command-line options.
298   assert((!EnableFastISelVerbose || EnableFastISel) &&
299          "-fast-isel-verbose requires -fast-isel");
300   assert((!EnableFastISelAbort || EnableFastISel) &&
301          "-fast-isel-abort requires -fast-isel");
302
303   // Do not codegen any 'available_externally' functions at all, they have
304   // definitions outside the translation unit.
305   if (Fn.hasAvailableExternallyLinkage())
306     return false;
307
308
309   // Get alias analysis for load/store combining.
310   AA = &getAnalysis<AliasAnalysis>();
311
312   TargetMachine &TM = TLI.getTargetMachine();
313   MF = &MachineFunction::construct(&Fn, TM);
314   const TargetInstrInfo &TII = *TM.getInstrInfo();
315   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
316
317   if (MF->getFunction()->hasGC())
318     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
319   else
320     GFI = 0;
321   RegInfo = &MF->getRegInfo();
322   DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
323
324   MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
325   DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
326   CurDAG->init(*MF, MMI, DW);
327   FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
328   SDL->init(GFI, *AA);
329
330   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
331     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
332       // Mark landing pad.
333       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
334
335   SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
336
337   // If the first basic block in the function has live ins that need to be
338   // copied into vregs, emit the copies into the top of the block before
339   // emitting the code for the block.
340   EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
341
342   // Add function live-ins to entry block live-in set.
343   for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
344          E = RegInfo->livein_end(); I != E; ++I)
345     MF->begin()->addLiveIn(I->first);
346
347 #ifndef NDEBUG
348   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
349          "Not all catch info was assigned to a landing pad!");
350 #endif
351
352   FuncInfo->clear();
353
354   return true;
355 }
356
357 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
358                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
359   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
360     if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
361       // Apply the catch info to DestBB.
362       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
363 #ifndef NDEBUG
364       if (!FLI.MBBMap[SrcBB]->isLandingPad())
365         FLI.CatchInfoFound.insert(EHSel);
366 #endif
367     }
368 }
369
370 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
371 /// whether object offset >= 0.
372 static bool
373 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
374   if (!isa<FrameIndexSDNode>(Op)) return false;
375
376   FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
377   int FrameIdx =  FrameIdxNode->getIndex();
378   return MFI->isFixedObjectIndex(FrameIdx) &&
379     MFI->getObjectOffset(FrameIdx) >= 0;
380 }
381
382 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
383 /// possibly be overwritten when lowering the outgoing arguments in a tail
384 /// call. Currently the implementation of this call is very conservative and
385 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
386 /// virtual registers would be overwritten by direct lowering.
387 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
388                                                     MachineFrameInfo *MFI) {
389   RegisterSDNode * OpReg = NULL;
390   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
391       (Op.getOpcode()== ISD::CopyFromReg &&
392        (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
393        (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
394       (Op.getOpcode() == ISD::LOAD &&
395        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
396       (Op.getOpcode() == ISD::MERGE_VALUES &&
397        Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
398        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
399                                        getOperand(1))))
400     return true;
401   return false;
402 }
403
404 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
405 /// DAG and fixes their tailcall attribute operand.
406 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 
407                                            const TargetLowering& TLI) {
408   SDNode * Ret = NULL;
409   SDValue Terminator = DAG.getRoot();
410
411   // Find RET node.
412   if (Terminator.getOpcode() == ISD::RET) {
413     Ret = Terminator.getNode();
414   }
415  
416   // Fix tail call attribute of CALL nodes.
417   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
418          BI = DAG.allnodes_end(); BI != BE; ) {
419     --BI;
420     if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
421       SDValue OpRet(Ret, 0);
422       SDValue OpCall(BI, 0);
423       bool isMarkedTailCall = TheCall->isTailCall();
424       // If CALL node has tail call attribute set to true and the call is not
425       // eligible (no RET or the target rejects) the attribute is fixed to
426       // false. The TargetLowering::IsEligibleForTailCallOptimization function
427       // must correctly identify tail call optimizable calls.
428       if (!isMarkedTailCall) continue;
429       if (Ret==NULL ||
430           !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
431         // Not eligible. Mark CALL node as non tail call. Note that we
432         // can modify the call node in place since calls are not CSE'd.
433         TheCall->setNotTailCall();
434       } else {
435         // Look for tail call clobbered arguments. Emit a series of
436         // copyto/copyfrom virtual register nodes to protect them.
437         SmallVector<SDValue, 32> Ops;
438         SDValue Chain = TheCall->getChain(), InFlag;
439         Ops.push_back(Chain);
440         Ops.push_back(TheCall->getCallee());
441         for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
442           SDValue Arg = TheCall->getArg(i);
443           bool isByVal = TheCall->getArgFlags(i).isByVal();
444           MachineFunction &MF = DAG.getMachineFunction();
445           MachineFrameInfo *MFI = MF.getFrameInfo();
446           if (!isByVal &&
447               IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
448             MVT VT = Arg.getValueType();
449             unsigned VReg = MF.getRegInfo().
450               createVirtualRegister(TLI.getRegClassFor(VT));
451             Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
452                                      VReg, Arg, InFlag);
453             InFlag = Chain.getValue(1);
454             Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
455                                      VReg, VT, InFlag);
456             Chain = Arg.getValue(1);
457             InFlag = Arg.getValue(2);
458           }
459           Ops.push_back(Arg);
460           Ops.push_back(TheCall->getArgFlagsVal(i));
461         }
462         // Link in chain of CopyTo/CopyFromReg.
463         Ops[0] = Chain;
464         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
465       }
466     }
467   }
468 }
469
470 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
471                                         BasicBlock::iterator Begin,
472                                         BasicBlock::iterator End) {
473   SDL->setCurrentBasicBlock(BB);
474
475   // Lower all of the non-terminator instructions.
476   for (BasicBlock::iterator I = Begin; I != End; ++I)
477     if (!isa<TerminatorInst>(I))
478       SDL->visit(*I);
479
480   // Ensure that all instructions which are used outside of their defining
481   // blocks are available as virtual registers.  Invoke is handled elsewhere.
482   for (BasicBlock::iterator I = Begin; I != End; ++I)
483     if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
484       SDL->CopyToExportRegsIfNeeded(I);
485
486   // Handle PHI nodes in successor blocks.
487   if (End == LLVMBB->end()) {
488     HandlePHINodesInSuccessorBlocks(LLVMBB);
489
490     // Lower the terminator after the copies are emitted.
491     SDL->visit(*LLVMBB->getTerminator());
492   }
493     
494   // Make sure the root of the DAG is up-to-date.
495   CurDAG->setRoot(SDL->getControlRoot());
496
497   // Check whether calls in this block are real tail calls. Fix up CALL nodes
498   // with correct tailcall attribute so that the target can rely on the tailcall
499   // attribute indicating whether the call is really eligible for tail call
500   // optimization.
501   if (PerformTailCallOpt)
502     CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
503
504   // Final step, emit the lowered DAG as machine code.
505   CodeGenAndEmitDAG();
506   SDL->clear();
507 }
508
509 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
510   SmallPtrSet<SDNode*, 128> VisitedNodes;
511   SmallVector<SDNode*, 128> Worklist;
512   
513   Worklist.push_back(CurDAG->getRoot().getNode());
514   
515   APInt Mask;
516   APInt KnownZero;
517   APInt KnownOne;
518   
519   while (!Worklist.empty()) {
520     SDNode *N = Worklist.back();
521     Worklist.pop_back();
522     
523     // If we've already seen this node, ignore it.
524     if (!VisitedNodes.insert(N))
525       continue;
526     
527     // Otherwise, add all chain operands to the worklist.
528     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
529       if (N->getOperand(i).getValueType() == MVT::Other)
530         Worklist.push_back(N->getOperand(i).getNode());
531     
532     // If this is a CopyToReg with a vreg dest, process it.
533     if (N->getOpcode() != ISD::CopyToReg)
534       continue;
535     
536     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
537     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
538       continue;
539     
540     // Ignore non-scalar or non-integer values.
541     SDValue Src = N->getOperand(2);
542     MVT SrcVT = Src.getValueType();
543     if (!SrcVT.isInteger() || SrcVT.isVector())
544       continue;
545     
546     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
547     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
548     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
549     
550     // Only install this information if it tells us something.
551     if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
552       DestReg -= TargetRegisterInfo::FirstVirtualRegister;
553       FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
554       if (DestReg >= FLI.LiveOutRegInfo.size())
555         FLI.LiveOutRegInfo.resize(DestReg+1);
556       FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
557       LOI.NumSignBits = NumSignBits;
558       LOI.KnownOne = KnownOne;
559       LOI.KnownZero = KnownZero;
560     }
561   }
562 }
563
564 void SelectionDAGISel::CodeGenAndEmitDAG() {
565   std::string GroupName;
566   if (TimePassesIsEnabled)
567     GroupName = "Instruction Selection and Scheduling";
568   std::string BlockName;
569   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
570       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
571       ViewSUnitDAGs)
572     BlockName = CurDAG->getMachineFunction().getFunction()->getNameStr() + ":" +
573                 BB->getBasicBlock()->getNameStr();
574
575   DOUT << "Initial selection DAG:\n";
576   DEBUG(CurDAG->dump());
577
578   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
579
580   // Run the DAG combiner in pre-legalize mode.
581   if (TimePassesIsEnabled) {
582     NamedRegionTimer T("DAG Combining 1", GroupName);
583     CurDAG->Combine(Unrestricted, *AA, OptLevel);
584   } else {
585     CurDAG->Combine(Unrestricted, *AA, OptLevel);
586   }
587   
588   DOUT << "Optimized lowered selection DAG:\n";
589   DEBUG(CurDAG->dump());
590   
591   // Second step, hack on the DAG until it only uses operations and types that
592   // the target supports.
593   if (!DisableLegalizeTypes) {
594     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
595                                                  BlockName);
596
597     bool Changed;
598     if (TimePassesIsEnabled) {
599       NamedRegionTimer T("Type Legalization", GroupName);
600       Changed = CurDAG->LegalizeTypes();
601     } else {
602       Changed = CurDAG->LegalizeTypes();
603     }
604
605     DOUT << "Type-legalized selection DAG:\n";
606     DEBUG(CurDAG->dump());
607
608     if (Changed) {
609       if (ViewDAGCombineLT)
610         CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
611
612       // Run the DAG combiner in post-type-legalize mode.
613       if (TimePassesIsEnabled) {
614         NamedRegionTimer T("DAG Combining after legalize types", GroupName);
615         CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
616       } else {
617         CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
618       }
619
620       DOUT << "Optimized type-legalized selection DAG:\n";
621       DEBUG(CurDAG->dump());
622     }
623
624     if (TimePassesIsEnabled) {
625       NamedRegionTimer T("Vector Legalization", GroupName);
626       Changed = CurDAG->LegalizeVectors();
627     } else {
628       Changed = CurDAG->LegalizeVectors();
629     }
630
631     if (Changed) {
632       if (TimePassesIsEnabled) {
633         NamedRegionTimer T("Type Legalization 2", GroupName);
634         Changed = CurDAG->LegalizeTypes();
635       } else {
636         Changed = CurDAG->LegalizeTypes();
637       }
638
639       if (ViewDAGCombineLT)
640         CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
641
642       // Run the DAG combiner in post-type-legalize mode.
643       if (TimePassesIsEnabled) {
644         NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
645         CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
646       } else {
647         CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
648       }
649
650       DOUT << "Optimized vector-legalized selection DAG:\n";
651       DEBUG(CurDAG->dump());
652     }
653   }
654   
655   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
656
657   if (TimePassesIsEnabled) {
658     NamedRegionTimer T("DAG Legalization", GroupName);
659     CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
660   } else {
661     CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
662   }
663   
664   DOUT << "Legalized selection DAG:\n";
665   DEBUG(CurDAG->dump());
666   
667   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
668
669   // Run the DAG combiner in post-legalize mode.
670   if (TimePassesIsEnabled) {
671     NamedRegionTimer T("DAG Combining 2", GroupName);
672     CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
673   } else {
674     CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
675   }
676   
677   DOUT << "Optimized legalized selection DAG:\n";
678   DEBUG(CurDAG->dump());
679
680   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
681   
682   if (OptLevel != CodeGenOpt::None)
683     ComputeLiveOutVRegInfo();
684
685   // Third, instruction select all of the operations to machine code, adding the
686   // code to the MachineBasicBlock.
687   if (TimePassesIsEnabled) {
688     NamedRegionTimer T("Instruction Selection", GroupName);
689     InstructionSelect();
690   } else {
691     InstructionSelect();
692   }
693
694   DOUT << "Selected selection DAG:\n";
695   DEBUG(CurDAG->dump());
696
697   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
698
699   // Schedule machine code.
700   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
701   if (TimePassesIsEnabled) {
702     NamedRegionTimer T("Instruction Scheduling", GroupName);
703     Scheduler->Run(CurDAG, BB, BB->end());
704   } else {
705     Scheduler->Run(CurDAG, BB, BB->end());
706   }
707
708   if (ViewSUnitDAGs) Scheduler->viewGraph();
709
710   // Emit machine code to BB.  This can change 'BB' to the last block being 
711   // inserted into.
712   if (TimePassesIsEnabled) {
713     NamedRegionTimer T("Instruction Creation", GroupName);
714     BB = Scheduler->EmitSchedule();
715   } else {
716     BB = Scheduler->EmitSchedule();
717   }
718
719   // Free the scheduler state.
720   if (TimePassesIsEnabled) {
721     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
722     delete Scheduler;
723   } else {
724     delete Scheduler;
725   }
726
727   DOUT << "Selected machine code:\n";
728   DEBUG(BB->dump());
729 }  
730
731 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
732                                             MachineFunction &MF,
733                                             MachineModuleInfo *MMI,
734                                             DwarfWriter *DW,
735                                             const TargetInstrInfo &TII) {
736   // Initialize the Fast-ISel state, if needed.
737   FastISel *FastIS = 0;
738   if (EnableFastISel)
739     FastIS = TLI.createFastISel(MF, MMI, DW,
740                                 FuncInfo->ValueMap,
741                                 FuncInfo->MBBMap,
742                                 FuncInfo->StaticAllocaMap
743 #ifndef NDEBUG
744                                 , FuncInfo->CatchInfoLost
745 #endif
746                                 );
747
748   // Iterate over all basic blocks in the function.
749   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
750     BasicBlock *LLVMBB = &*I;
751     BB = FuncInfo->MBBMap[LLVMBB];
752
753     BasicBlock::iterator const Begin = LLVMBB->begin();
754     BasicBlock::iterator const End = LLVMBB->end();
755     BasicBlock::iterator BI = Begin;
756
757     // Lower any arguments needed in this block if this is the entry block.
758     bool SuppressFastISel = false;
759     if (LLVMBB == &Fn.getEntryBlock()) {
760       LowerArguments(LLVMBB);
761
762       // If any of the arguments has the byval attribute, forgo
763       // fast-isel in the entry block.
764       if (FastIS) {
765         unsigned j = 1;
766         for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
767              I != E; ++I, ++j)
768           if (Fn.paramHasAttr(j, Attribute::ByVal)) {
769             if (EnableFastISelVerbose || EnableFastISelAbort)
770               cerr << "FastISel skips entry block due to byval argument\n";
771             SuppressFastISel = true;
772             break;
773           }
774       }
775     }
776
777     if (MMI && BB->isLandingPad()) {
778       // Add a label to mark the beginning of the landing pad.  Deletion of the
779       // landing pad can thus be detected via the MachineModuleInfo.
780       unsigned LabelID = MMI->addLandingPad(BB);
781
782       const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
783       BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
784
785       // Mark exception register as live in.
786       unsigned Reg = TLI.getExceptionAddressRegister();
787       if (Reg) BB->addLiveIn(Reg);
788
789       // Mark exception selector register as live in.
790       Reg = TLI.getExceptionSelectorRegister();
791       if (Reg) BB->addLiveIn(Reg);
792
793       // FIXME: Hack around an exception handling flaw (PR1508): the personality
794       // function and list of typeids logically belong to the invoke (or, if you
795       // like, the basic block containing the invoke), and need to be associated
796       // with it in the dwarf exception handling tables.  Currently however the
797       // information is provided by an intrinsic (eh.selector) that can be moved
798       // to unexpected places by the optimizers: if the unwind edge is critical,
799       // then breaking it can result in the intrinsics being in the successor of
800       // the landing pad, not the landing pad itself.  This results in exceptions
801       // not being caught because no typeids are associated with the invoke.
802       // This may not be the only way things can go wrong, but it is the only way
803       // we try to work around for the moment.
804       BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
805
806       if (Br && Br->isUnconditional()) { // Critical edge?
807         BasicBlock::iterator I, E;
808         for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
809           if (isa<EHSelectorInst>(I))
810             break;
811
812         if (I == E)
813           // No catch info found - try to extract some from the successor.
814           copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
815       }
816     }
817
818     // Before doing SelectionDAG ISel, see if FastISel has been requested.
819     if (FastIS && !SuppressFastISel) {
820       // Emit code for any incoming arguments. This must happen before
821       // beginning FastISel on the entry block.
822       if (LLVMBB == &Fn.getEntryBlock()) {
823         CurDAG->setRoot(SDL->getControlRoot());
824         CodeGenAndEmitDAG();
825         SDL->clear();
826       }
827       FastIS->startNewBlock(BB);
828       // Do FastISel on as many instructions as possible.
829       for (; BI != End; ++BI) {
830         // Just before the terminator instruction, insert instructions to
831         // feed PHI nodes in successor blocks.
832         if (isa<TerminatorInst>(BI))
833           if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
834             if (EnableFastISelVerbose || EnableFastISelAbort) {
835               cerr << "FastISel miss: ";
836               BI->dump();
837             }
838             assert(!EnableFastISelAbort && 
839                    "FastISel didn't handle a PHI in a successor");
840             break;
841           }
842
843         // First try normal tablegen-generated "fast" selection.
844         if (FastIS->SelectInstruction(BI))
845           continue;
846
847         // Next, try calling the target to attempt to handle the instruction.
848         if (FastIS->TargetSelectInstruction(BI))
849           continue;
850
851         // Then handle certain instructions as single-LLVM-Instruction blocks.
852         if (isa<CallInst>(BI)) {
853           if (EnableFastISelVerbose || EnableFastISelAbort) {
854             cerr << "FastISel missed call: ";
855             BI->dump();
856           }
857
858           if (BI->getType() != Type::VoidTy) {
859             unsigned &R = FuncInfo->ValueMap[BI];
860             if (!R)
861               R = FuncInfo->CreateRegForValue(BI);
862           }
863
864           SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
865           SelectBasicBlock(LLVMBB, BI, next(BI));
866           // If the instruction was codegen'd with multiple blocks,
867           // inform the FastISel object where to resume inserting.
868           FastIS->setCurrentBlock(BB);
869           continue;
870         }
871
872         // Otherwise, give up on FastISel for the rest of the block.
873         // For now, be a little lenient about non-branch terminators.
874         if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
875           if (EnableFastISelVerbose || EnableFastISelAbort) {
876             cerr << "FastISel miss: ";
877             BI->dump();
878           }
879           if (EnableFastISelAbort)
880             // The "fast" selector couldn't handle something and bailed.
881             // For the purpose of debugging, just abort.
882             llvm_unreachable("FastISel didn't select the entire block");
883         }
884         break;
885       }
886     }
887
888     // Run SelectionDAG instruction selection on the remainder of the block
889     // not handled by FastISel. If FastISel is not run, this is the entire
890     // block.
891     if (BI != End) {
892       // If FastISel is run and it has known DebugLoc then use it.
893       if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
894         SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
895       SelectBasicBlock(LLVMBB, BI, End);
896     }
897
898     FinishBasicBlock();
899   }
900
901   delete FastIS;
902 }
903
904 void
905 SelectionDAGISel::FinishBasicBlock() {
906
907   DOUT << "Target-post-processed machine code:\n";
908   DEBUG(BB->dump());
909
910   DOUT << "Total amount of phi nodes to update: "
911        << SDL->PHINodesToUpdate.size() << "\n";
912   DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
913           DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
914                << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
915   
916   // Next, now that we know what the last MBB the LLVM BB expanded is, update
917   // PHI nodes in successors.
918   if (SDL->SwitchCases.empty() &&
919       SDL->JTCases.empty() &&
920       SDL->BitTestCases.empty()) {
921     for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
922       MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
923       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
924              "This is not a machine PHI node that we are updating!");
925       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
926                                                 false));
927       PHI->addOperand(MachineOperand::CreateMBB(BB));
928     }
929     SDL->PHINodesToUpdate.clear();
930     return;
931   }
932
933   for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
934     // Lower header first, if it wasn't already lowered
935     if (!SDL->BitTestCases[i].Emitted) {
936       // Set the current basic block to the mbb we wish to insert the code into
937       BB = SDL->BitTestCases[i].Parent;
938       SDL->setCurrentBasicBlock(BB);
939       // Emit the code
940       SDL->visitBitTestHeader(SDL->BitTestCases[i]);
941       CurDAG->setRoot(SDL->getRoot());
942       CodeGenAndEmitDAG();
943       SDL->clear();
944     }    
945
946     for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
947       // Set the current basic block to the mbb we wish to insert the code into
948       BB = SDL->BitTestCases[i].Cases[j].ThisBB;
949       SDL->setCurrentBasicBlock(BB);
950       // Emit the code
951       if (j+1 != ej)
952         SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
953                               SDL->BitTestCases[i].Reg,
954                               SDL->BitTestCases[i].Cases[j]);
955       else
956         SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
957                               SDL->BitTestCases[i].Reg,
958                               SDL->BitTestCases[i].Cases[j]);
959         
960         
961       CurDAG->setRoot(SDL->getRoot());
962       CodeGenAndEmitDAG();
963       SDL->clear();
964     }
965
966     // Update PHI Nodes
967     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
968       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
969       MachineBasicBlock *PHIBB = PHI->getParent();
970       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
971              "This is not a machine PHI node that we are updating!");
972       // This is "default" BB. We have two jumps to it. From "header" BB and
973       // from last "case" BB.
974       if (PHIBB == SDL->BitTestCases[i].Default) {
975         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
976                                                   false));
977         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
978         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
979                                                   false));
980         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
981                                                   back().ThisBB));
982       }
983       // One of "cases" BB.
984       for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
985            j != ej; ++j) {
986         MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
987         if (cBB->succ_end() !=
988             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
989           PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
990                                                     false));
991           PHI->addOperand(MachineOperand::CreateMBB(cBB));
992         }
993       }
994     }
995   }
996   SDL->BitTestCases.clear();
997
998   // If the JumpTable record is filled in, then we need to emit a jump table.
999   // Updating the PHI nodes is tricky in this case, since we need to determine
1000   // whether the PHI is a successor of the range check MBB or the jump table MBB
1001   for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
1002     // Lower header first, if it wasn't already lowered
1003     if (!SDL->JTCases[i].first.Emitted) {
1004       // Set the current basic block to the mbb we wish to insert the code into
1005       BB = SDL->JTCases[i].first.HeaderBB;
1006       SDL->setCurrentBasicBlock(BB);
1007       // Emit the code
1008       SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1009       CurDAG->setRoot(SDL->getRoot());
1010       CodeGenAndEmitDAG();
1011       SDL->clear();
1012     }
1013     
1014     // Set the current basic block to the mbb we wish to insert the code into
1015     BB = SDL->JTCases[i].second.MBB;
1016     SDL->setCurrentBasicBlock(BB);
1017     // Emit the code
1018     SDL->visitJumpTable(SDL->JTCases[i].second);
1019     CurDAG->setRoot(SDL->getRoot());
1020     CodeGenAndEmitDAG();
1021     SDL->clear();
1022     
1023     // Update PHI Nodes
1024     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1025       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
1026       MachineBasicBlock *PHIBB = PHI->getParent();
1027       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1028              "This is not a machine PHI node that we are updating!");
1029       // "default" BB. We can go there only from header BB.
1030       if (PHIBB == SDL->JTCases[i].second.Default) {
1031         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1032                                                   false));
1033         PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
1034       }
1035       // JT BB. Just iterate over successors here
1036       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
1037         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1038                                                   false));
1039         PHI->addOperand(MachineOperand::CreateMBB(BB));
1040       }
1041     }
1042   }
1043   SDL->JTCases.clear();
1044   
1045   // If the switch block involved a branch to one of the actual successors, we
1046   // need to update PHI nodes in that block.
1047   for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1048     MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1049     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1050            "This is not a machine PHI node that we are updating!");
1051     if (BB->isSuccessor(PHI->getParent())) {
1052       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1053                                                 false));
1054       PHI->addOperand(MachineOperand::CreateMBB(BB));
1055     }
1056   }
1057   
1058   // If we generated any switch lowering information, build and codegen any
1059   // additional DAGs necessary.
1060   for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1061     // Set the current basic block to the mbb we wish to insert the code into
1062     BB = SDL->SwitchCases[i].ThisBB;
1063     SDL->setCurrentBasicBlock(BB);
1064     
1065     // Emit the code
1066     SDL->visitSwitchCase(SDL->SwitchCases[i]);
1067     CurDAG->setRoot(SDL->getRoot());
1068     CodeGenAndEmitDAG();
1069     SDL->clear();
1070     
1071     // Handle any PHI nodes in successors of this chunk, as if we were coming
1072     // from the original BB before switch expansion.  Note that PHI nodes can
1073     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1074     // handle them the right number of times.
1075     while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
1076       for (MachineBasicBlock::iterator Phi = BB->begin();
1077            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1078         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1079         for (unsigned pn = 0; ; ++pn) {
1080           assert(pn != SDL->PHINodesToUpdate.size() &&
1081                  "Didn't find PHI entry!");
1082           if (SDL->PHINodesToUpdate[pn].first == Phi) {
1083             Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1084                                                       second, false));
1085             Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1086             break;
1087           }
1088         }
1089       }
1090       
1091       // Don't process RHS if same block as LHS.
1092       if (BB == SDL->SwitchCases[i].FalseBB)
1093         SDL->SwitchCases[i].FalseBB = 0;
1094       
1095       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
1096       SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1097       SDL->SwitchCases[i].FalseBB = 0;
1098     }
1099     assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1100   }
1101   SDL->SwitchCases.clear();
1102
1103   SDL->PHINodesToUpdate.clear();
1104 }
1105
1106
1107 /// Create the scheduler. If a specific scheduler was specified
1108 /// via the SchedulerRegistry, use it, otherwise select the
1109 /// one preferred by the target.
1110 ///
1111 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1112   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1113   
1114   if (!Ctor) {
1115     Ctor = ISHeuristic;
1116     RegisterScheduler::setDefault(Ctor);
1117   }
1118   
1119   return Ctor(this, OptLevel);
1120 }
1121
1122 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1123   return new ScheduleHazardRecognizer();
1124 }
1125
1126 //===----------------------------------------------------------------------===//
1127 // Helper functions used by the generated instruction selector.
1128 //===----------------------------------------------------------------------===//
1129 // Calls to these methods are generated by tblgen.
1130
1131 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1132 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1133 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1134 /// specified in the .td file (e.g. 255).
1135 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 
1136                                     int64_t DesiredMaskS) const {
1137   const APInt &ActualMask = RHS->getAPIntValue();
1138   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1139   
1140   // If the actual mask exactly matches, success!
1141   if (ActualMask == DesiredMask)
1142     return true;
1143   
1144   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1145   if (ActualMask.intersects(~DesiredMask))
1146     return false;
1147   
1148   // Otherwise, the DAG Combiner may have proven that the value coming in is
1149   // either already zero or is not demanded.  Check for known zero input bits.
1150   APInt NeededMask = DesiredMask & ~ActualMask;
1151   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1152     return true;
1153   
1154   // TODO: check to see if missing bits are just not demanded.
1155
1156   // Otherwise, this pattern doesn't match.
1157   return false;
1158 }
1159
1160 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1161 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1162 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1163 /// specified in the .td file (e.g. 255).
1164 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 
1165                                    int64_t DesiredMaskS) const {
1166   const APInt &ActualMask = RHS->getAPIntValue();
1167   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1168   
1169   // If the actual mask exactly matches, success!
1170   if (ActualMask == DesiredMask)
1171     return true;
1172   
1173   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1174   if (ActualMask.intersects(~DesiredMask))
1175     return false;
1176   
1177   // Otherwise, the DAG Combiner may have proven that the value coming in is
1178   // either already zero or is not demanded.  Check for known zero input bits.
1179   APInt NeededMask = DesiredMask & ~ActualMask;
1180   
1181   APInt KnownZero, KnownOne;
1182   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1183   
1184   // If all the missing bits in the or are already known to be set, match!
1185   if ((NeededMask & KnownOne) == NeededMask)
1186     return true;
1187   
1188   // TODO: check to see if missing bits are just not demanded.
1189   
1190   // Otherwise, this pattern doesn't match.
1191   return false;
1192 }
1193
1194
1195 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1196 /// by tblgen.  Others should not call it.
1197 void SelectionDAGISel::
1198 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1199   std::vector<SDValue> InOps;
1200   std::swap(InOps, Ops);
1201
1202   Ops.push_back(InOps[0]);  // input chain.
1203   Ops.push_back(InOps[1]);  // input asm string.
1204
1205   unsigned i = 2, e = InOps.size();
1206   if (InOps[e-1].getValueType() == MVT::Flag)
1207     --e;  // Don't process a flag operand if it is here.
1208   
1209   while (i != e) {
1210     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1211     if ((Flags & 7) != 4 /*MEM*/) {
1212       // Just skip over this operand, copying the operands verbatim.
1213       Ops.insert(Ops.end(), InOps.begin()+i,
1214                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1215       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1216     } else {
1217       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1218              "Memory operand with multiple values?");
1219       // Otherwise, this is a memory operand.  Ask the target to select it.
1220       std::vector<SDValue> SelOps;
1221       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1222         llvm_report_error("Could not match memory address.  Inline asm"
1223                           " failure!");
1224       }
1225       
1226       // Add this to the output node.
1227       MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1228       Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1229                                               IntPtrTy));
1230       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1231       i += 2;
1232     }
1233   }
1234   
1235   // Add the flag input back if present.
1236   if (e != InOps.size())
1237     Ops.push_back(InOps.back());
1238 }
1239
1240 /// findFlagUse - Return use of MVT::Flag value produced by the specified
1241 /// SDNode.
1242 ///
1243 static SDNode *findFlagUse(SDNode *N) {
1244   unsigned FlagResNo = N->getNumValues()-1;
1245   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1246     SDUse &Use = I.getUse();
1247     if (Use.getResNo() == FlagResNo)
1248       return Use.getUser();
1249   }
1250   return NULL;
1251 }
1252
1253 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1254 /// This function recursively traverses up the operand chain, ignoring
1255 /// certain nodes.
1256 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1257                           SDNode *Root,
1258                           SmallPtrSet<SDNode*, 16> &Visited) {
1259   if (Use->getNodeId() < Def->getNodeId() ||
1260       !Visited.insert(Use))
1261     return false;
1262
1263   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1264     SDNode *N = Use->getOperand(i).getNode();
1265     if (N == Def) {
1266       if (Use == ImmedUse || Use == Root)
1267         continue;  // We are not looking for immediate use.
1268       assert(N != Root);
1269       return true;
1270     }
1271
1272     // Traverse up the operand chain.
1273     if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1274       return true;
1275   }
1276   return false;
1277 }
1278
1279 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1280 /// be reached. Return true if that's the case. However, ignore direct uses
1281 /// by ImmedUse (which would be U in the example illustrated in
1282 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1283 /// case).
1284 /// FIXME: to be really generic, we should allow direct use by any node
1285 /// that is being folded. But realisticly since we only fold loads which
1286 /// have one non-chain use, we only need to watch out for load/op/store
1287 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1288 /// its chain operand.
1289 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1290   SmallPtrSet<SDNode*, 16> Visited;
1291   return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1292 }
1293
1294 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1295 /// U can be folded during instruction selection that starts at Root and
1296 /// folding N is profitable.
1297 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1298                                                   SDNode *Root) const {
1299   if (OptLevel == CodeGenOpt::None) return false;
1300
1301   // If Root use can somehow reach N through a path that that doesn't contain
1302   // U then folding N would create a cycle. e.g. In the following
1303   // diagram, Root can reach N through X. If N is folded into into Root, then
1304   // X is both a predecessor and a successor of U.
1305   //
1306   //          [N*]           //
1307   //         ^   ^           //
1308   //        /     \          //
1309   //      [U*]    [X]?       //
1310   //        ^     ^          //
1311   //         \   /           //
1312   //          \ /            //
1313   //         [Root*]         //
1314   //
1315   // * indicates nodes to be folded together.
1316   //
1317   // If Root produces a flag, then it gets (even more) interesting. Since it
1318   // will be "glued" together with its flag use in the scheduler, we need to
1319   // check if it might reach N.
1320   //
1321   //          [N*]           //
1322   //         ^   ^           //
1323   //        /     \          //
1324   //      [U*]    [X]?       //
1325   //        ^       ^        //
1326   //         \       \       //
1327   //          \      |       //
1328   //         [Root*] |       //
1329   //          ^      |       //
1330   //          f      |       //
1331   //          |      /       //
1332   //         [Y]    /        //
1333   //           ^   /         //
1334   //           f  /          //
1335   //           | /           //
1336   //          [FU]           //
1337   //
1338   // If FU (flag use) indirectly reaches N (the load), and Root folds N
1339   // (call it Fold), then X is a predecessor of FU and a successor of
1340   // Fold. But since Fold and FU are flagged together, this will create
1341   // a cycle in the scheduling graph.
1342
1343   MVT VT = Root->getValueType(Root->getNumValues()-1);
1344   while (VT == MVT::Flag) {
1345     SDNode *FU = findFlagUse(Root);
1346     if (FU == NULL)
1347       break;
1348     Root = FU;
1349     VT = Root->getValueType(Root->getNumValues()-1);
1350   }
1351
1352   return !isNonImmUse(Root, N, U);
1353 }
1354
1355
1356 char SelectionDAGISel::ID = 0;