34878f34425cc3768bdd6809a9d455ff15425271
[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 "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/ParameterAttributes.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/ScheduleDAG.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/Timer.h"
51 #include <algorithm>
52 using namespace llvm;
53
54 static cl::opt<bool>
55 EnableValueProp("enable-value-prop", cl::Hidden);
56 static cl::opt<bool>
57 EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
58 static cl::opt<bool>
59 EnableFastISel("fast-isel", cl::Hidden,
60           cl::desc("Enable the experimental \"fast\" instruction selector"));
61 static cl::opt<bool>
62 DisableFastISelAbort("fast-isel-no-abort", cl::Hidden,
63           cl::desc("Use the SelectionDAGISel when \"fast\" instruction "
64                    "selection fails"));
65
66 #ifndef NDEBUG
67 static cl::opt<bool>
68 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
69           cl::desc("Pop up a window to show dags before the first "
70                    "dag combine pass"));
71 static cl::opt<bool>
72 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
73           cl::desc("Pop up a window to show dags before legalize types"));
74 static cl::opt<bool>
75 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
76           cl::desc("Pop up a window to show dags before legalize"));
77 static cl::opt<bool>
78 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
79           cl::desc("Pop up a window to show dags before the second "
80                    "dag combine pass"));
81 static cl::opt<bool>
82 ViewISelDAGs("view-isel-dags", cl::Hidden,
83           cl::desc("Pop up a window to show isel dags as they are selected"));
84 static cl::opt<bool>
85 ViewSchedDAGs("view-sched-dags", cl::Hidden,
86           cl::desc("Pop up a window to show sched dags as they are processed"));
87 static cl::opt<bool>
88 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
89       cl::desc("Pop up a window to show SUnit dags after they are processed"));
90 #else
91 static const bool ViewDAGCombine1 = false,
92                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
93                   ViewDAGCombine2 = false,
94                   ViewISelDAGs = false, ViewSchedDAGs = false,
95                   ViewSUnitDAGs = false;
96 #endif
97
98 //===---------------------------------------------------------------------===//
99 ///
100 /// RegisterScheduler class - Track the registration of instruction schedulers.
101 ///
102 //===---------------------------------------------------------------------===//
103 MachinePassRegistry RegisterScheduler::Registry;
104
105 //===---------------------------------------------------------------------===//
106 ///
107 /// ISHeuristic command line option for instruction schedulers.
108 ///
109 //===---------------------------------------------------------------------===//
110 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
111                RegisterPassParser<RegisterScheduler> >
112 ISHeuristic("pre-RA-sched",
113             cl::init(&createDefaultScheduler),
114             cl::desc("Instruction schedulers available (before register"
115                      " allocation):"));
116
117 static RegisterScheduler
118 defaultListDAGScheduler("default", "  Best scheduler for the target",
119                         createDefaultScheduler);
120
121 namespace { struct SDISelAsmOperandInfo; }
122
123 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
124 /// insertvalue or extractvalue indices that identify a member, return
125 /// the linearized index of the start of the member.
126 ///
127 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
128                                    const unsigned *Indices,
129                                    const unsigned *IndicesEnd,
130                                    unsigned CurIndex = 0) {
131   // Base case: We're done.
132   if (Indices && Indices == IndicesEnd)
133     return CurIndex;
134
135   // Given a struct type, recursively traverse the elements.
136   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
137     for (StructType::element_iterator EB = STy->element_begin(),
138                                       EI = EB,
139                                       EE = STy->element_end();
140         EI != EE; ++EI) {
141       if (Indices && *Indices == unsigned(EI - EB))
142         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
143       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
144     }
145   }
146   // Given an array type, recursively traverse the elements.
147   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
148     const Type *EltTy = ATy->getElementType();
149     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
150       if (Indices && *Indices == i)
151         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
152       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
153     }
154   }
155   // We haven't found the type we're looking for, so keep searching.
156   return CurIndex + 1;
157 }
158
159 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
160 /// MVTs that represent all the individual underlying
161 /// non-aggregate types that comprise it.
162 ///
163 /// If Offsets is non-null, it points to a vector to be filled in
164 /// with the in-memory offsets of each of the individual values.
165 ///
166 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
167                             SmallVectorImpl<MVT> &ValueVTs,
168                             SmallVectorImpl<uint64_t> *Offsets = 0,
169                             uint64_t StartingOffset = 0) {
170   // Given a struct type, recursively traverse the elements.
171   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
172     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
173     for (StructType::element_iterator EB = STy->element_begin(),
174                                       EI = EB,
175                                       EE = STy->element_end();
176          EI != EE; ++EI)
177       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
178                       StartingOffset + SL->getElementOffset(EI - EB));
179     return;
180   }
181   // Given an array type, recursively traverse the elements.
182   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
183     const Type *EltTy = ATy->getElementType();
184     uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
185     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
186       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
187                       StartingOffset + i * EltSize);
188     return;
189   }
190   // Base case: we can get an MVT for this LLVM IR type.
191   ValueVTs.push_back(TLI.getValueType(Ty));
192   if (Offsets)
193     Offsets->push_back(StartingOffset);
194 }
195
196 namespace {
197   /// RegsForValue - This struct represents the registers (physical or virtual)
198   /// that a particular set of values is assigned, and the type information about
199   /// the value. The most common situation is to represent one value at a time,
200   /// but struct or array values are handled element-wise as multiple values.
201   /// The splitting of aggregates is performed recursively, so that we never
202   /// have aggregate-typed registers. The values at this point do not necessarily
203   /// have legal types, so each value may require one or more registers of some
204   /// legal type.
205   /// 
206   struct VISIBILITY_HIDDEN RegsForValue {
207     /// TLI - The TargetLowering object.
208     ///
209     const TargetLowering *TLI;
210
211     /// ValueVTs - The value types of the values, which may not be legal, and
212     /// may need be promoted or synthesized from one or more registers.
213     ///
214     SmallVector<MVT, 4> ValueVTs;
215     
216     /// RegVTs - The value types of the registers. This is the same size as
217     /// ValueVTs and it records, for each value, what the type of the assigned
218     /// register or registers are. (Individual values are never synthesized
219     /// from more than one type of register.)
220     ///
221     /// With virtual registers, the contents of RegVTs is redundant with TLI's
222     /// getRegisterType member function, however when with physical registers
223     /// it is necessary to have a separate record of the types.
224     ///
225     SmallVector<MVT, 4> RegVTs;
226     
227     /// Regs - This list holds the registers assigned to the values.
228     /// Each legal or promoted value requires one register, and each
229     /// expanded value requires multiple registers.
230     ///
231     SmallVector<unsigned, 4> Regs;
232     
233     RegsForValue() : TLI(0) {}
234     
235     RegsForValue(const TargetLowering &tli,
236                  const SmallVector<unsigned, 4> &regs, 
237                  MVT regvt, MVT valuevt)
238       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
239     RegsForValue(const TargetLowering &tli,
240                  const SmallVector<unsigned, 4> &regs, 
241                  const SmallVector<MVT, 4> &regvts,
242                  const SmallVector<MVT, 4> &valuevts)
243       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
244     RegsForValue(const TargetLowering &tli,
245                  unsigned Reg, const Type *Ty) : TLI(&tli) {
246       ComputeValueVTs(tli, Ty, ValueVTs);
247
248       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
249         MVT ValueVT = ValueVTs[Value];
250         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
251         MVT RegisterVT = TLI->getRegisterType(ValueVT);
252         for (unsigned i = 0; i != NumRegs; ++i)
253           Regs.push_back(Reg + i);
254         RegVTs.push_back(RegisterVT);
255         Reg += NumRegs;
256       }
257     }
258     
259     /// append - Add the specified values to this one.
260     void append(const RegsForValue &RHS) {
261       TLI = RHS.TLI;
262       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
263       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
264       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
265     }
266     
267     
268     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
269     /// this value and returns the result as a ValueVTs value.  This uses 
270     /// Chain/Flag as the input and updates them for the output Chain/Flag.
271     /// If the Flag pointer is NULL, no flag is used.
272     SDValue getCopyFromRegs(SelectionDAG &DAG,
273                               SDValue &Chain, SDValue *Flag) const;
274
275     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
276     /// specified value into the registers specified by this object.  This uses 
277     /// Chain/Flag as the input and updates them for the output Chain/Flag.
278     /// If the Flag pointer is NULL, no flag is used.
279     void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
280                        SDValue &Chain, SDValue *Flag) const;
281     
282     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
283     /// operand list.  This adds the code marker and includes the number of 
284     /// values added into it.
285     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
286                               std::vector<SDValue> &Ops) const;
287   };
288 }
289
290 namespace llvm {
291   //===--------------------------------------------------------------------===//
292   /// createDefaultScheduler - This creates an instruction scheduler appropriate
293   /// for the target.
294   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
295                                       SelectionDAG *DAG,
296                                       MachineBasicBlock *BB,
297                                       bool Fast) {
298     TargetLowering &TLI = IS->getTargetLowering();
299     
300     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
301       return createTDListDAGScheduler(IS, DAG, BB, Fast);
302     } else {
303       assert(TLI.getSchedulingPreference() ==
304            TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
305       return createBURRListDAGScheduler(IS, DAG, BB, Fast);
306     }
307   }
308
309
310   //===--------------------------------------------------------------------===//
311   /// FunctionLoweringInfo - This contains information that is global to a
312   /// function that is used when lowering a region of the function.
313   class FunctionLoweringInfo {
314   public:
315     TargetLowering &TLI;
316     Function *Fn;
317     MachineFunction *MF;
318     MachineRegisterInfo *RegInfo;
319
320     explicit FunctionLoweringInfo(TargetLowering &TLI);
321
322     /// set - Initialize this FunctionLoweringInfo with the given Function
323     /// and its associated MachineFunction.
324     ///
325     void set(Function &Fn, MachineFunction &MF);
326
327     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
328     DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
329
330     /// ValueMap - Since we emit code for the function a basic block at a time,
331     /// we must remember which virtual registers hold the values for
332     /// cross-basic-block values.
333     DenseMap<const Value*, unsigned> ValueMap;
334
335     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
336     /// the entry block.  This allows the allocas to be efficiently referenced
337     /// anywhere in the function.
338     DenseMap<const AllocaInst*, int> StaticAllocaMap;
339
340 #ifndef NDEBUG
341     SmallSet<Instruction*, 8> CatchInfoLost;
342     SmallSet<Instruction*, 8> CatchInfoFound;
343 #endif
344
345     unsigned MakeReg(MVT VT) {
346       return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
347     }
348     
349     /// isExportedInst - Return true if the specified value is an instruction
350     /// exported from its block.
351     bool isExportedInst(const Value *V) {
352       return ValueMap.count(V);
353     }
354
355     unsigned CreateRegForValue(const Value *V);
356     
357     unsigned InitializeRegForValue(const Value *V) {
358       unsigned &R = ValueMap[V];
359       assert(R == 0 && "Already initialized this value register!");
360       return R = CreateRegForValue(V);
361     }
362     
363     struct LiveOutInfo {
364       unsigned NumSignBits;
365       APInt KnownOne, KnownZero;
366       LiveOutInfo() : NumSignBits(0) {}
367     };
368     
369     /// LiveOutRegInfo - Information about live out vregs, indexed by their
370     /// register number offset by 'FirstVirtualRegister'.
371     std::vector<LiveOutInfo> LiveOutRegInfo;
372
373     /// clear - Clear out all the function-specific state. This returns this
374     /// FunctionLoweringInfo to an empty state, ready to be used for a
375     /// different function.
376     void clear() {
377       MBBMap.clear();
378       ValueMap.clear();
379       StaticAllocaMap.clear();
380 #ifndef NDEBUG
381       CatchInfoLost.clear();
382       CatchInfoFound.clear();
383 #endif
384       LiveOutRegInfo.clear();
385     }
386   };
387 }
388
389 /// isSelector - Return true if this instruction is a call to the
390 /// eh.selector intrinsic.
391 static bool isSelector(Instruction *I) {
392   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
393     return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
394             II->getIntrinsicID() == Intrinsic::eh_selector_i64);
395   return false;
396 }
397
398 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
399 /// PHI nodes or outside of the basic block that defines it, or used by a 
400 /// switch or atomic instruction, which may expand to multiple basic blocks.
401 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
402   if (isa<PHINode>(I)) return true;
403   BasicBlock *BB = I->getParent();
404   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
405     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
406         // FIXME: Remove switchinst special case.
407         isa<SwitchInst>(*UI))
408       return true;
409   return false;
410 }
411
412 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
413 /// entry block, return true.  This includes arguments used by switches, since
414 /// the switch may expand into multiple basic blocks.
415 static bool isOnlyUsedInEntryBlock(Argument *A) {
416   // With FastISel active, we may be splitting blocks, so force creation
417   // of virtual registers for all non-dead arguments.
418   if (EnableFastISel)
419     return A->use_empty();
420
421   BasicBlock *Entry = A->getParent()->begin();
422   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
423     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
424       return false;  // Use not in entry block.
425   return true;
426 }
427
428 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
429   : TLI(tli) {
430 }
431
432 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf) {
433    Fn = &fn;
434    MF = &mf;
435    RegInfo = &MF->getRegInfo();
436
437   // Create a vreg for each argument register that is not dead and is used
438   // outside of the entry block for the function.
439   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
440        AI != E; ++AI)
441     if (!isOnlyUsedInEntryBlock(AI))
442       InitializeRegForValue(AI);
443
444   // Initialize the mapping of values to registers.  This is only set up for
445   // instruction values that are used outside of the block that defines
446   // them.
447   Function::iterator BB = Fn->begin(), EB = Fn->end();
448   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
449     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
450       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
451         const Type *Ty = AI->getAllocatedType();
452         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
453         unsigned Align = 
454           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
455                    AI->getAlignment());
456
457         TySize *= CUI->getZExtValue();   // Get total allocated size.
458         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
459         StaticAllocaMap[AI] =
460           MF->getFrameInfo()->CreateStackObject(TySize, Align);
461       }
462
463   for (; BB != EB; ++BB)
464     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
465       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
466         if (!isa<AllocaInst>(I) ||
467             !StaticAllocaMap.count(cast<AllocaInst>(I)))
468           InitializeRegForValue(I);
469
470   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
471   // also creates the initial PHI MachineInstrs, though none of the input
472   // operands are populated.
473   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
474     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
475     MBBMap[BB] = MBB;
476     MF->push_back(MBB);
477
478     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
479     // appropriate.
480     PHINode *PN;
481     for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
482       if (PN->use_empty()) continue;
483       
484       unsigned PHIReg = ValueMap[PN];
485       assert(PHIReg && "PHI node does not have an assigned virtual register!");
486
487       SmallVector<MVT, 4> ValueVTs;
488       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
489       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
490         MVT VT = ValueVTs[vti];
491         unsigned NumRegisters = TLI.getNumRegisters(VT);
492         const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
493         for (unsigned i = 0; i != NumRegisters; ++i)
494           BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
495         PHIReg += NumRegisters;
496       }
497     }
498   }
499 }
500
501 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
502 /// the correctly promoted or expanded types.  Assign these registers
503 /// consecutive vreg numbers and return the first assigned number.
504 ///
505 /// In the case that the given value has struct or array type, this function
506 /// will assign registers for each member or element.
507 ///
508 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
509   SmallVector<MVT, 4> ValueVTs;
510   ComputeValueVTs(TLI, V->getType(), ValueVTs);
511
512   unsigned FirstReg = 0;
513   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
514     MVT ValueVT = ValueVTs[Value];
515     MVT RegisterVT = TLI.getRegisterType(ValueVT);
516
517     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
518     for (unsigned i = 0; i != NumRegs; ++i) {
519       unsigned R = MakeReg(RegisterVT);
520       if (!FirstReg) FirstReg = R;
521     }
522   }
523   return FirstReg;
524 }
525
526 namespace {
527
528 /// CaseBlock - This structure is used to communicate between SDLowering and
529 /// SDISel for the code generation of additional basic blocks needed by multi-
530 /// case switch statements.
531 struct CaseBlock {
532   CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
533             MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
534             MachineBasicBlock *me)
535     : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
536       TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
537   // CC - the condition code to use for the case block's setcc node
538   ISD::CondCode CC;
539   // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
540   // Emit by default LHS op RHS. MHS is used for range comparisons:
541   // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
542   Value *CmpLHS, *CmpMHS, *CmpRHS;
543   // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
544   MachineBasicBlock *TrueBB, *FalseBB;
545   // ThisBB - the block into which to emit the code for the setcc and branches
546   MachineBasicBlock *ThisBB;
547 };
548 struct JumpTable {
549   JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
550             MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
551   
552   /// Reg - the virtual register containing the index of the jump table entry
553   //. to jump to.
554   unsigned Reg;
555   /// JTI - the JumpTableIndex for this jump table in the function.
556   unsigned JTI;
557   /// MBB - the MBB into which to emit the code for the indirect jump.
558   MachineBasicBlock *MBB;
559   /// Default - the MBB of the default bb, which is a successor of the range
560   /// check MBB.  This is when updating PHI nodes in successors.
561   MachineBasicBlock *Default;
562 };
563 struct JumpTableHeader {
564   JumpTableHeader(uint64_t F, uint64_t L, Value* SV, MachineBasicBlock* H,
565                   bool E = false):
566     First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
567   uint64_t First;
568   uint64_t Last;
569   Value *SValue;
570   MachineBasicBlock *HeaderBB;
571   bool Emitted;
572 };
573 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
574
575 struct BitTestCase {
576   BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
577     Mask(M), ThisBB(T), TargetBB(Tr) { }
578   uint64_t Mask;
579   MachineBasicBlock* ThisBB;
580   MachineBasicBlock* TargetBB;
581 };
582
583 typedef SmallVector<BitTestCase, 3> BitTestInfo;
584
585 struct BitTestBlock {
586   BitTestBlock(uint64_t F, uint64_t R, Value* SV,
587                unsigned Rg, bool E,
588                MachineBasicBlock* P, MachineBasicBlock* D,
589                const BitTestInfo& C):
590     First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
591     Parent(P), Default(D), Cases(C) { }
592   uint64_t First;
593   uint64_t Range;
594   Value  *SValue;
595   unsigned Reg;
596   bool Emitted;
597   MachineBasicBlock *Parent;
598   MachineBasicBlock *Default;
599   BitTestInfo Cases;
600 };
601
602 } // end anonymous namespace
603
604 //===----------------------------------------------------------------------===//
605 /// SelectionDAGLowering - This is the common target-independent lowering
606 /// implementation that is parameterized by a TargetLowering object.
607 /// Also, targets can overload any lowering method.
608 ///
609 namespace llvm {
610 class SelectionDAGLowering {
611   MachineBasicBlock *CurMBB;
612
613   DenseMap<const Value*, SDValue> NodeMap;
614
615   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
616   /// them up and then emit token factor nodes when possible.  This allows us to
617   /// get simple disambiguation between loads without worrying about alias
618   /// analysis.
619   SmallVector<SDValue, 8> PendingLoads;
620
621   /// PendingExports - CopyToReg nodes that copy values to virtual registers
622   /// for export to other blocks need to be emitted before any terminator
623   /// instruction, but they have no other ordering requirements. We bunch them
624   /// up and the emit a single tokenfactor for them just before terminator
625   /// instructions.
626   SmallVector<SDValue, 8> PendingExports;
627
628   /// Case - A struct to record the Value for a switch case, and the
629   /// case's target basic block.
630   struct Case {
631     Constant* Low;
632     Constant* High;
633     MachineBasicBlock* BB;
634
635     Case() : Low(0), High(0), BB(0) { }
636     Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
637       Low(low), High(high), BB(bb) { }
638     uint64_t size() const {
639       uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
640       uint64_t rLow  = cast<ConstantInt>(Low)->getSExtValue();
641       return (rHigh - rLow + 1ULL);
642     }
643   };
644
645   struct CaseBits {
646     uint64_t Mask;
647     MachineBasicBlock* BB;
648     unsigned Bits;
649
650     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
651       Mask(mask), BB(bb), Bits(bits) { }
652   };
653
654   typedef std::vector<Case>           CaseVector;
655   typedef std::vector<CaseBits>       CaseBitsVector;
656   typedef CaseVector::iterator        CaseItr;
657   typedef std::pair<CaseItr, CaseItr> CaseRange;
658
659   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
660   /// of conditional branches.
661   struct CaseRec {
662     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
663     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
664
665     /// CaseBB - The MBB in which to emit the compare and branch
666     MachineBasicBlock *CaseBB;
667     /// LT, GE - If nonzero, we know the current case value must be less-than or
668     /// greater-than-or-equal-to these Constants.
669     Constant *LT;
670     Constant *GE;
671     /// Range - A pair of iterators representing the range of case values to be
672     /// processed at this point in the binary search tree.
673     CaseRange Range;
674   };
675
676   typedef std::vector<CaseRec> CaseRecVector;
677
678   /// The comparison function for sorting the switch case values in the vector.
679   /// WARNING: Case ranges should be disjoint!
680   struct CaseCmp {
681     bool operator () (const Case& C1, const Case& C2) {
682       assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
683       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
684       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
685       return CI1->getValue().slt(CI2->getValue());
686     }
687   };
688
689   struct CaseBitsCmp {
690     bool operator () (const CaseBits& C1, const CaseBits& C2) {
691       return C1.Bits > C2.Bits;
692     }
693   };
694
695   unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
696   
697 public:
698   // TLI - This is information that describes the available target features we
699   // need for lowering.  This indicates when operations are unavailable,
700   // implemented with a libcall, etc.
701   TargetLowering &TLI;
702   SelectionDAG &DAG;
703   const TargetData *TD;
704   AliasAnalysis *AA;
705
706   /// SwitchCases - Vector of CaseBlock structures used to communicate
707   /// SwitchInst code generation information.
708   std::vector<CaseBlock> SwitchCases;
709   /// JTCases - Vector of JumpTable structures used to communicate
710   /// SwitchInst code generation information.
711   std::vector<JumpTableBlock> JTCases;
712   /// BitTestCases - Vector of BitTestBlock structures used to communicate
713   /// SwitchInst code generation information.
714   std::vector<BitTestBlock> BitTestCases;
715   
716   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
717
718   // Emit PHI-node-operand constants only once even if used by multiple
719   // PHI nodes.
720   DenseMap<Constant*, unsigned> ConstantsOut;
721
722   /// FuncInfo - Information about the function as a whole.
723   ///
724   FunctionLoweringInfo &FuncInfo;
725   
726   /// GFI - Garbage collection metadata for the function.
727   GCFunctionInfo *GFI;
728
729   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
730                        FunctionLoweringInfo &funcinfo)
731     : TLI(tli), DAG(dag), FuncInfo(funcinfo) {
732   }
733
734   void init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
735     AA = &aa;
736     GFI = gfi;
737     TD = DAG.getTarget().getTargetData();
738   }
739
740   /// clear - Clear out the curret SelectionDAG and the associated
741   /// state and prepare this SelectionDAGLowering object to be used
742   /// for a new block. This doesn't clear out information about
743   /// additional blocks that are needed to complete switch lowering
744   /// or PHI node updating; that information is cleared out as it is
745   /// consumed.
746   void clear() {
747     NodeMap.clear();
748     PendingLoads.clear();
749     PendingExports.clear();
750     DAG.clear();
751   }
752
753   /// getRoot - Return the current virtual root of the Selection DAG,
754   /// flushing any PendingLoad items. This must be done before emitting
755   /// a store or any other node that may need to be ordered after any
756   /// prior load instructions.
757   ///
758   SDValue getRoot() {
759     if (PendingLoads.empty())
760       return DAG.getRoot();
761
762     if (PendingLoads.size() == 1) {
763       SDValue Root = PendingLoads[0];
764       DAG.setRoot(Root);
765       PendingLoads.clear();
766       return Root;
767     }
768
769     // Otherwise, we have to make a token factor node.
770     SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
771                                  &PendingLoads[0], PendingLoads.size());
772     PendingLoads.clear();
773     DAG.setRoot(Root);
774     return Root;
775   }
776
777   /// getControlRoot - Similar to getRoot, but instead of flushing all the
778   /// PendingLoad items, flush all the PendingExports items. It is necessary
779   /// to do this before emitting a terminator instruction.
780   ///
781   SDValue getControlRoot() {
782     SDValue Root = DAG.getRoot();
783
784     if (PendingExports.empty())
785       return Root;
786
787     // Turn all of the CopyToReg chains into one factored node.
788     if (Root.getOpcode() != ISD::EntryToken) {
789       unsigned i = 0, e = PendingExports.size();
790       for (; i != e; ++i) {
791         assert(PendingExports[i].Val->getNumOperands() > 1);
792         if (PendingExports[i].Val->getOperand(0) == Root)
793           break;  // Don't add the root if we already indirectly depend on it.
794       }
795         
796       if (i == e)
797         PendingExports.push_back(Root);
798     }
799
800     Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
801                        &PendingExports[0],
802                        PendingExports.size());
803     PendingExports.clear();
804     DAG.setRoot(Root);
805     return Root;
806   }
807
808   void CopyValueToVirtualRegister(Value *V, unsigned Reg);
809
810   void visit(Instruction &I) { visit(I.getOpcode(), I); }
811
812   void visit(unsigned Opcode, User &I) {
813     // Note: this doesn't use InstVisitor, because it has to work with
814     // ConstantExpr's in addition to instructions.
815     switch (Opcode) {
816     default: assert(0 && "Unknown instruction type encountered!");
817              abort();
818       // Build the switch statement using the Instruction.def file.
819 #define HANDLE_INST(NUM, OPCODE, CLASS) \
820     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
821 #include "llvm/Instruction.def"
822     }
823   }
824
825   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
826
827   SDValue getValue(const Value *V);
828
829   void setValue(const Value *V, SDValue NewN) {
830     SDValue &N = NodeMap[V];
831     assert(N.Val == 0 && "Already set a value for this node!");
832     N = NewN;
833   }
834   
835   void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
836                             std::set<unsigned> &OutputRegs, 
837                             std::set<unsigned> &InputRegs);
838
839   void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
840                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
841                             unsigned Opc);
842   bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
843   void ExportFromCurrentBlock(Value *V);
844   void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
845                    MachineBasicBlock *LandingPad = NULL);
846
847   // Terminator instructions.
848   void visitRet(ReturnInst &I);
849   void visitBr(BranchInst &I);
850   void visitSwitch(SwitchInst &I);
851   void visitUnreachable(UnreachableInst &I) { /* noop */ }
852
853   // Helpers for visitSwitch
854   bool handleSmallSwitchRange(CaseRec& CR,
855                               CaseRecVector& WorkList,
856                               Value* SV,
857                               MachineBasicBlock* Default);
858   bool handleJTSwitchCase(CaseRec& CR,
859                           CaseRecVector& WorkList,
860                           Value* SV,
861                           MachineBasicBlock* Default);
862   bool handleBTSplitSwitchCase(CaseRec& CR,
863                                CaseRecVector& WorkList,
864                                Value* SV,
865                                MachineBasicBlock* Default);
866   bool handleBitTestsSwitchCase(CaseRec& CR,
867                                 CaseRecVector& WorkList,
868                                 Value* SV,
869                                 MachineBasicBlock* Default);  
870   void visitSwitchCase(CaseBlock &CB);
871   void visitBitTestHeader(BitTestBlock &B);
872   void visitBitTestCase(MachineBasicBlock* NextMBB,
873                         unsigned Reg,
874                         BitTestCase &B);
875   void visitJumpTable(JumpTable &JT);
876   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
877   
878   // These all get lowered before this pass.
879   void visitInvoke(InvokeInst &I);
880   void visitUnwind(UnwindInst &I);
881
882   void visitBinary(User &I, unsigned OpCode);
883   void visitShift(User &I, unsigned Opcode);
884   void visitAdd(User &I) { 
885     if (I.getType()->isFPOrFPVector())
886       visitBinary(I, ISD::FADD);
887     else
888       visitBinary(I, ISD::ADD);
889   }
890   void visitSub(User &I);
891   void visitMul(User &I) {
892     if (I.getType()->isFPOrFPVector())
893       visitBinary(I, ISD::FMUL);
894     else
895       visitBinary(I, ISD::MUL);
896   }
897   void visitURem(User &I) { visitBinary(I, ISD::UREM); }
898   void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
899   void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
900   void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
901   void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
902   void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
903   void visitAnd (User &I) { visitBinary(I, ISD::AND); }
904   void visitOr  (User &I) { visitBinary(I, ISD::OR); }
905   void visitXor (User &I) { visitBinary(I, ISD::XOR); }
906   void visitShl (User &I) { visitShift(I, ISD::SHL); }
907   void visitLShr(User &I) { visitShift(I, ISD::SRL); }
908   void visitAShr(User &I) { visitShift(I, ISD::SRA); }
909   void visitICmp(User &I);
910   void visitFCmp(User &I);
911   void visitVICmp(User &I);
912   void visitVFCmp(User &I);
913   // Visit the conversion instructions
914   void visitTrunc(User &I);
915   void visitZExt(User &I);
916   void visitSExt(User &I);
917   void visitFPTrunc(User &I);
918   void visitFPExt(User &I);
919   void visitFPToUI(User &I);
920   void visitFPToSI(User &I);
921   void visitUIToFP(User &I);
922   void visitSIToFP(User &I);
923   void visitPtrToInt(User &I);
924   void visitIntToPtr(User &I);
925   void visitBitCast(User &I);
926
927   void visitExtractElement(User &I);
928   void visitInsertElement(User &I);
929   void visitShuffleVector(User &I);
930
931   void visitExtractValue(ExtractValueInst &I);
932   void visitInsertValue(InsertValueInst &I);
933
934   void visitGetElementPtr(User &I);
935   void visitSelect(User &I);
936
937   void visitMalloc(MallocInst &I);
938   void visitFree(FreeInst &I);
939   void visitAlloca(AllocaInst &I);
940   void visitLoad(LoadInst &I);
941   void visitStore(StoreInst &I);
942   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
943   void visitCall(CallInst &I);
944   void visitInlineAsm(CallSite CS);
945   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
946   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
947
948   void visitVAStart(CallInst &I);
949   void visitVAArg(VAArgInst &I);
950   void visitVAEnd(CallInst &I);
951   void visitVACopy(CallInst &I);
952
953   void visitUserOp1(Instruction &I) {
954     assert(0 && "UserOp1 should not exist at instruction selection time!");
955     abort();
956   }
957   void visitUserOp2(Instruction &I) {
958     assert(0 && "UserOp2 should not exist at instruction selection time!");
959     abort();
960   }
961   
962 private:
963   inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
964
965 };
966 } // end namespace llvm
967
968
969 /// getCopyFromParts - Create a value that contains the specified legal parts
970 /// combined into the value they represent.  If the parts combine to a type
971 /// larger then ValueVT then AssertOp can be used to specify whether the extra
972 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
973 /// (ISD::AssertSext).
974 static SDValue getCopyFromParts(SelectionDAG &DAG,
975                                   const SDValue *Parts,
976                                   unsigned NumParts,
977                                   MVT PartVT,
978                                   MVT ValueVT,
979                                   ISD::NodeType AssertOp = ISD::DELETED_NODE) {
980   assert(NumParts > 0 && "No parts to assemble!");
981   TargetLowering &TLI = DAG.getTargetLoweringInfo();
982   SDValue Val = Parts[0];
983
984   if (NumParts > 1) {
985     // Assemble the value from multiple parts.
986     if (!ValueVT.isVector()) {
987       unsigned PartBits = PartVT.getSizeInBits();
988       unsigned ValueBits = ValueVT.getSizeInBits();
989
990       // Assemble the power of 2 part.
991       unsigned RoundParts = NumParts & (NumParts - 1) ?
992         1 << Log2_32(NumParts) : NumParts;
993       unsigned RoundBits = PartBits * RoundParts;
994       MVT RoundVT = RoundBits == ValueBits ?
995         ValueVT : MVT::getIntegerVT(RoundBits);
996       SDValue Lo, Hi;
997
998       if (RoundParts > 2) {
999         MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
1000         Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
1001         Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
1002                               PartVT, HalfVT);
1003       } else {
1004         Lo = Parts[0];
1005         Hi = Parts[1];
1006       }
1007       if (TLI.isBigEndian())
1008         std::swap(Lo, Hi);
1009       Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
1010
1011       if (RoundParts < NumParts) {
1012         // Assemble the trailing non-power-of-2 part.
1013         unsigned OddParts = NumParts - RoundParts;
1014         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
1015         Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
1016
1017         // Combine the round and odd parts.
1018         Lo = Val;
1019         if (TLI.isBigEndian())
1020           std::swap(Lo, Hi);
1021         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
1022         Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
1023         Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
1024                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
1025                                          TLI.getShiftAmountTy()));
1026         Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
1027         Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
1028       }
1029     } else {
1030       // Handle a multi-element vector.
1031       MVT IntermediateVT, RegisterVT;
1032       unsigned NumIntermediates;
1033       unsigned NumRegs =
1034         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1035                                    RegisterVT);
1036       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1037       NumParts = NumRegs; // Silence a compiler warning.
1038       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1039       assert(RegisterVT == Parts[0].getValueType() &&
1040              "Part type doesn't match part!");
1041
1042       // Assemble the parts into intermediate operands.
1043       SmallVector<SDValue, 8> Ops(NumIntermediates);
1044       if (NumIntermediates == NumParts) {
1045         // If the register was not expanded, truncate or copy the value,
1046         // as appropriate.
1047         for (unsigned i = 0; i != NumParts; ++i)
1048           Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
1049                                     PartVT, IntermediateVT);
1050       } else if (NumParts > 0) {
1051         // If the intermediate type was expanded, build the intermediate operands
1052         // from the parts.
1053         assert(NumParts % NumIntermediates == 0 &&
1054                "Must expand into a divisible number of parts!");
1055         unsigned Factor = NumParts / NumIntermediates;
1056         for (unsigned i = 0; i != NumIntermediates; ++i)
1057           Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
1058                                     PartVT, IntermediateVT);
1059       }
1060
1061       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
1062       // operands.
1063       Val = DAG.getNode(IntermediateVT.isVector() ?
1064                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
1065                         ValueVT, &Ops[0], NumIntermediates);
1066     }
1067   }
1068
1069   // There is now one part, held in Val.  Correct it to match ValueVT.
1070   PartVT = Val.getValueType();
1071
1072   if (PartVT == ValueVT)
1073     return Val;
1074
1075   if (PartVT.isVector()) {
1076     assert(ValueVT.isVector() && "Unknown vector conversion!");
1077     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
1078   }
1079
1080   if (ValueVT.isVector()) {
1081     assert(ValueVT.getVectorElementType() == PartVT &&
1082            ValueVT.getVectorNumElements() == 1 &&
1083            "Only trivial scalar-to-vector conversions should get here!");
1084     return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
1085   }
1086
1087   if (PartVT.isInteger() &&
1088       ValueVT.isInteger()) {
1089     if (ValueVT.bitsLT(PartVT)) {
1090       // For a truncate, see if we have any information to
1091       // indicate whether the truncated bits will always be
1092       // zero or sign-extension.
1093       if (AssertOp != ISD::DELETED_NODE)
1094         Val = DAG.getNode(AssertOp, PartVT, Val,
1095                           DAG.getValueType(ValueVT));
1096       return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1097     } else {
1098       return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1099     }
1100   }
1101
1102   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
1103     if (ValueVT.bitsLT(Val.getValueType()))
1104       // FP_ROUND's are always exact here.
1105       return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
1106                          DAG.getIntPtrConstant(1));
1107     return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
1108   }
1109
1110   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
1111     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
1112
1113   assert(0 && "Unknown mismatch!");
1114   return SDValue();
1115 }
1116
1117 /// getCopyToParts - Create a series of nodes that contain the specified value
1118 /// split into legal parts.  If the parts contain more bits than Val, then, for
1119 /// integers, ExtendKind can be used to specify how to generate the extra bits.
1120 static void getCopyToParts(SelectionDAG &DAG,
1121                            SDValue Val,
1122                            SDValue *Parts,
1123                            unsigned NumParts,
1124                            MVT PartVT,
1125                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
1126   TargetLowering &TLI = DAG.getTargetLoweringInfo();
1127   MVT PtrVT = TLI.getPointerTy();
1128   MVT ValueVT = Val.getValueType();
1129   unsigned PartBits = PartVT.getSizeInBits();
1130   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
1131
1132   if (!NumParts)
1133     return;
1134
1135   if (!ValueVT.isVector()) {
1136     if (PartVT == ValueVT) {
1137       assert(NumParts == 1 && "No-op copy with multiple parts!");
1138       Parts[0] = Val;
1139       return;
1140     }
1141
1142     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
1143       // If the parts cover more bits than the value has, promote the value.
1144       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
1145         assert(NumParts == 1 && "Do not know what to promote to!");
1146         Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
1147       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1148         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1149         Val = DAG.getNode(ExtendKind, ValueVT, Val);
1150       } else {
1151         assert(0 && "Unknown mismatch!");
1152       }
1153     } else if (PartBits == ValueVT.getSizeInBits()) {
1154       // Different types of the same size.
1155       assert(NumParts == 1 && PartVT != ValueVT);
1156       Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1157     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
1158       // If the parts cover less bits than value has, truncate the value.
1159       if (PartVT.isInteger() && ValueVT.isInteger()) {
1160         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1161         Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1162       } else {
1163         assert(0 && "Unknown mismatch!");
1164       }
1165     }
1166
1167     // The value may have changed - recompute ValueVT.
1168     ValueVT = Val.getValueType();
1169     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
1170            "Failed to tile the value with PartVT!");
1171
1172     if (NumParts == 1) {
1173       assert(PartVT == ValueVT && "Type conversion failed!");
1174       Parts[0] = Val;
1175       return;
1176     }
1177
1178     // Expand the value into multiple parts.
1179     if (NumParts & (NumParts - 1)) {
1180       // The number of parts is not a power of 2.  Split off and copy the tail.
1181       assert(PartVT.isInteger() && ValueVT.isInteger() &&
1182              "Do not know what to expand to!");
1183       unsigned RoundParts = 1 << Log2_32(NumParts);
1184       unsigned RoundBits = RoundParts * PartBits;
1185       unsigned OddParts = NumParts - RoundParts;
1186       SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1187                                      DAG.getConstant(RoundBits,
1188                                                      TLI.getShiftAmountTy()));
1189       getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1190       if (TLI.isBigEndian())
1191         // The odd parts were reversed by getCopyToParts - unreverse them.
1192         std::reverse(Parts + RoundParts, Parts + NumParts);
1193       NumParts = RoundParts;
1194       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1195       Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1196     }
1197
1198     // The number of parts is a power of 2.  Repeatedly bisect the value using
1199     // EXTRACT_ELEMENT.
1200     Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1201                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
1202                            Val);
1203     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1204       for (unsigned i = 0; i < NumParts; i += StepSize) {
1205         unsigned ThisBits = StepSize * PartBits / 2;
1206         MVT ThisVT = MVT::getIntegerVT (ThisBits);
1207         SDValue &Part0 = Parts[i];
1208         SDValue &Part1 = Parts[i+StepSize/2];
1209
1210         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1211                             DAG.getConstant(1, PtrVT));
1212         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1213                             DAG.getConstant(0, PtrVT));
1214
1215         if (ThisBits == PartBits && ThisVT != PartVT) {
1216           Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1217           Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1218         }
1219       }
1220     }
1221
1222     if (TLI.isBigEndian())
1223       std::reverse(Parts, Parts + NumParts);
1224
1225     return;
1226   }
1227
1228   // Vector ValueVT.
1229   if (NumParts == 1) {
1230     if (PartVT != ValueVT) {
1231       if (PartVT.isVector()) {
1232         Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1233       } else {
1234         assert(ValueVT.getVectorElementType() == PartVT &&
1235                ValueVT.getVectorNumElements() == 1 &&
1236                "Only trivial vector-to-scalar conversions should get here!");
1237         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1238                           DAG.getConstant(0, PtrVT));
1239       }
1240     }
1241
1242     Parts[0] = Val;
1243     return;
1244   }
1245
1246   // Handle a multi-element vector.
1247   MVT IntermediateVT, RegisterVT;
1248   unsigned NumIntermediates;
1249   unsigned NumRegs =
1250     DAG.getTargetLoweringInfo()
1251       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1252                               RegisterVT);
1253   unsigned NumElements = ValueVT.getVectorNumElements();
1254
1255   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1256   NumParts = NumRegs; // Silence a compiler warning.
1257   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1258
1259   // Split the vector into intermediate operands.
1260   SmallVector<SDValue, 8> Ops(NumIntermediates);
1261   for (unsigned i = 0; i != NumIntermediates; ++i)
1262     if (IntermediateVT.isVector())
1263       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1264                            IntermediateVT, Val,
1265                            DAG.getConstant(i * (NumElements / NumIntermediates),
1266                                            PtrVT));
1267     else
1268       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1269                            IntermediateVT, Val, 
1270                            DAG.getConstant(i, PtrVT));
1271
1272   // Split the intermediate operands into legal parts.
1273   if (NumParts == NumIntermediates) {
1274     // If the register was not expanded, promote or copy the value,
1275     // as appropriate.
1276     for (unsigned i = 0; i != NumParts; ++i)
1277       getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1278   } else if (NumParts > 0) {
1279     // If the intermediate type was expanded, split each the value into
1280     // legal parts.
1281     assert(NumParts % NumIntermediates == 0 &&
1282            "Must expand into a divisible number of parts!");
1283     unsigned Factor = NumParts / NumIntermediates;
1284     for (unsigned i = 0; i != NumIntermediates; ++i)
1285       getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1286   }
1287 }
1288
1289
1290 SDValue SelectionDAGLowering::getValue(const Value *V) {
1291   SDValue &N = NodeMap[V];
1292   if (N.Val) return N;
1293   
1294   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1295     MVT VT = TLI.getValueType(V->getType(), true);
1296     
1297     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1298       return N = DAG.getConstant(CI->getValue(), VT);
1299
1300     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1301       return N = DAG.getGlobalAddress(GV, VT);
1302     
1303     if (isa<ConstantPointerNull>(C))
1304       return N = DAG.getConstant(0, TLI.getPointerTy());
1305     
1306     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1307       return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1308     
1309     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1310         !V->getType()->isAggregateType())
1311       return N = DAG.getNode(ISD::UNDEF, VT);
1312
1313     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1314       visit(CE->getOpcode(), *CE);
1315       SDValue N1 = NodeMap[V];
1316       assert(N1.Val && "visit didn't populate the ValueMap!");
1317       return N1;
1318     }
1319     
1320     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1321       SmallVector<SDValue, 4> Constants;
1322       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1323            OI != OE; ++OI) {
1324         SDNode *Val = getValue(*OI).Val;
1325         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1326           Constants.push_back(SDValue(Val, i));
1327       }
1328       return DAG.getMergeValues(&Constants[0], Constants.size());
1329     }
1330
1331     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
1332       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1333              "Unknown struct or array constant!");
1334
1335       SmallVector<MVT, 4> ValueVTs;
1336       ComputeValueVTs(TLI, C->getType(), ValueVTs);
1337       unsigned NumElts = ValueVTs.size();
1338       if (NumElts == 0)
1339         return SDValue(); // empty struct
1340       SmallVector<SDValue, 4> Constants(NumElts);
1341       for (unsigned i = 0; i != NumElts; ++i) {
1342         MVT EltVT = ValueVTs[i];
1343         if (isa<UndefValue>(C))
1344           Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1345         else if (EltVT.isFloatingPoint())
1346           Constants[i] = DAG.getConstantFP(0, EltVT);
1347         else
1348           Constants[i] = DAG.getConstant(0, EltVT);
1349       }
1350       return DAG.getMergeValues(&Constants[0], NumElts);
1351     }
1352
1353     const VectorType *VecTy = cast<VectorType>(V->getType());
1354     unsigned NumElements = VecTy->getNumElements();
1355     
1356     // Now that we know the number and type of the elements, get that number of
1357     // elements into the Ops array based on what kind of constant it is.
1358     SmallVector<SDValue, 16> Ops;
1359     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1360       for (unsigned i = 0; i != NumElements; ++i)
1361         Ops.push_back(getValue(CP->getOperand(i)));
1362     } else {
1363       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1364              "Unknown vector constant!");
1365       MVT EltVT = TLI.getValueType(VecTy->getElementType());
1366
1367       SDValue Op;
1368       if (isa<UndefValue>(C))
1369         Op = DAG.getNode(ISD::UNDEF, EltVT);
1370       else if (EltVT.isFloatingPoint())
1371         Op = DAG.getConstantFP(0, EltVT);
1372       else
1373         Op = DAG.getConstant(0, EltVT);
1374       Ops.assign(NumElements, Op);
1375     }
1376     
1377     // Create a BUILD_VECTOR node.
1378     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1379   }
1380       
1381   // If this is a static alloca, generate it as the frameindex instead of
1382   // computation.
1383   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1384     DenseMap<const AllocaInst*, int>::iterator SI =
1385       FuncInfo.StaticAllocaMap.find(AI);
1386     if (SI != FuncInfo.StaticAllocaMap.end())
1387       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1388   }
1389       
1390   unsigned InReg = FuncInfo.ValueMap[V];
1391   assert(InReg && "Value not in map!");
1392   
1393   RegsForValue RFV(TLI, InReg, V->getType());
1394   SDValue Chain = DAG.getEntryNode();
1395   return RFV.getCopyFromRegs(DAG, Chain, NULL);
1396 }
1397
1398
1399 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1400   if (I.getNumOperands() == 0) {
1401     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1402     return;
1403   }
1404   
1405   SmallVector<SDValue, 8> NewValues;
1406   NewValues.push_back(getControlRoot());
1407   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {  
1408     SDValue RetOp = getValue(I.getOperand(i));
1409
1410     SmallVector<MVT, 4> ValueVTs;
1411     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1412     for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1413       MVT VT = ValueVTs[j];
1414
1415       // FIXME: C calling convention requires the return type to be promoted to
1416       // at least 32-bit. But this is not necessary for non-C calling conventions.
1417       if (VT.isInteger()) {
1418         MVT MinVT = TLI.getRegisterType(MVT::i32);
1419         if (VT.bitsLT(MinVT))
1420           VT = MinVT;
1421       }
1422
1423       unsigned NumParts = TLI.getNumRegisters(VT);
1424       MVT PartVT = TLI.getRegisterType(VT);
1425       SmallVector<SDValue, 4> Parts(NumParts);
1426       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1427   
1428       const Function *F = I.getParent()->getParent();
1429       if (F->paramHasAttr(0, ParamAttr::SExt))
1430         ExtendKind = ISD::SIGN_EXTEND;
1431       else if (F->paramHasAttr(0, ParamAttr::ZExt))
1432         ExtendKind = ISD::ZERO_EXTEND;
1433
1434       getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.getResNo() + j),
1435                      &Parts[0], NumParts, PartVT, ExtendKind);
1436
1437       for (unsigned i = 0; i < NumParts; ++i) {
1438         NewValues.push_back(Parts[i]);
1439         NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1440       }
1441     }
1442   }
1443   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1444                           &NewValues[0], NewValues.size()));
1445 }
1446
1447 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1448 /// the current basic block, add it to ValueMap now so that we'll get a
1449 /// CopyTo/FromReg.
1450 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1451   // No need to export constants.
1452   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1453   
1454   // Already exported?
1455   if (FuncInfo.isExportedInst(V)) return;
1456
1457   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1458   CopyValueToVirtualRegister(V, Reg);
1459 }
1460
1461 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1462                                                     const BasicBlock *FromBB) {
1463   // The operands of the setcc have to be in this block.  We don't know
1464   // how to export them from some other block.
1465   if (Instruction *VI = dyn_cast<Instruction>(V)) {
1466     // Can export from current BB.
1467     if (VI->getParent() == FromBB)
1468       return true;
1469     
1470     // Is already exported, noop.
1471     return FuncInfo.isExportedInst(V);
1472   }
1473   
1474   // If this is an argument, we can export it if the BB is the entry block or
1475   // if it is already exported.
1476   if (isa<Argument>(V)) {
1477     if (FromBB == &FromBB->getParent()->getEntryBlock())
1478       return true;
1479
1480     // Otherwise, can only export this if it is already exported.
1481     return FuncInfo.isExportedInst(V);
1482   }
1483   
1484   // Otherwise, constants can always be exported.
1485   return true;
1486 }
1487
1488 static bool InBlock(const Value *V, const BasicBlock *BB) {
1489   if (const Instruction *I = dyn_cast<Instruction>(V))
1490     return I->getParent() == BB;
1491   return true;
1492 }
1493
1494 /// FindMergedConditions - If Cond is an expression like 
1495 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1496                                                 MachineBasicBlock *TBB,
1497                                                 MachineBasicBlock *FBB,
1498                                                 MachineBasicBlock *CurBB,
1499                                                 unsigned Opc) {
1500   // If this node is not part of the or/and tree, emit it as a branch.
1501   Instruction *BOp = dyn_cast<Instruction>(Cond);
1502
1503   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 
1504       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1505       BOp->getParent() != CurBB->getBasicBlock() ||
1506       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1507       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1508     const BasicBlock *BB = CurBB->getBasicBlock();
1509     
1510     // If the leaf of the tree is a comparison, merge the condition into 
1511     // the caseblock.
1512     if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1513         // The operands of the cmp have to be in this block.  We don't know
1514         // how to export them from some other block.  If this is the first block
1515         // of the sequence, no exporting is needed.
1516         (CurBB == CurMBB ||
1517          (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1518           isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1519       BOp = cast<Instruction>(Cond);
1520       ISD::CondCode Condition;
1521       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1522         switch (IC->getPredicate()) {
1523         default: assert(0 && "Unknown icmp predicate opcode!");
1524         case ICmpInst::ICMP_EQ:  Condition = ISD::SETEQ;  break;
1525         case ICmpInst::ICMP_NE:  Condition = ISD::SETNE;  break;
1526         case ICmpInst::ICMP_SLE: Condition = ISD::SETLE;  break;
1527         case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1528         case ICmpInst::ICMP_SGE: Condition = ISD::SETGE;  break;
1529         case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1530         case ICmpInst::ICMP_SLT: Condition = ISD::SETLT;  break;
1531         case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1532         case ICmpInst::ICMP_SGT: Condition = ISD::SETGT;  break;
1533         case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1534         }
1535       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1536         ISD::CondCode FPC, FOC;
1537         switch (FC->getPredicate()) {
1538         default: assert(0 && "Unknown fcmp predicate opcode!");
1539         case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1540         case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1541         case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1542         case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1543         case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1544         case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1545         case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1546         case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1547         case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1548         case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1549         case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1550         case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1551         case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1552         case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1553         case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1554         case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1555         }
1556         if (FiniteOnlyFPMath())
1557           Condition = FOC;
1558         else 
1559           Condition = FPC;
1560       } else {
1561         Condition = ISD::SETEQ; // silence warning.
1562         assert(0 && "Unknown compare instruction");
1563       }
1564       
1565       CaseBlock CB(Condition, BOp->getOperand(0), 
1566                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1567       SwitchCases.push_back(CB);
1568       return;
1569     }
1570     
1571     // Create a CaseBlock record representing this branch.
1572     CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1573                  NULL, TBB, FBB, CurBB);
1574     SwitchCases.push_back(CB);
1575     return;
1576   }
1577   
1578   
1579   //  Create TmpBB after CurBB.
1580   MachineFunction::iterator BBI = CurBB;
1581   MachineFunction &MF = DAG.getMachineFunction();
1582   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1583   CurBB->getParent()->insert(++BBI, TmpBB);
1584   
1585   if (Opc == Instruction::Or) {
1586     // Codegen X | Y as:
1587     //   jmp_if_X TBB
1588     //   jmp TmpBB
1589     // TmpBB:
1590     //   jmp_if_Y TBB
1591     //   jmp FBB
1592     //
1593   
1594     // Emit the LHS condition.
1595     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1596   
1597     // Emit the RHS condition into TmpBB.
1598     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1599   } else {
1600     assert(Opc == Instruction::And && "Unknown merge op!");
1601     // Codegen X & Y as:
1602     //   jmp_if_X TmpBB
1603     //   jmp FBB
1604     // TmpBB:
1605     //   jmp_if_Y TBB
1606     //   jmp FBB
1607     //
1608     //  This requires creation of TmpBB after CurBB.
1609     
1610     // Emit the LHS condition.
1611     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1612     
1613     // Emit the RHS condition into TmpBB.
1614     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1615   }
1616 }
1617
1618 /// If the set of cases should be emitted as a series of branches, return true.
1619 /// If we should emit this as a bunch of and/or'd together conditions, return
1620 /// false.
1621 static bool 
1622 ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1623   if (Cases.size() != 2) return true;
1624   
1625   // If this is two comparisons of the same values or'd or and'd together, they
1626   // will get folded into a single comparison, so don't emit two blocks.
1627   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1628        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1629       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1630        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1631     return false;
1632   }
1633   
1634   return true;
1635 }
1636
1637 void SelectionDAGLowering::visitBr(BranchInst &I) {
1638   // Update machine-CFG edges.
1639   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1640
1641   // Figure out which block is immediately after the current one.
1642   MachineBasicBlock *NextBlock = 0;
1643   MachineFunction::iterator BBI = CurMBB;
1644   if (++BBI != CurMBB->getParent()->end())
1645     NextBlock = BBI;
1646
1647   if (I.isUnconditional()) {
1648     // Update machine-CFG edges.
1649     CurMBB->addSuccessor(Succ0MBB);
1650     
1651     // If this is not a fall-through branch, emit the branch.
1652     if (Succ0MBB != NextBlock)
1653       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1654                               DAG.getBasicBlock(Succ0MBB)));
1655     return;
1656   }
1657
1658   // If this condition is one of the special cases we handle, do special stuff
1659   // now.
1660   Value *CondVal = I.getCondition();
1661   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1662
1663   // If this is a series of conditions that are or'd or and'd together, emit
1664   // this as a sequence of branches instead of setcc's with and/or operations.
1665   // For example, instead of something like:
1666   //     cmp A, B
1667   //     C = seteq 
1668   //     cmp D, E
1669   //     F = setle 
1670   //     or C, F
1671   //     jnz foo
1672   // Emit:
1673   //     cmp A, B
1674   //     je foo
1675   //     cmp D, E
1676   //     jle foo
1677   //
1678   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1679     if (BOp->hasOneUse() && 
1680         (BOp->getOpcode() == Instruction::And ||
1681          BOp->getOpcode() == Instruction::Or)) {
1682       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1683       // If the compares in later blocks need to use values not currently
1684       // exported from this block, export them now.  This block should always
1685       // be the first entry.
1686       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1687       
1688       // Allow some cases to be rejected.
1689       if (ShouldEmitAsBranches(SwitchCases)) {
1690         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1691           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1692           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1693         }
1694         
1695         // Emit the branch for this block.
1696         visitSwitchCase(SwitchCases[0]);
1697         SwitchCases.erase(SwitchCases.begin());
1698         return;
1699       }
1700       
1701       // Okay, we decided not to do this, remove any inserted MBB's and clear
1702       // SwitchCases.
1703       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1704         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1705       
1706       SwitchCases.clear();
1707     }
1708   }
1709   
1710   // Create a CaseBlock record representing this branch.
1711   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1712                NULL, Succ0MBB, Succ1MBB, CurMBB);
1713   // Use visitSwitchCase to actually insert the fast branch sequence for this
1714   // cond branch.
1715   visitSwitchCase(CB);
1716 }
1717
1718 /// visitSwitchCase - Emits the necessary code to represent a single node in
1719 /// the binary search tree resulting from lowering a switch instruction.
1720 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1721   SDValue Cond;
1722   SDValue CondLHS = getValue(CB.CmpLHS);
1723   
1724   // Build the setcc now. 
1725   if (CB.CmpMHS == NULL) {
1726     // Fold "(X == true)" to X and "(X == false)" to !X to
1727     // handle common cases produced by branch lowering.
1728     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1729       Cond = CondLHS;
1730     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1731       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1732       Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1733     } else
1734       Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1735   } else {
1736     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1737
1738     uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1739     uint64_t High  = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1740
1741     SDValue CmpOp = getValue(CB.CmpMHS);
1742     MVT VT = CmpOp.getValueType();
1743
1744     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1745       Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1746     } else {
1747       SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1748       Cond = DAG.getSetCC(MVT::i1, SUB,
1749                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1750     }
1751   }
1752   
1753   // Update successor info
1754   CurMBB->addSuccessor(CB.TrueBB);
1755   CurMBB->addSuccessor(CB.FalseBB);
1756   
1757   // Set NextBlock to be the MBB immediately after the current one, if any.
1758   // This is used to avoid emitting unnecessary branches to the next block.
1759   MachineBasicBlock *NextBlock = 0;
1760   MachineFunction::iterator BBI = CurMBB;
1761   if (++BBI != CurMBB->getParent()->end())
1762     NextBlock = BBI;
1763   
1764   // If the lhs block is the next block, invert the condition so that we can
1765   // fall through to the lhs instead of the rhs block.
1766   if (CB.TrueBB == NextBlock) {
1767     std::swap(CB.TrueBB, CB.FalseBB);
1768     SDValue True = DAG.getConstant(1, Cond.getValueType());
1769     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1770   }
1771   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1772                                  DAG.getBasicBlock(CB.TrueBB));
1773   
1774   // If the branch was constant folded, fix up the CFG.
1775   if (BrCond.getOpcode() == ISD::BR) {
1776     CurMBB->removeSuccessor(CB.FalseBB);
1777     DAG.setRoot(BrCond);
1778   } else {
1779     // Otherwise, go ahead and insert the false branch.
1780     if (BrCond == getControlRoot()) 
1781       CurMBB->removeSuccessor(CB.TrueBB);
1782     
1783     if (CB.FalseBB == NextBlock)
1784       DAG.setRoot(BrCond);
1785     else
1786       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1787                               DAG.getBasicBlock(CB.FalseBB)));
1788   }
1789 }
1790
1791 /// visitJumpTable - Emit JumpTable node in the current MBB
1792 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1793   // Emit the code for the jump table
1794   assert(JT.Reg != -1U && "Should lower JT Header first!");
1795   MVT PTy = TLI.getPointerTy();
1796   SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1797   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1798   DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1799                           Table, Index));
1800   return;
1801 }
1802
1803 /// visitJumpTableHeader - This function emits necessary code to produce index
1804 /// in the JumpTable from switch case.
1805 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1806                                                 JumpTableHeader &JTH) {
1807   // Subtract the lowest switch case value from the value being switched on
1808   // and conditional branch to default mbb if the result is greater than the
1809   // difference between smallest and largest cases.
1810   SDValue SwitchOp = getValue(JTH.SValue);
1811   MVT VT = SwitchOp.getValueType();
1812   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1813                               DAG.getConstant(JTH.First, VT));
1814   
1815   // The SDNode we just created, which holds the value being switched on
1816   // minus the the smallest case value, needs to be copied to a virtual
1817   // register so it can be used as an index into the jump table in a 
1818   // subsequent basic block.  This value may be smaller or larger than the
1819   // target's pointer type, and therefore require extension or truncating.
1820   if (VT.bitsGT(TLI.getPointerTy()))
1821     SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1822   else
1823     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1824   
1825   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1826   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1827   JT.Reg = JumpTableReg;
1828
1829   // Emit the range check for the jump table, and branch to the default
1830   // block for the switch statement if the value being switched on exceeds
1831   // the largest case in the switch.
1832   SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1833                                DAG.getConstant(JTH.Last-JTH.First,VT),
1834                                ISD::SETUGT);
1835
1836   // Set NextBlock to be the MBB immediately after the current one, if any.
1837   // This is used to avoid emitting unnecessary branches to the next block.
1838   MachineBasicBlock *NextBlock = 0;
1839   MachineFunction::iterator BBI = CurMBB;
1840   if (++BBI != CurMBB->getParent()->end())
1841     NextBlock = BBI;
1842
1843   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1844                                  DAG.getBasicBlock(JT.Default));
1845
1846   if (JT.MBB == NextBlock)
1847     DAG.setRoot(BrCond);
1848   else
1849     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1850                             DAG.getBasicBlock(JT.MBB)));
1851
1852   return;
1853 }
1854
1855 /// visitBitTestHeader - This function emits necessary code to produce value
1856 /// suitable for "bit tests"
1857 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1858   // Subtract the minimum value
1859   SDValue SwitchOp = getValue(B.SValue);
1860   MVT VT = SwitchOp.getValueType();
1861   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1862                               DAG.getConstant(B.First, VT));
1863
1864   // Check range
1865   SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1866                                     DAG.getConstant(B.Range, VT),
1867                                     ISD::SETUGT);
1868
1869   SDValue ShiftOp;
1870   if (VT.bitsGT(TLI.getShiftAmountTy()))
1871     ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1872   else
1873     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1874
1875   // Make desired shift
1876   SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1877                                     DAG.getConstant(1, TLI.getPointerTy()),
1878                                     ShiftOp);
1879
1880   unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1881   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1882   B.Reg = SwitchReg;
1883
1884   // Set NextBlock to be the MBB immediately after the current one, if any.
1885   // This is used to avoid emitting unnecessary branches to the next block.
1886   MachineBasicBlock *NextBlock = 0;
1887   MachineFunction::iterator BBI = CurMBB;
1888   if (++BBI != CurMBB->getParent()->end())
1889     NextBlock = BBI;
1890
1891   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1892
1893   CurMBB->addSuccessor(B.Default);
1894   CurMBB->addSuccessor(MBB);
1895
1896   SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1897                                   DAG.getBasicBlock(B.Default));
1898   
1899   if (MBB == NextBlock)
1900     DAG.setRoot(BrRange);
1901   else
1902     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1903                             DAG.getBasicBlock(MBB)));
1904
1905   return;
1906 }
1907
1908 /// visitBitTestCase - this function produces one "bit test"
1909 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1910                                             unsigned Reg,
1911                                             BitTestCase &B) {
1912   // Emit bit tests and jumps
1913   SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, 
1914                                            TLI.getPointerTy());
1915   
1916   SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1917                                 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1918   SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1919                                   DAG.getConstant(0, TLI.getPointerTy()),
1920                                   ISD::SETNE);
1921
1922   CurMBB->addSuccessor(B.TargetBB);
1923   CurMBB->addSuccessor(NextMBB);
1924   
1925   SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1926                                 AndCmp, DAG.getBasicBlock(B.TargetBB));
1927
1928   // Set NextBlock to be the MBB immediately after the current one, if any.
1929   // This is used to avoid emitting unnecessary branches to the next block.
1930   MachineBasicBlock *NextBlock = 0;
1931   MachineFunction::iterator BBI = CurMBB;
1932   if (++BBI != CurMBB->getParent()->end())
1933     NextBlock = BBI;
1934
1935   if (NextMBB == NextBlock)
1936     DAG.setRoot(BrAnd);
1937   else
1938     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1939                             DAG.getBasicBlock(NextMBB)));
1940
1941   return;
1942 }
1943
1944 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1945   // Retrieve successors.
1946   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1947   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1948
1949   if (isa<InlineAsm>(I.getCalledValue()))
1950     visitInlineAsm(&I);
1951   else
1952     LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1953
1954   // If the value of the invoke is used outside of its defining block, make it
1955   // available as a virtual register.
1956   if (!I.use_empty()) {
1957     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1958     if (VMI != FuncInfo.ValueMap.end())
1959       CopyValueToVirtualRegister(&I, VMI->second);
1960   }
1961
1962   // Update successor info
1963   CurMBB->addSuccessor(Return);
1964   CurMBB->addSuccessor(LandingPad);
1965
1966   // Drop into normal successor.
1967   DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1968                           DAG.getBasicBlock(Return)));
1969 }
1970
1971 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1972 }
1973
1974 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1975 /// small case ranges).
1976 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1977                                                   CaseRecVector& WorkList,
1978                                                   Value* SV,
1979                                                   MachineBasicBlock* Default) {
1980   Case& BackCase  = *(CR.Range.second-1);
1981   
1982   // Size is the number of Cases represented by this range.
1983   unsigned Size = CR.Range.second - CR.Range.first;
1984   if (Size > 3)
1985     return false;  
1986   
1987   // Get the MachineFunction which holds the current MBB.  This is used when
1988   // inserting any additional MBBs necessary to represent the switch.
1989   MachineFunction *CurMF = CurMBB->getParent();  
1990
1991   // Figure out which block is immediately after the current one.
1992   MachineBasicBlock *NextBlock = 0;
1993   MachineFunction::iterator BBI = CR.CaseBB;
1994
1995   if (++BBI != CurMBB->getParent()->end())
1996     NextBlock = BBI;
1997
1998   // TODO: If any two of the cases has the same destination, and if one value
1999   // is the same as the other, but has one bit unset that the other has set,
2000   // use bit manipulation to do two compares at once.  For example:
2001   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2002     
2003   // Rearrange the case blocks so that the last one falls through if possible.
2004   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2005     // The last case block won't fall through into 'NextBlock' if we emit the
2006     // branches in this order.  See if rearranging a case value would help.
2007     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
2008       if (I->BB == NextBlock) {
2009         std::swap(*I, BackCase);
2010         break;
2011       }
2012     }
2013   }
2014   
2015   // Create a CaseBlock record representing a conditional branch to
2016   // the Case's target mbb if the value being switched on SV is equal
2017   // to C.
2018   MachineBasicBlock *CurBlock = CR.CaseBB;
2019   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2020     MachineBasicBlock *FallThrough;
2021     if (I != E-1) {
2022       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2023       CurMF->insert(BBI, FallThrough);
2024     } else {
2025       // If the last case doesn't match, go to the default block.
2026       FallThrough = Default;
2027     }
2028
2029     Value *RHS, *LHS, *MHS;
2030     ISD::CondCode CC;
2031     if (I->High == I->Low) {
2032       // This is just small small case range :) containing exactly 1 case
2033       CC = ISD::SETEQ;
2034       LHS = SV; RHS = I->High; MHS = NULL;
2035     } else {
2036       CC = ISD::SETLE;
2037       LHS = I->Low; MHS = SV; RHS = I->High;
2038     }
2039     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
2040     
2041     // If emitting the first comparison, just call visitSwitchCase to emit the
2042     // code into the current block.  Otherwise, push the CaseBlock onto the
2043     // vector to be later processed by SDISel, and insert the node's MBB
2044     // before the next MBB.
2045     if (CurBlock == CurMBB)
2046       visitSwitchCase(CB);
2047     else
2048       SwitchCases.push_back(CB);
2049     
2050     CurBlock = FallThrough;
2051   }
2052
2053   return true;
2054 }
2055
2056 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2057   return !DisableJumpTables &&
2058           (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
2059            TLI.isOperationLegal(ISD::BRIND, MVT::Other));
2060 }
2061   
2062 /// handleJTSwitchCase - Emit jumptable for current switch case range
2063 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
2064                                               CaseRecVector& WorkList,
2065                                               Value* SV,
2066                                               MachineBasicBlock* Default) {
2067   Case& FrontCase = *CR.Range.first;
2068   Case& BackCase  = *(CR.Range.second-1);
2069
2070   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2071   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
2072
2073   uint64_t TSize = 0;
2074   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2075        I!=E; ++I)
2076     TSize += I->size();
2077
2078   if (!areJTsAllowed(TLI) || TSize <= 3)
2079     return false;
2080   
2081   double Density = (double)TSize / (double)((Last - First) + 1ULL);  
2082   if (Density < 0.4)
2083     return false;
2084
2085   DOUT << "Lowering jump table\n"
2086        << "First entry: " << First << ". Last entry: " << Last << "\n"
2087        << "Size: " << TSize << ". Density: " << Density << "\n\n";
2088
2089   // Get the MachineFunction which holds the current MBB.  This is used when
2090   // inserting any additional MBBs necessary to represent the switch.
2091   MachineFunction *CurMF = CurMBB->getParent();
2092
2093   // Figure out which block is immediately after the current one.
2094   MachineBasicBlock *NextBlock = 0;
2095   MachineFunction::iterator BBI = CR.CaseBB;
2096
2097   if (++BBI != CurMBB->getParent()->end())
2098     NextBlock = BBI;
2099
2100   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2101
2102   // Create a new basic block to hold the code for loading the address
2103   // of the jump table, and jumping to it.  Update successor information;
2104   // we will either branch to the default case for the switch, or the jump
2105   // table.
2106   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2107   CurMF->insert(BBI, JumpTableBB);
2108   CR.CaseBB->addSuccessor(Default);
2109   CR.CaseBB->addSuccessor(JumpTableBB);
2110                 
2111   // Build a vector of destination BBs, corresponding to each target
2112   // of the jump table. If the value of the jump table slot corresponds to
2113   // a case statement, push the case's BB onto the vector, otherwise, push
2114   // the default BB.
2115   std::vector<MachineBasicBlock*> DestBBs;
2116   int64_t TEI = First;
2117   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2118     int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
2119     int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
2120     
2121     if ((Low <= TEI) && (TEI <= High)) {
2122       DestBBs.push_back(I->BB);
2123       if (TEI==High)
2124         ++I;
2125     } else {
2126       DestBBs.push_back(Default);
2127     }
2128   }
2129   
2130   // Update successor info. Add one edge to each unique successor.
2131   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());  
2132   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 
2133          E = DestBBs.end(); I != E; ++I) {
2134     if (!SuccsHandled[(*I)->getNumber()]) {
2135       SuccsHandled[(*I)->getNumber()] = true;
2136       JumpTableBB->addSuccessor(*I);
2137     }
2138   }
2139       
2140   // Create a jump table index for this jump table, or return an existing
2141   // one.
2142   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2143   
2144   // Set the jump table information so that we can codegen it as a second
2145   // MachineBasicBlock
2146   JumpTable JT(-1U, JTI, JumpTableBB, Default);
2147   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
2148   if (CR.CaseBB == CurMBB)
2149     visitJumpTableHeader(JT, JTH);
2150         
2151   JTCases.push_back(JumpTableBlock(JTH, JT));
2152
2153   return true;
2154 }
2155
2156 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2157 /// 2 subtrees.
2158 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
2159                                                    CaseRecVector& WorkList,
2160                                                    Value* SV,
2161                                                    MachineBasicBlock* Default) {
2162   // Get the MachineFunction which holds the current MBB.  This is used when
2163   // inserting any additional MBBs necessary to represent the switch.
2164   MachineFunction *CurMF = CurMBB->getParent();  
2165
2166   // Figure out which block is immediately after the current one.
2167   MachineBasicBlock *NextBlock = 0;
2168   MachineFunction::iterator BBI = CR.CaseBB;
2169
2170   if (++BBI != CurMBB->getParent()->end())
2171     NextBlock = BBI;
2172
2173   Case& FrontCase = *CR.Range.first;
2174   Case& BackCase  = *(CR.Range.second-1);
2175   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2176
2177   // Size is the number of Cases represented by this range.
2178   unsigned Size = CR.Range.second - CR.Range.first;
2179
2180   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2181   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
2182   double FMetric = 0;
2183   CaseItr Pivot = CR.Range.first + Size/2;
2184
2185   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2186   // (heuristically) allow us to emit JumpTable's later.
2187   uint64_t TSize = 0;
2188   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2189        I!=E; ++I)
2190     TSize += I->size();
2191
2192   uint64_t LSize = FrontCase.size();
2193   uint64_t RSize = TSize-LSize;
2194   DOUT << "Selecting best pivot: \n"
2195        << "First: " << First << ", Last: " << Last <<"\n"
2196        << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2197   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2198        J!=E; ++I, ++J) {
2199     int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2200     int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2201     assert((RBegin-LEnd>=1) && "Invalid case distance");
2202     double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2203     double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2204     double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2205     // Should always split in some non-trivial place
2206     DOUT <<"=>Step\n"
2207          << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2208          << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2209          << "Metric: " << Metric << "\n"; 
2210     if (FMetric < Metric) {
2211       Pivot = J;
2212       FMetric = Metric;
2213       DOUT << "Current metric set to: " << FMetric << "\n";
2214     }
2215
2216     LSize += J->size();
2217     RSize -= J->size();
2218   }
2219   if (areJTsAllowed(TLI)) {
2220     // If our case is dense we *really* should handle it earlier!
2221     assert((FMetric > 0) && "Should handle dense range earlier!");
2222   } else {
2223     Pivot = CR.Range.first + Size/2;
2224   }
2225   
2226   CaseRange LHSR(CR.Range.first, Pivot);
2227   CaseRange RHSR(Pivot, CR.Range.second);
2228   Constant *C = Pivot->Low;
2229   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2230       
2231   // We know that we branch to the LHS if the Value being switched on is
2232   // less than the Pivot value, C.  We use this to optimize our binary 
2233   // tree a bit, by recognizing that if SV is greater than or equal to the
2234   // LHS's Case Value, and that Case Value is exactly one less than the 
2235   // Pivot's Value, then we can branch directly to the LHS's Target,
2236   // rather than creating a leaf node for it.
2237   if ((LHSR.second - LHSR.first) == 1 &&
2238       LHSR.first->High == CR.GE &&
2239       cast<ConstantInt>(C)->getSExtValue() ==
2240       (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2241     TrueBB = LHSR.first->BB;
2242   } else {
2243     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2244     CurMF->insert(BBI, TrueBB);
2245     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2246   }
2247   
2248   // Similar to the optimization above, if the Value being switched on is
2249   // known to be less than the Constant CR.LT, and the current Case Value
2250   // is CR.LT - 1, then we can branch directly to the target block for
2251   // the current Case Value, rather than emitting a RHS leaf node for it.
2252   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2253       cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2254       (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2255     FalseBB = RHSR.first->BB;
2256   } else {
2257     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2258     CurMF->insert(BBI, FalseBB);
2259     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2260   }
2261
2262   // Create a CaseBlock record representing a conditional branch to
2263   // the LHS node if the value being switched on SV is less than C. 
2264   // Otherwise, branch to LHS.
2265   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2266
2267   if (CR.CaseBB == CurMBB)
2268     visitSwitchCase(CB);
2269   else
2270     SwitchCases.push_back(CB);
2271
2272   return true;
2273 }
2274
2275 /// handleBitTestsSwitchCase - if current case range has few destination and
2276 /// range span less, than machine word bitwidth, encode case range into series
2277 /// of masks and emit bit tests with these masks.
2278 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2279                                                     CaseRecVector& WorkList,
2280                                                     Value* SV,
2281                                                     MachineBasicBlock* Default){
2282   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2283
2284   Case& FrontCase = *CR.Range.first;
2285   Case& BackCase  = *(CR.Range.second-1);
2286
2287   // Get the MachineFunction which holds the current MBB.  This is used when
2288   // inserting any additional MBBs necessary to represent the switch.
2289   MachineFunction *CurMF = CurMBB->getParent();  
2290
2291   unsigned numCmps = 0;
2292   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2293        I!=E; ++I) {
2294     // Single case counts one, case range - two.
2295     if (I->Low == I->High)
2296       numCmps +=1;
2297     else
2298       numCmps +=2;
2299   }
2300     
2301   // Count unique destinations
2302   SmallSet<MachineBasicBlock*, 4> Dests;
2303   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2304     Dests.insert(I->BB);
2305     if (Dests.size() > 3)
2306       // Don't bother the code below, if there are too much unique destinations
2307       return false;
2308   }
2309   DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2310        << "Total number of comparisons: " << numCmps << "\n";
2311   
2312   // Compute span of values.
2313   Constant* minValue = FrontCase.Low;
2314   Constant* maxValue = BackCase.High;
2315   uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2316                    cast<ConstantInt>(minValue)->getSExtValue();
2317   DOUT << "Compare range: " << range << "\n"
2318        << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2319        << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2320   
2321   if (range>=IntPtrBits ||
2322       (!(Dests.size() == 1 && numCmps >= 3) &&
2323        !(Dests.size() == 2 && numCmps >= 5) &&
2324        !(Dests.size() >= 3 && numCmps >= 6)))
2325     return false;
2326   
2327   DOUT << "Emitting bit tests\n";
2328   int64_t lowBound = 0;
2329     
2330   // Optimize the case where all the case values fit in a
2331   // word without having to subtract minValue. In this case,
2332   // we can optimize away the subtraction.
2333   if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2334       cast<ConstantInt>(maxValue)->getSExtValue() <  IntPtrBits) {
2335     range = cast<ConstantInt>(maxValue)->getSExtValue();
2336   } else {
2337     lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2338   }
2339     
2340   CaseBitsVector CasesBits;
2341   unsigned i, count = 0;
2342
2343   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2344     MachineBasicBlock* Dest = I->BB;
2345     for (i = 0; i < count; ++i)
2346       if (Dest == CasesBits[i].BB)
2347         break;
2348     
2349     if (i == count) {
2350       assert((count < 3) && "Too much destinations to test!");
2351       CasesBits.push_back(CaseBits(0, Dest, 0));
2352       count++;
2353     }
2354     
2355     uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2356     uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2357     
2358     for (uint64_t j = lo; j <= hi; j++) {
2359       CasesBits[i].Mask |=  1ULL << j;
2360       CasesBits[i].Bits++;
2361     }
2362       
2363   }
2364   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2365   
2366   BitTestInfo BTC;
2367
2368   // Figure out which block is immediately after the current one.
2369   MachineFunction::iterator BBI = CR.CaseBB;
2370   ++BBI;
2371
2372   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2373
2374   DOUT << "Cases:\n";
2375   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2376     DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2377          << ", BB: " << CasesBits[i].BB << "\n";
2378
2379     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2380     CurMF->insert(BBI, CaseBB);
2381     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2382                               CaseBB,
2383                               CasesBits[i].BB));
2384   }
2385   
2386   BitTestBlock BTB(lowBound, range, SV,
2387                    -1U, (CR.CaseBB == CurMBB),
2388                    CR.CaseBB, Default, BTC);
2389
2390   if (CR.CaseBB == CurMBB)
2391     visitBitTestHeader(BTB);
2392   
2393   BitTestCases.push_back(BTB);
2394
2395   return true;
2396 }
2397
2398
2399 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2400 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2401                                           const SwitchInst& SI) {
2402   unsigned numCmps = 0;
2403
2404   // Start with "simple" cases
2405   for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2406     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2407     Cases.push_back(Case(SI.getSuccessorValue(i),
2408                          SI.getSuccessorValue(i),
2409                          SMBB));
2410   }
2411   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2412
2413   // Merge case into clusters
2414   if (Cases.size()>=2)
2415     // Must recompute end() each iteration because it may be
2416     // invalidated by erase if we hold on to it
2417     for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2418       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2419       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2420       MachineBasicBlock* nextBB = J->BB;
2421       MachineBasicBlock* currentBB = I->BB;
2422
2423       // If the two neighboring cases go to the same destination, merge them
2424       // into a single case.
2425       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2426         I->High = J->High;
2427         J = Cases.erase(J);
2428       } else {
2429         I = J++;
2430       }
2431     }
2432
2433   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2434     if (I->Low != I->High)
2435       // A range counts double, since it requires two compares.
2436       ++numCmps;
2437   }
2438
2439   return numCmps;
2440 }
2441
2442 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {  
2443   // Figure out which block is immediately after the current one.
2444   MachineBasicBlock *NextBlock = 0;
2445   MachineFunction::iterator BBI = CurMBB;
2446
2447   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2448
2449   // If there is only the default destination, branch to it if it is not the
2450   // next basic block.  Otherwise, just fall through.
2451   if (SI.getNumOperands() == 2) {
2452     // Update machine-CFG edges.
2453
2454     // If this is not a fall-through branch, emit the branch.
2455     CurMBB->addSuccessor(Default);
2456     if (Default != NextBlock)
2457       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2458                               DAG.getBasicBlock(Default)));
2459     
2460     return;
2461   }
2462   
2463   // If there are any non-default case statements, create a vector of Cases
2464   // representing each one, and sort the vector so that we can efficiently
2465   // create a binary search tree from them.
2466   CaseVector Cases;
2467   unsigned numCmps = Clusterify(Cases, SI);
2468   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2469        << ". Total compares: " << numCmps << "\n";
2470
2471   // Get the Value to be switched on and default basic blocks, which will be
2472   // inserted into CaseBlock records, representing basic blocks in the binary
2473   // search tree.
2474   Value *SV = SI.getOperand(0);
2475
2476   // Push the initial CaseRec onto the worklist
2477   CaseRecVector WorkList;
2478   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2479
2480   while (!WorkList.empty()) {
2481     // Grab a record representing a case range to process off the worklist
2482     CaseRec CR = WorkList.back();
2483     WorkList.pop_back();
2484
2485     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2486       continue;
2487     
2488     // If the range has few cases (two or less) emit a series of specific
2489     // tests.
2490     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2491       continue;
2492     
2493     // If the switch has more than 5 blocks, and at least 40% dense, and the 
2494     // target supports indirect branches, then emit a jump table rather than 
2495     // lowering the switch to a binary tree of conditional branches.
2496     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2497       continue;
2498           
2499     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2500     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2501     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2502   }
2503 }
2504
2505
2506 void SelectionDAGLowering::visitSub(User &I) {
2507   // -0.0 - X --> fneg
2508   const Type *Ty = I.getType();
2509   if (isa<VectorType>(Ty)) {
2510     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2511       const VectorType *DestTy = cast<VectorType>(I.getType());
2512       const Type *ElTy = DestTy->getElementType();
2513       if (ElTy->isFloatingPoint()) {
2514         unsigned VL = DestTy->getNumElements();
2515         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2516         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2517         if (CV == CNZ) {
2518           SDValue Op2 = getValue(I.getOperand(1));
2519           setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2520           return;
2521         }
2522       }
2523     }
2524   }
2525   if (Ty->isFloatingPoint()) {
2526     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2527       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2528         SDValue Op2 = getValue(I.getOperand(1));
2529         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2530         return;
2531       }
2532   }
2533
2534   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2535 }
2536
2537 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2538   SDValue Op1 = getValue(I.getOperand(0));
2539   SDValue Op2 = getValue(I.getOperand(1));
2540   
2541   setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2542 }
2543
2544 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2545   SDValue Op1 = getValue(I.getOperand(0));
2546   SDValue Op2 = getValue(I.getOperand(1));
2547   if (!isa<VectorType>(I.getType())) {
2548     if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2549       Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2550     else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2551       Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2552   }
2553   
2554   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2555 }
2556
2557 void SelectionDAGLowering::visitICmp(User &I) {
2558   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2559   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2560     predicate = IC->getPredicate();
2561   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2562     predicate = ICmpInst::Predicate(IC->getPredicate());
2563   SDValue Op1 = getValue(I.getOperand(0));
2564   SDValue Op2 = getValue(I.getOperand(1));
2565   ISD::CondCode Opcode;
2566   switch (predicate) {
2567     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2568     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2569     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2570     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2571     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2572     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2573     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2574     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2575     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2576     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2577     default:
2578       assert(!"Invalid ICmp predicate value");
2579       Opcode = ISD::SETEQ;
2580       break;
2581   }
2582   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2583 }
2584
2585 void SelectionDAGLowering::visitFCmp(User &I) {
2586   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2587   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2588     predicate = FC->getPredicate();
2589   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2590     predicate = FCmpInst::Predicate(FC->getPredicate());
2591   SDValue Op1 = getValue(I.getOperand(0));
2592   SDValue Op2 = getValue(I.getOperand(1));
2593   ISD::CondCode Condition, FOC, FPC;
2594   switch (predicate) {
2595     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2596     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2597     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2598     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2599     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2600     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2601     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2602     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2603     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2604     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2605     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2606     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2607     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2608     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2609     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2610     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2611     default:
2612       assert(!"Invalid FCmp predicate value");
2613       FOC = FPC = ISD::SETFALSE;
2614       break;
2615   }
2616   if (FiniteOnlyFPMath())
2617     Condition = FOC;
2618   else 
2619     Condition = FPC;
2620   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2621 }
2622
2623 void SelectionDAGLowering::visitVICmp(User &I) {
2624   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2625   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2626     predicate = IC->getPredicate();
2627   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2628     predicate = ICmpInst::Predicate(IC->getPredicate());
2629   SDValue Op1 = getValue(I.getOperand(0));
2630   SDValue Op2 = getValue(I.getOperand(1));
2631   ISD::CondCode Opcode;
2632   switch (predicate) {
2633     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2634     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2635     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2636     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2637     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2638     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2639     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2640     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2641     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2642     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2643     default:
2644       assert(!"Invalid ICmp predicate value");
2645       Opcode = ISD::SETEQ;
2646       break;
2647   }
2648   setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2649 }
2650
2651 void SelectionDAGLowering::visitVFCmp(User &I) {
2652   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2653   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2654     predicate = FC->getPredicate();
2655   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2656     predicate = FCmpInst::Predicate(FC->getPredicate());
2657   SDValue Op1 = getValue(I.getOperand(0));
2658   SDValue Op2 = getValue(I.getOperand(1));
2659   ISD::CondCode Condition, FOC, FPC;
2660   switch (predicate) {
2661     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2662     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2663     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2664     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2665     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2666     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2667     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2668     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2669     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2670     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2671     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2672     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2673     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2674     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2675     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2676     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2677     default:
2678       assert(!"Invalid VFCmp predicate value");
2679       FOC = FPC = ISD::SETFALSE;
2680       break;
2681   }
2682   if (FiniteOnlyFPMath())
2683     Condition = FOC;
2684   else 
2685     Condition = FPC;
2686     
2687   MVT DestVT = TLI.getValueType(I.getType());
2688     
2689   setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2690 }
2691
2692 void SelectionDAGLowering::visitSelect(User &I) {
2693   SDValue Cond     = getValue(I.getOperand(0));
2694   SDValue TrueVal  = getValue(I.getOperand(1));
2695   SDValue FalseVal = getValue(I.getOperand(2));
2696   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2697                            TrueVal, FalseVal));
2698 }
2699
2700
2701 void SelectionDAGLowering::visitTrunc(User &I) {
2702   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2703   SDValue N = getValue(I.getOperand(0));
2704   MVT DestVT = TLI.getValueType(I.getType());
2705   setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2706 }
2707
2708 void SelectionDAGLowering::visitZExt(User &I) {
2709   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2710   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2711   SDValue N = getValue(I.getOperand(0));
2712   MVT DestVT = TLI.getValueType(I.getType());
2713   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2714 }
2715
2716 void SelectionDAGLowering::visitSExt(User &I) {
2717   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2718   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2719   SDValue N = getValue(I.getOperand(0));
2720   MVT DestVT = TLI.getValueType(I.getType());
2721   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2722 }
2723
2724 void SelectionDAGLowering::visitFPTrunc(User &I) {
2725   // FPTrunc is never a no-op cast, no need to check
2726   SDValue N = getValue(I.getOperand(0));
2727   MVT DestVT = TLI.getValueType(I.getType());
2728   setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2729 }
2730
2731 void SelectionDAGLowering::visitFPExt(User &I){ 
2732   // FPTrunc is never a no-op cast, no need to check
2733   SDValue N = getValue(I.getOperand(0));
2734   MVT DestVT = TLI.getValueType(I.getType());
2735   setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2736 }
2737
2738 void SelectionDAGLowering::visitFPToUI(User &I) { 
2739   // FPToUI is never a no-op cast, no need to check
2740   SDValue N = getValue(I.getOperand(0));
2741   MVT DestVT = TLI.getValueType(I.getType());
2742   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2743 }
2744
2745 void SelectionDAGLowering::visitFPToSI(User &I) {
2746   // FPToSI is never a no-op cast, no need to check
2747   SDValue N = getValue(I.getOperand(0));
2748   MVT DestVT = TLI.getValueType(I.getType());
2749   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2750 }
2751
2752 void SelectionDAGLowering::visitUIToFP(User &I) { 
2753   // UIToFP is never a no-op cast, no need to check
2754   SDValue N = getValue(I.getOperand(0));
2755   MVT DestVT = TLI.getValueType(I.getType());
2756   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2757 }
2758
2759 void SelectionDAGLowering::visitSIToFP(User &I){ 
2760   // UIToFP is never a no-op cast, no need to check
2761   SDValue N = getValue(I.getOperand(0));
2762   MVT DestVT = TLI.getValueType(I.getType());
2763   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2764 }
2765
2766 void SelectionDAGLowering::visitPtrToInt(User &I) {
2767   // What to do depends on the size of the integer and the size of the pointer.
2768   // We can either truncate, zero extend, or no-op, accordingly.
2769   SDValue N = getValue(I.getOperand(0));
2770   MVT SrcVT = N.getValueType();
2771   MVT DestVT = TLI.getValueType(I.getType());
2772   SDValue Result;
2773   if (DestVT.bitsLT(SrcVT))
2774     Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2775   else 
2776     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2777     Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2778   setValue(&I, Result);
2779 }
2780
2781 void SelectionDAGLowering::visitIntToPtr(User &I) {
2782   // What to do depends on the size of the integer and the size of the pointer.
2783   // We can either truncate, zero extend, or no-op, accordingly.
2784   SDValue N = getValue(I.getOperand(0));
2785   MVT SrcVT = N.getValueType();
2786   MVT DestVT = TLI.getValueType(I.getType());
2787   if (DestVT.bitsLT(SrcVT))
2788     setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2789   else 
2790     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2791     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2792 }
2793
2794 void SelectionDAGLowering::visitBitCast(User &I) { 
2795   SDValue N = getValue(I.getOperand(0));
2796   MVT DestVT = TLI.getValueType(I.getType());
2797
2798   // BitCast assures us that source and destination are the same size so this 
2799   // is either a BIT_CONVERT or a no-op.
2800   if (DestVT != N.getValueType())
2801     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2802   else
2803     setValue(&I, N); // noop cast.
2804 }
2805
2806 void SelectionDAGLowering::visitInsertElement(User &I) {
2807   SDValue InVec = getValue(I.getOperand(0));
2808   SDValue InVal = getValue(I.getOperand(1));
2809   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2810                                 getValue(I.getOperand(2)));
2811
2812   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2813                            TLI.getValueType(I.getType()),
2814                            InVec, InVal, InIdx));
2815 }
2816
2817 void SelectionDAGLowering::visitExtractElement(User &I) {
2818   SDValue InVec = getValue(I.getOperand(0));
2819   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2820                                 getValue(I.getOperand(1)));
2821   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2822                            TLI.getValueType(I.getType()), InVec, InIdx));
2823 }
2824
2825 void SelectionDAGLowering::visitShuffleVector(User &I) {
2826   SDValue V1   = getValue(I.getOperand(0));
2827   SDValue V2   = getValue(I.getOperand(1));
2828   SDValue Mask = getValue(I.getOperand(2));
2829
2830   setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2831                            TLI.getValueType(I.getType()),
2832                            V1, V2, Mask));
2833 }
2834
2835 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2836   const Value *Op0 = I.getOperand(0);
2837   const Value *Op1 = I.getOperand(1);
2838   const Type *AggTy = I.getType();
2839   const Type *ValTy = Op1->getType();
2840   bool IntoUndef = isa<UndefValue>(Op0);
2841   bool FromUndef = isa<UndefValue>(Op1);
2842
2843   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2844                                             I.idx_begin(), I.idx_end());
2845
2846   SmallVector<MVT, 4> AggValueVTs;
2847   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2848   SmallVector<MVT, 4> ValValueVTs;
2849   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2850
2851   unsigned NumAggValues = AggValueVTs.size();
2852   unsigned NumValValues = ValValueVTs.size();
2853   SmallVector<SDValue, 4> Values(NumAggValues);
2854
2855   SDValue Agg = getValue(Op0);
2856   SDValue Val = getValue(Op1);
2857   unsigned i = 0;
2858   // Copy the beginning value(s) from the original aggregate.
2859   for (; i != LinearIndex; ++i)
2860     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2861                 SDValue(Agg.Val, Agg.getResNo() + i);
2862   // Copy values from the inserted value(s).
2863   for (; i != LinearIndex + NumValValues; ++i)
2864     Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2865                 SDValue(Val.Val, Val.getResNo() + i - LinearIndex);
2866   // Copy remaining value(s) from the original aggregate.
2867   for (; i != NumAggValues; ++i)
2868     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2869                 SDValue(Agg.Val, Agg.getResNo() + i);
2870
2871   setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2872                                   &Values[0], NumAggValues));
2873 }
2874
2875 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2876   const Value *Op0 = I.getOperand(0);
2877   const Type *AggTy = Op0->getType();
2878   const Type *ValTy = I.getType();
2879   bool OutOfUndef = isa<UndefValue>(Op0);
2880
2881   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2882                                             I.idx_begin(), I.idx_end());
2883
2884   SmallVector<MVT, 4> ValValueVTs;
2885   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2886
2887   unsigned NumValValues = ValValueVTs.size();
2888   SmallVector<SDValue, 4> Values(NumValValues);
2889
2890   SDValue Agg = getValue(Op0);
2891   // Copy out the selected value(s).
2892   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2893     Values[i - LinearIndex] =
2894       OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.getResNo() + i)) :
2895                    SDValue(Agg.Val, Agg.getResNo() + i);
2896
2897   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2898                                   &Values[0], NumValValues));
2899 }
2900
2901
2902 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2903   SDValue N = getValue(I.getOperand(0));
2904   const Type *Ty = I.getOperand(0)->getType();
2905
2906   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2907        OI != E; ++OI) {
2908     Value *Idx = *OI;
2909     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2910       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2911       if (Field) {
2912         // N = N + Offset
2913         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2914         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2915                         DAG.getIntPtrConstant(Offset));
2916       }
2917       Ty = StTy->getElementType(Field);
2918     } else {
2919       Ty = cast<SequentialType>(Ty)->getElementType();
2920
2921       // If this is a constant subscript, handle it quickly.
2922       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2923         if (CI->getZExtValue() == 0) continue;
2924         uint64_t Offs = 
2925             TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2926         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2927                         DAG.getIntPtrConstant(Offs));
2928         continue;
2929       }
2930       
2931       // N = N + Idx * ElementSize;
2932       uint64_t ElementSize = TD->getABITypeSize(Ty);
2933       SDValue IdxN = getValue(Idx);
2934
2935       // If the index is smaller or larger than intptr_t, truncate or extend
2936       // it.
2937       if (IdxN.getValueType().bitsLT(N.getValueType()))
2938         IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2939       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2940         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2941
2942       // If this is a multiply by a power of two, turn it into a shl
2943       // immediately.  This is a very common case.
2944       if (ElementSize != 1) {
2945         if (isPowerOf2_64(ElementSize)) {
2946           unsigned Amt = Log2_64(ElementSize);
2947           IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2948                              DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2949         } else {
2950           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2951           IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2952         }
2953       }
2954
2955       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2956     }
2957   }
2958   setValue(&I, N);
2959 }
2960
2961 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2962   // If this is a fixed sized alloca in the entry block of the function,
2963   // allocate it statically on the stack.
2964   if (FuncInfo.StaticAllocaMap.count(&I))
2965     return;   // getValue will auto-populate this.
2966
2967   const Type *Ty = I.getAllocatedType();
2968   uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2969   unsigned Align =
2970     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2971              I.getAlignment());
2972
2973   SDValue AllocSize = getValue(I.getArraySize());
2974   MVT IntPtr = TLI.getPointerTy();
2975   if (IntPtr.bitsLT(AllocSize.getValueType()))
2976     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2977   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2978     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2979
2980   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2981                           DAG.getIntPtrConstant(TySize));
2982
2983   // Handle alignment.  If the requested alignment is less than or equal to
2984   // the stack alignment, ignore it.  If the size is greater than or equal to
2985   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2986   unsigned StackAlign =
2987     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2988   if (Align <= StackAlign)
2989     Align = 0;
2990
2991   // Round the size of the allocation up to the stack alignment size
2992   // by add SA-1 to the size.
2993   AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2994                           DAG.getIntPtrConstant(StackAlign-1));
2995   // Mask out the low bits for alignment purposes.
2996   AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2997                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2998
2999   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3000   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
3001                                                     MVT::Other);
3002   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
3003   setValue(&I, DSA);
3004   DAG.setRoot(DSA.getValue(1));
3005
3006   // Inform the Frame Information that we have just allocated a variable-sized
3007   // object.
3008   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
3009 }
3010
3011 void SelectionDAGLowering::visitLoad(LoadInst &I) {
3012   const Value *SV = I.getOperand(0);
3013   SDValue Ptr = getValue(SV);
3014
3015   const Type *Ty = I.getType();
3016   bool isVolatile = I.isVolatile();
3017   unsigned Alignment = I.getAlignment();
3018
3019   SmallVector<MVT, 4> ValueVTs;
3020   SmallVector<uint64_t, 4> Offsets;
3021   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3022   unsigned NumValues = ValueVTs.size();
3023   if (NumValues == 0)
3024     return;
3025
3026   SDValue Root;
3027   bool ConstantMemory = false;
3028   if (I.isVolatile())
3029     // Serialize volatile loads with other side effects.
3030     Root = getRoot();
3031   else if (AA->pointsToConstantMemory(SV)) {
3032     // Do not serialize (non-volatile) loads of constant memory with anything.
3033     Root = DAG.getEntryNode();
3034     ConstantMemory = true;
3035   } else {
3036     // Do not serialize non-volatile loads against each other.
3037     Root = DAG.getRoot();
3038   }
3039
3040   SmallVector<SDValue, 4> Values(NumValues);
3041   SmallVector<SDValue, 4> Chains(NumValues);
3042   MVT PtrVT = Ptr.getValueType();
3043   for (unsigned i = 0; i != NumValues; ++i) {
3044     SDValue L = DAG.getLoad(ValueVTs[i], Root,
3045                               DAG.getNode(ISD::ADD, PtrVT, Ptr,
3046                                           DAG.getConstant(Offsets[i], PtrVT)),
3047                               SV, Offsets[i],
3048                               isVolatile, Alignment);
3049     Values[i] = L;
3050     Chains[i] = L.getValue(1);
3051   }
3052   
3053   if (!ConstantMemory) {
3054     SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3055                                   &Chains[0], NumValues);
3056     if (isVolatile)
3057       DAG.setRoot(Chain);
3058     else
3059       PendingLoads.push_back(Chain);
3060   }
3061
3062   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
3063                                   &Values[0], NumValues));
3064 }
3065
3066
3067 void SelectionDAGLowering::visitStore(StoreInst &I) {
3068   Value *SrcV = I.getOperand(0);
3069   Value *PtrV = I.getOperand(1);
3070
3071   SmallVector<MVT, 4> ValueVTs;
3072   SmallVector<uint64_t, 4> Offsets;
3073   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3074   unsigned NumValues = ValueVTs.size();
3075   if (NumValues == 0)
3076     return;
3077
3078   // Get the lowered operands. Note that we do this after
3079   // checking if NumResults is zero, because with zero results
3080   // the operands won't have values in the map.
3081   SDValue Src = getValue(SrcV);
3082   SDValue Ptr = getValue(PtrV);
3083
3084   SDValue Root = getRoot();
3085   SmallVector<SDValue, 4> Chains(NumValues);
3086   MVT PtrVT = Ptr.getValueType();
3087   bool isVolatile = I.isVolatile();
3088   unsigned Alignment = I.getAlignment();
3089   for (unsigned i = 0; i != NumValues; ++i)
3090     Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.getResNo() + i),
3091                              DAG.getNode(ISD::ADD, PtrVT, Ptr,
3092                                          DAG.getConstant(Offsets[i], PtrVT)),
3093                              PtrV, Offsets[i],
3094                              isVolatile, Alignment);
3095
3096   DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
3097 }
3098
3099 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3100 /// node.
3101 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
3102                                                 unsigned Intrinsic) {
3103   bool HasChain = !I.doesNotAccessMemory();
3104   bool OnlyLoad = HasChain && I.onlyReadsMemory();
3105
3106   // Build the operand list.
3107   SmallVector<SDValue, 8> Ops;
3108   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3109     if (OnlyLoad) {
3110       // We don't need to serialize loads against other loads.
3111       Ops.push_back(DAG.getRoot());
3112     } else { 
3113       Ops.push_back(getRoot());
3114     }
3115   }
3116   
3117   // Add the intrinsic ID as an integer operand.
3118   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3119
3120   // Add all operands of the call to the operand list.
3121   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3122     SDValue Op = getValue(I.getOperand(i));
3123     assert(TLI.isTypeLegal(Op.getValueType()) &&
3124            "Intrinsic uses a non-legal type?");
3125     Ops.push_back(Op);
3126   }
3127
3128   std::vector<MVT> VTs;
3129   if (I.getType() != Type::VoidTy) {
3130     MVT VT = TLI.getValueType(I.getType());
3131     if (VT.isVector()) {
3132       const VectorType *DestTy = cast<VectorType>(I.getType());
3133       MVT EltVT = TLI.getValueType(DestTy->getElementType());
3134       
3135       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
3136       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3137     }
3138     
3139     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3140     VTs.push_back(VT);
3141   }
3142   if (HasChain)
3143     VTs.push_back(MVT::Other);
3144
3145   const MVT *VTList = DAG.getNodeValueTypes(VTs);
3146
3147   // Create the node.
3148   SDValue Result;
3149   if (!HasChain)
3150     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3151                          &Ops[0], Ops.size());
3152   else if (I.getType() != Type::VoidTy)
3153     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3154                          &Ops[0], Ops.size());
3155   else
3156     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3157                          &Ops[0], Ops.size());
3158
3159   if (HasChain) {
3160     SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
3161     if (OnlyLoad)
3162       PendingLoads.push_back(Chain);
3163     else
3164       DAG.setRoot(Chain);
3165   }
3166   if (I.getType() != Type::VoidTy) {
3167     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3168       MVT VT = TLI.getValueType(PTy);
3169       Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3170     } 
3171     setValue(&I, Result);
3172   }
3173 }
3174
3175 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3176 static GlobalVariable *ExtractTypeInfo (Value *V) {
3177   V = V->stripPointerCasts();
3178   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3179   assert ((GV || isa<ConstantPointerNull>(V)) &&
3180           "TypeInfo must be a global variable or NULL");
3181   return GV;
3182 }
3183
3184 /// addCatchInfo - Extract the personality and type infos from an eh.selector
3185 /// call, and add them to the specified machine basic block.
3186 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3187                          MachineBasicBlock *MBB) {
3188   // Inform the MachineModuleInfo of the personality for this landing pad.
3189   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3190   assert(CE->getOpcode() == Instruction::BitCast &&
3191          isa<Function>(CE->getOperand(0)) &&
3192          "Personality should be a function");
3193   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3194
3195   // Gather all the type infos for this landing pad and pass them along to
3196   // MachineModuleInfo.
3197   std::vector<GlobalVariable *> TyInfo;
3198   unsigned N = I.getNumOperands();
3199
3200   for (unsigned i = N - 1; i > 2; --i) {
3201     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3202       unsigned FilterLength = CI->getZExtValue();
3203       unsigned FirstCatch = i + FilterLength + !FilterLength;
3204       assert (FirstCatch <= N && "Invalid filter length");
3205
3206       if (FirstCatch < N) {
3207         TyInfo.reserve(N - FirstCatch);
3208         for (unsigned j = FirstCatch; j < N; ++j)
3209           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3210         MMI->addCatchTypeInfo(MBB, TyInfo);
3211         TyInfo.clear();
3212       }
3213
3214       if (!FilterLength) {
3215         // Cleanup.
3216         MMI->addCleanup(MBB);
3217       } else {
3218         // Filter.
3219         TyInfo.reserve(FilterLength - 1);
3220         for (unsigned j = i + 1; j < FirstCatch; ++j)
3221           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3222         MMI->addFilterTypeInfo(MBB, TyInfo);
3223         TyInfo.clear();
3224       }
3225
3226       N = i;
3227     }
3228   }
3229
3230   if (N > 3) {
3231     TyInfo.reserve(N - 3);
3232     for (unsigned j = 3; j < N; ++j)
3233       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3234     MMI->addCatchTypeInfo(MBB, TyInfo);
3235   }
3236 }
3237
3238
3239 /// Inlined utility function to implement binary input atomic intrinsics for 
3240 // visitIntrinsicCall: I is a call instruction
3241 //                     Op is the associated NodeType for I
3242 const char *
3243 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3244   SDValue Root = getRoot();   
3245   SDValue L = DAG.getAtomic(Op, Root, 
3246                               getValue(I.getOperand(1)), 
3247                               getValue(I.getOperand(2)),
3248                               I.getOperand(1));
3249   setValue(&I, L);
3250   DAG.setRoot(L.getValue(1));
3251   return 0;
3252 }
3253
3254 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3255 /// we want to emit this as a call to a named external function, return the name
3256 /// otherwise lower it and return null.
3257 const char *
3258 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3259   switch (Intrinsic) {
3260   default:
3261     // By default, turn this into a target intrinsic node.
3262     visitTargetIntrinsic(I, Intrinsic);
3263     return 0;
3264   case Intrinsic::vastart:  visitVAStart(I); return 0;
3265   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3266   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3267   case Intrinsic::returnaddress:
3268     setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3269                              getValue(I.getOperand(1))));
3270     return 0;
3271   case Intrinsic::frameaddress:
3272     setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3273                              getValue(I.getOperand(1))));
3274     return 0;
3275   case Intrinsic::setjmp:
3276     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3277     break;
3278   case Intrinsic::longjmp:
3279     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3280     break;
3281   case Intrinsic::memcpy_i32:
3282   case Intrinsic::memcpy_i64: {
3283     SDValue Op1 = getValue(I.getOperand(1));
3284     SDValue Op2 = getValue(I.getOperand(2));
3285     SDValue Op3 = getValue(I.getOperand(3));
3286     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3287     DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3288                               I.getOperand(1), 0, I.getOperand(2), 0));
3289     return 0;
3290   }
3291   case Intrinsic::memset_i32:
3292   case Intrinsic::memset_i64: {
3293     SDValue Op1 = getValue(I.getOperand(1));
3294     SDValue Op2 = getValue(I.getOperand(2));
3295     SDValue Op3 = getValue(I.getOperand(3));
3296     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3297     DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3298                               I.getOperand(1), 0));
3299     return 0;
3300   }
3301   case Intrinsic::memmove_i32:
3302   case Intrinsic::memmove_i64: {
3303     SDValue Op1 = getValue(I.getOperand(1));
3304     SDValue Op2 = getValue(I.getOperand(2));
3305     SDValue Op3 = getValue(I.getOperand(3));
3306     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3307
3308     // If the source and destination are known to not be aliases, we can
3309     // lower memmove as memcpy.
3310     uint64_t Size = -1ULL;
3311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3312       Size = C->getValue();
3313     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3314         AliasAnalysis::NoAlias) {
3315       DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3316                                 I.getOperand(1), 0, I.getOperand(2), 0));
3317       return 0;
3318     }
3319
3320     DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3321                                I.getOperand(1), 0, I.getOperand(2), 0));
3322     return 0;
3323   }
3324   case Intrinsic::dbg_stoppoint: {
3325     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3326     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3327     if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3328       DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3329       assert(DD && "Not a debug information descriptor");
3330       DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3331                                       SPI.getLine(),
3332                                       SPI.getColumn(),
3333                                       cast<CompileUnitDesc>(DD)));
3334     }
3335
3336     return 0;
3337   }
3338   case Intrinsic::dbg_region_start: {
3339     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3340     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3341     if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3342       unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3343       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3344     }
3345
3346     return 0;
3347   }
3348   case Intrinsic::dbg_region_end: {
3349     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3350     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3351     if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3352       unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3353       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3354     }
3355
3356     return 0;
3357   }
3358   case Intrinsic::dbg_func_start: {
3359     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3360     if (!MMI) return 0;
3361     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3362     Value *SP = FSI.getSubprogram();
3363     if (SP && MMI->Verify(SP)) {
3364       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3365       // what (most?) gdb expects.
3366       DebugInfoDesc *DD = MMI->getDescFor(SP);
3367       assert(DD && "Not a debug information descriptor");
3368       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3369       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3370       unsigned SrcFile = MMI->RecordSource(CompileUnit);
3371       // Record the source line but does create a label. It will be emitted
3372       // at asm emission time.
3373       MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3374     }
3375
3376     return 0;
3377   }
3378   case Intrinsic::dbg_declare: {
3379     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3380     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3381     Value *Variable = DI.getVariable();
3382     if (MMI && Variable && MMI->Verify(Variable))
3383       DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3384                               getValue(DI.getAddress()), getValue(Variable)));
3385     return 0;
3386   }
3387     
3388   case Intrinsic::eh_exception: {
3389     if (!CurMBB->isLandingPad()) {
3390       // FIXME: Mark exception register as live in.  Hack for PR1508.
3391       unsigned Reg = TLI.getExceptionAddressRegister();
3392       if (Reg) CurMBB->addLiveIn(Reg);
3393     }
3394     // Insert the EXCEPTIONADDR instruction.
3395     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3396     SDValue Ops[1];
3397     Ops[0] = DAG.getRoot();
3398     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3399     setValue(&I, Op);
3400     DAG.setRoot(Op.getValue(1));
3401     return 0;
3402   }
3403
3404   case Intrinsic::eh_selector_i32:
3405   case Intrinsic::eh_selector_i64: {
3406     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3407     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3408                          MVT::i32 : MVT::i64);
3409     
3410     if (MMI) {
3411       if (CurMBB->isLandingPad())
3412         addCatchInfo(I, MMI, CurMBB);
3413       else {
3414 #ifndef NDEBUG
3415         FuncInfo.CatchInfoLost.insert(&I);
3416 #endif
3417         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
3418         unsigned Reg = TLI.getExceptionSelectorRegister();
3419         if (Reg) CurMBB->addLiveIn(Reg);
3420       }
3421
3422       // Insert the EHSELECTION instruction.
3423       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3424       SDValue Ops[2];
3425       Ops[0] = getValue(I.getOperand(1));
3426       Ops[1] = getRoot();
3427       SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3428       setValue(&I, Op);
3429       DAG.setRoot(Op.getValue(1));
3430     } else {
3431       setValue(&I, DAG.getConstant(0, VT));
3432     }
3433     
3434     return 0;
3435   }
3436
3437   case Intrinsic::eh_typeid_for_i32:
3438   case Intrinsic::eh_typeid_for_i64: {
3439     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3440     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3441                          MVT::i32 : MVT::i64);
3442     
3443     if (MMI) {
3444       // Find the type id for the given typeinfo.
3445       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3446
3447       unsigned TypeID = MMI->getTypeIDFor(GV);
3448       setValue(&I, DAG.getConstant(TypeID, VT));
3449     } else {
3450       // Return something different to eh_selector.
3451       setValue(&I, DAG.getConstant(1, VT));
3452     }
3453
3454     return 0;
3455   }
3456
3457   case Intrinsic::eh_return: {
3458     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3459
3460     if (MMI) {
3461       MMI->setCallsEHReturn(true);
3462       DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3463                               MVT::Other,
3464                               getControlRoot(),
3465                               getValue(I.getOperand(1)),
3466                               getValue(I.getOperand(2))));
3467     } else {
3468       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3469     }
3470
3471     return 0;
3472   }
3473
3474    case Intrinsic::eh_unwind_init: {    
3475      if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3476        MMI->setCallsUnwindInit(true);
3477      }
3478
3479      return 0;
3480    }
3481
3482    case Intrinsic::eh_dwarf_cfa: {
3483      MVT VT = getValue(I.getOperand(1)).getValueType();
3484      SDValue CfaArg;
3485      if (VT.bitsGT(TLI.getPointerTy()))
3486        CfaArg = DAG.getNode(ISD::TRUNCATE,
3487                             TLI.getPointerTy(), getValue(I.getOperand(1)));
3488      else
3489        CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3490                             TLI.getPointerTy(), getValue(I.getOperand(1)));
3491
3492      SDValue Offset = DAG.getNode(ISD::ADD,
3493                                     TLI.getPointerTy(),
3494                                     DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3495                                                 TLI.getPointerTy()),
3496                                     CfaArg);
3497      setValue(&I, DAG.getNode(ISD::ADD,
3498                               TLI.getPointerTy(),
3499                               DAG.getNode(ISD::FRAMEADDR,
3500                                           TLI.getPointerTy(),
3501                                           DAG.getConstant(0,
3502                                                           TLI.getPointerTy())),
3503                               Offset));
3504      return 0;
3505   }
3506
3507   case Intrinsic::sqrt:
3508     setValue(&I, DAG.getNode(ISD::FSQRT,
3509                              getValue(I.getOperand(1)).getValueType(),
3510                              getValue(I.getOperand(1))));
3511     return 0;
3512   case Intrinsic::powi:
3513     setValue(&I, DAG.getNode(ISD::FPOWI,
3514                              getValue(I.getOperand(1)).getValueType(),
3515                              getValue(I.getOperand(1)),
3516                              getValue(I.getOperand(2))));
3517     return 0;
3518   case Intrinsic::sin:
3519     setValue(&I, DAG.getNode(ISD::FSIN,
3520                              getValue(I.getOperand(1)).getValueType(),
3521                              getValue(I.getOperand(1))));
3522     return 0;
3523   case Intrinsic::cos:
3524     setValue(&I, DAG.getNode(ISD::FCOS,
3525                              getValue(I.getOperand(1)).getValueType(),
3526                              getValue(I.getOperand(1))));
3527     return 0;
3528   case Intrinsic::pow:
3529     setValue(&I, DAG.getNode(ISD::FPOW,
3530                              getValue(I.getOperand(1)).getValueType(),
3531                              getValue(I.getOperand(1)),
3532                              getValue(I.getOperand(2))));
3533     return 0;
3534   case Intrinsic::pcmarker: {
3535     SDValue Tmp = getValue(I.getOperand(1));
3536     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3537     return 0;
3538   }
3539   case Intrinsic::readcyclecounter: {
3540     SDValue Op = getRoot();
3541     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3542                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3543                                 &Op, 1);
3544     setValue(&I, Tmp);
3545     DAG.setRoot(Tmp.getValue(1));
3546     return 0;
3547   }
3548   case Intrinsic::part_select: {
3549     // Currently not implemented: just abort
3550     assert(0 && "part_select intrinsic not implemented");
3551     abort();
3552   }
3553   case Intrinsic::part_set: {
3554     // Currently not implemented: just abort
3555     assert(0 && "part_set intrinsic not implemented");
3556     abort();
3557   }
3558   case Intrinsic::bswap:
3559     setValue(&I, DAG.getNode(ISD::BSWAP,
3560                              getValue(I.getOperand(1)).getValueType(),
3561                              getValue(I.getOperand(1))));
3562     return 0;
3563   case Intrinsic::cttz: {
3564     SDValue Arg = getValue(I.getOperand(1));
3565     MVT Ty = Arg.getValueType();
3566     SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3567     setValue(&I, result);
3568     return 0;
3569   }
3570   case Intrinsic::ctlz: {
3571     SDValue Arg = getValue(I.getOperand(1));
3572     MVT Ty = Arg.getValueType();
3573     SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3574     setValue(&I, result);
3575     return 0;
3576   }
3577   case Intrinsic::ctpop: {
3578     SDValue Arg = getValue(I.getOperand(1));
3579     MVT Ty = Arg.getValueType();
3580     SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3581     setValue(&I, result);
3582     return 0;
3583   }
3584   case Intrinsic::stacksave: {
3585     SDValue Op = getRoot();
3586     SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3587               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3588     setValue(&I, Tmp);
3589     DAG.setRoot(Tmp.getValue(1));
3590     return 0;
3591   }
3592   case Intrinsic::stackrestore: {
3593     SDValue Tmp = getValue(I.getOperand(1));
3594     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3595     return 0;
3596   }
3597   case Intrinsic::var_annotation:
3598     // Discard annotate attributes
3599     return 0;
3600
3601   case Intrinsic::init_trampoline: {
3602     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3603
3604     SDValue Ops[6];
3605     Ops[0] = getRoot();
3606     Ops[1] = getValue(I.getOperand(1));
3607     Ops[2] = getValue(I.getOperand(2));
3608     Ops[3] = getValue(I.getOperand(3));
3609     Ops[4] = DAG.getSrcValue(I.getOperand(1));
3610     Ops[5] = DAG.getSrcValue(F);
3611
3612     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3613                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
3614                                                       MVT::Other), 2,
3615                                 Ops, 6);
3616
3617     setValue(&I, Tmp);
3618     DAG.setRoot(Tmp.getValue(1));
3619     return 0;
3620   }
3621
3622   case Intrinsic::gcroot:
3623     if (GFI) {
3624       Value *Alloca = I.getOperand(1);
3625       Constant *TypeMap = cast<Constant>(I.getOperand(2));
3626       
3627       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3628       GFI->addStackRoot(FI->getIndex(), TypeMap);
3629     }
3630     return 0;
3631
3632   case Intrinsic::gcread:
3633   case Intrinsic::gcwrite:
3634     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3635     return 0;
3636
3637   case Intrinsic::flt_rounds: {
3638     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3639     return 0;
3640   }
3641
3642   case Intrinsic::trap: {
3643     DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3644     return 0;
3645   }
3646   case Intrinsic::prefetch: {
3647     SDValue Ops[4];
3648     Ops[0] = getRoot();
3649     Ops[1] = getValue(I.getOperand(1));
3650     Ops[2] = getValue(I.getOperand(2));
3651     Ops[3] = getValue(I.getOperand(3));
3652     DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3653     return 0;
3654   }
3655   
3656   case Intrinsic::memory_barrier: {
3657     SDValue Ops[6];
3658     Ops[0] = getRoot();
3659     for (int x = 1; x < 6; ++x)
3660       Ops[x] = getValue(I.getOperand(x));
3661
3662     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3663     return 0;
3664   }
3665   case Intrinsic::atomic_cmp_swap: {
3666     SDValue Root = getRoot();   
3667     SDValue L;
3668     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3669       case MVT::i8:
3670         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root, 
3671                           getValue(I.getOperand(1)), 
3672                           getValue(I.getOperand(2)),
3673                           getValue(I.getOperand(3)),
3674                           I.getOperand(1));
3675         break;
3676       case MVT::i16:
3677         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root, 
3678                           getValue(I.getOperand(1)), 
3679                           getValue(I.getOperand(2)),
3680                           getValue(I.getOperand(3)),
3681                           I.getOperand(1));
3682         break;
3683       case MVT::i32:
3684         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root, 
3685                           getValue(I.getOperand(1)), 
3686                           getValue(I.getOperand(2)),
3687                           getValue(I.getOperand(3)),
3688                           I.getOperand(1));
3689         break;
3690       case MVT::i64:
3691         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root, 
3692                           getValue(I.getOperand(1)), 
3693                           getValue(I.getOperand(2)),
3694                           getValue(I.getOperand(3)),
3695                           I.getOperand(1));
3696         break;
3697       default:
3698        assert(0 && "Invalid atomic type");
3699        abort();
3700     }
3701     setValue(&I, L);
3702     DAG.setRoot(L.getValue(1));
3703     return 0;
3704   }
3705   case Intrinsic::atomic_load_add:
3706     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3707       case MVT::i8:
3708         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3709       case MVT::i16:
3710         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3711       case MVT::i32:
3712         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3713       case MVT::i64:
3714         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3715       default:
3716        assert(0 && "Invalid atomic type");
3717        abort();
3718     }
3719   case Intrinsic::atomic_load_sub:
3720     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3721       case MVT::i8:
3722         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3723       case MVT::i16:
3724         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3725       case MVT::i32:
3726         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3727       case MVT::i64:
3728         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3729       default:
3730        assert(0 && "Invalid atomic type");
3731        abort();
3732     }
3733   case Intrinsic::atomic_load_or:
3734     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3735       case MVT::i8:
3736         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3737       case MVT::i16:
3738         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3739       case MVT::i32:
3740         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3741       case MVT::i64:
3742         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3743       default:
3744        assert(0 && "Invalid atomic type");
3745        abort();
3746     }
3747   case Intrinsic::atomic_load_xor:
3748     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3749       case MVT::i8:
3750         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3751       case MVT::i16:
3752         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3753       case MVT::i32:
3754         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3755       case MVT::i64:
3756         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3757       default:
3758        assert(0 && "Invalid atomic type");
3759        abort();
3760     }
3761   case Intrinsic::atomic_load_and:
3762     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3763       case MVT::i8:
3764         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3765       case MVT::i16:
3766         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3767       case MVT::i32:
3768         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3769       case MVT::i64:
3770         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3771       default:
3772        assert(0 && "Invalid atomic type");
3773        abort();
3774     }
3775   case Intrinsic::atomic_load_nand:
3776     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3777       case MVT::i8:
3778         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3779       case MVT::i16:
3780         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3781       case MVT::i32:
3782         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3783       case MVT::i64:
3784         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3785       default:
3786        assert(0 && "Invalid atomic type");
3787        abort();
3788     }
3789   case Intrinsic::atomic_load_max:
3790     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3791       case MVT::i8:
3792         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3793       case MVT::i16:
3794         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3795       case MVT::i32:
3796         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3797       case MVT::i64:
3798         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3799       default:
3800        assert(0 && "Invalid atomic type");
3801        abort();
3802     }
3803   case Intrinsic::atomic_load_min:
3804     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3805       case MVT::i8:
3806         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3807       case MVT::i16:
3808         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3809       case MVT::i32:
3810         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3811       case MVT::i64:
3812         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3813       default:
3814        assert(0 && "Invalid atomic type");
3815        abort();
3816     }
3817   case Intrinsic::atomic_load_umin:
3818     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3819       case MVT::i8:
3820         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3821       case MVT::i16:
3822         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3823       case MVT::i32:
3824         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3825       case MVT::i64:
3826         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3827       default:
3828        assert(0 && "Invalid atomic type");
3829        abort();
3830     }
3831   case Intrinsic::atomic_load_umax:
3832     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3833       case MVT::i8:
3834         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
3835       case MVT::i16:
3836         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
3837       case MVT::i32:
3838         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
3839       case MVT::i64:
3840         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
3841       default:
3842        assert(0 && "Invalid atomic type");
3843        abort();
3844     }
3845   case Intrinsic::atomic_swap:
3846     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3847       case MVT::i8:
3848         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
3849       case MVT::i16:
3850         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
3851       case MVT::i32:
3852         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
3853       case MVT::i64:
3854         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
3855       default:
3856        assert(0 && "Invalid atomic type");
3857        abort();
3858     }
3859   }
3860 }
3861
3862
3863 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
3864                                        bool IsTailCall,
3865                                        MachineBasicBlock *LandingPad) {
3866   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3867   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3868   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3869   unsigned BeginLabel = 0, EndLabel = 0;
3870
3871   TargetLowering::ArgListTy Args;
3872   TargetLowering::ArgListEntry Entry;
3873   Args.reserve(CS.arg_size());
3874   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3875        i != e; ++i) {
3876     SDValue ArgNode = getValue(*i);
3877     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3878
3879     unsigned attrInd = i - CS.arg_begin() + 1;
3880     Entry.isSExt  = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3881     Entry.isZExt  = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3882     Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3883     Entry.isSRet  = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3884     Entry.isNest  = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3885     Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3886     Entry.Alignment = CS.getParamAlignment(attrInd);
3887     Args.push_back(Entry);
3888   }
3889
3890   if (LandingPad && MMI) {
3891     // Insert a label before the invoke call to mark the try range.  This can be
3892     // used to detect deletion of the invoke via the MachineModuleInfo.
3893     BeginLabel = MMI->NextLabelID();
3894     // Both PendingLoads and PendingExports must be flushed here;
3895     // this call might not return.
3896     (void)getRoot();
3897     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3898   }
3899
3900   std::pair<SDValue,SDValue> Result =
3901     TLI.LowerCallTo(getRoot(), CS.getType(),
3902                     CS.paramHasAttr(0, ParamAttr::SExt),
3903                     CS.paramHasAttr(0, ParamAttr::ZExt),
3904                     FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3905                     Callee, Args, DAG);
3906   if (CS.getType() != Type::VoidTy)
3907     setValue(CS.getInstruction(), Result.first);
3908   DAG.setRoot(Result.second);
3909
3910   if (LandingPad && MMI) {
3911     // Insert a label at the end of the invoke call to mark the try range.  This
3912     // can be used to detect deletion of the invoke via the MachineModuleInfo.
3913     EndLabel = MMI->NextLabelID();
3914     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3915
3916     // Inform MachineModuleInfo of range.
3917     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3918   }
3919 }
3920
3921
3922 void SelectionDAGLowering::visitCall(CallInst &I) {
3923   const char *RenameFn = 0;
3924   if (Function *F = I.getCalledFunction()) {
3925     if (F->isDeclaration()) {
3926       if (unsigned IID = F->getIntrinsicID()) {
3927         RenameFn = visitIntrinsicCall(I, IID);
3928         if (!RenameFn)
3929           return;
3930       }
3931     }
3932
3933     // Check for well-known libc/libm calls.  If the function is internal, it
3934     // can't be a library call.
3935     unsigned NameLen = F->getNameLen();
3936     if (!F->hasInternalLinkage() && NameLen) {
3937       const char *NameStr = F->getNameStart();
3938       if (NameStr[0] == 'c' &&
3939           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3940            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3941         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
3942             I.getOperand(1)->getType()->isFloatingPoint() &&
3943             I.getType() == I.getOperand(1)->getType() &&
3944             I.getType() == I.getOperand(2)->getType()) {
3945           SDValue LHS = getValue(I.getOperand(1));
3946           SDValue RHS = getValue(I.getOperand(2));
3947           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3948                                    LHS, RHS));
3949           return;
3950         }
3951       } else if (NameStr[0] == 'f' &&
3952                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3953                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3954                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3955         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3956             I.getOperand(1)->getType()->isFloatingPoint() &&
3957             I.getType() == I.getOperand(1)->getType()) {
3958           SDValue Tmp = getValue(I.getOperand(1));
3959           setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3960           return;
3961         }
3962       } else if (NameStr[0] == 's' && 
3963                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3964                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3965                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3966         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3967             I.getOperand(1)->getType()->isFloatingPoint() &&
3968             I.getType() == I.getOperand(1)->getType()) {
3969           SDValue Tmp = getValue(I.getOperand(1));
3970           setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3971           return;
3972         }
3973       } else if (NameStr[0] == 'c' &&
3974                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3975                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3976                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3977         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3978             I.getOperand(1)->getType()->isFloatingPoint() &&
3979             I.getType() == I.getOperand(1)->getType()) {
3980           SDValue Tmp = getValue(I.getOperand(1));
3981           setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3982           return;
3983         }
3984       }
3985     }
3986   } else if (isa<InlineAsm>(I.getOperand(0))) {
3987     visitInlineAsm(&I);
3988     return;
3989   }
3990
3991   SDValue Callee;
3992   if (!RenameFn)
3993     Callee = getValue(I.getOperand(0));
3994   else
3995     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3996
3997   LowerCallTo(&I, Callee, I.isTailCall());
3998 }
3999
4000
4001 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4002 /// this value and returns the result as a ValueVT value.  This uses 
4003 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4004 /// If the Flag pointer is NULL, no flag is used.
4005 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 
4006                                       SDValue &Chain,
4007                                       SDValue *Flag) const {
4008   // Assemble the legal parts into the final values.
4009   SmallVector<SDValue, 4> Values(ValueVTs.size());
4010   SmallVector<SDValue, 8> Parts;
4011   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4012     // Copy the legal parts from the registers.
4013     MVT ValueVT = ValueVTs[Value];
4014     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4015     MVT RegisterVT = RegVTs[Value];
4016
4017     Parts.resize(Part + NumRegs);
4018     for (unsigned i = 0; i != NumRegs; ++i) {
4019       SDValue P;
4020       if (Flag == 0)
4021         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4022       else {
4023         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4024         *Flag = P.getValue(2);
4025       }
4026       Chain = P.getValue(1);
4027       
4028       // If the source register was virtual and if we know something about it,
4029       // add an assert node.
4030       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4031           RegisterVT.isInteger() && !RegisterVT.isVector()) {
4032         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4033         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4034         if (FLI.LiveOutRegInfo.size() > SlotNo) {
4035           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4036           
4037           unsigned RegSize = RegisterVT.getSizeInBits();
4038           unsigned NumSignBits = LOI.NumSignBits;
4039           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4040           
4041           // FIXME: We capture more information than the dag can represent.  For
4042           // now, just use the tightest assertzext/assertsext possible.
4043           bool isSExt = true;
4044           MVT FromVT(MVT::Other);
4045           if (NumSignBits == RegSize)
4046             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
4047           else if (NumZeroBits >= RegSize-1)
4048             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
4049           else if (NumSignBits > RegSize-8)
4050             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
4051           else if (NumZeroBits >= RegSize-9)
4052             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
4053           else if (NumSignBits > RegSize-16)
4054             isSExt = true, FromVT = MVT::i16;   // ASSERT SEXT 16
4055           else if (NumZeroBits >= RegSize-17)
4056             isSExt = false, FromVT = MVT::i16;  // ASSERT ZEXT 16
4057           else if (NumSignBits > RegSize-32)
4058             isSExt = true, FromVT = MVT::i32;   // ASSERT SEXT 32
4059           else if (NumZeroBits >= RegSize-33)
4060             isSExt = false, FromVT = MVT::i32;  // ASSERT ZEXT 32
4061           
4062           if (FromVT != MVT::Other) {
4063             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4064                             RegisterVT, P, DAG.getValueType(FromVT));
4065
4066           }
4067         }
4068       }
4069       
4070       Parts[Part+i] = P;
4071     }
4072   
4073     Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
4074                                      ValueVT);
4075     Part += NumRegs;
4076   }
4077
4078   return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4079                             &Values[0], ValueVTs.size());
4080 }
4081
4082 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4083 /// specified value into the registers specified by this object.  This uses 
4084 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4085 /// If the Flag pointer is NULL, no flag is used.
4086 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4087                                  SDValue &Chain, SDValue *Flag) const {
4088   // Get the list of the values's legal parts.
4089   unsigned NumRegs = Regs.size();
4090   SmallVector<SDValue, 8> Parts(NumRegs);
4091   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4092     MVT ValueVT = ValueVTs[Value];
4093     unsigned NumParts = TLI->getNumRegisters(ValueVT);
4094     MVT RegisterVT = RegVTs[Value];
4095
4096     getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4097                    &Parts[Part], NumParts, RegisterVT);
4098     Part += NumParts;
4099   }
4100
4101   // Copy the parts into the registers.
4102   SmallVector<SDValue, 8> Chains(NumRegs);
4103   for (unsigned i = 0; i != NumRegs; ++i) {
4104     SDValue Part;
4105     if (Flag == 0)
4106       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4107     else {
4108       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4109       *Flag = Part.getValue(1);
4110     }
4111     Chains[i] = Part.getValue(0);
4112   }
4113   
4114   if (NumRegs == 1 || Flag)
4115     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 
4116     // flagged to it. That is the CopyToReg nodes and the user are considered
4117     // a single scheduling unit. If we create a TokenFactor and return it as
4118     // chain, then the TokenFactor is both a predecessor (operand) of the
4119     // user as well as a successor (the TF operands are flagged to the user).
4120     // c1, f1 = CopyToReg
4121     // c2, f2 = CopyToReg
4122     // c3     = TokenFactor c1, c2
4123     // ...
4124     //        = op c3, ..., f2
4125     Chain = Chains[NumRegs-1];
4126   else
4127     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4128 }
4129
4130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4131 /// operand list.  This adds the code marker and includes the number of 
4132 /// values added into it.
4133 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4134                                         std::vector<SDValue> &Ops) const {
4135   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4136   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4137   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4138     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4139     MVT RegisterVT = RegVTs[Value];
4140     for (unsigned i = 0; i != NumRegs; ++i)
4141       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4142   }
4143 }
4144
4145 /// isAllocatableRegister - If the specified register is safe to allocate, 
4146 /// i.e. it isn't a stack pointer or some other special register, return the
4147 /// register class for the register.  Otherwise, return null.
4148 static const TargetRegisterClass *
4149 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4150                       const TargetLowering &TLI,
4151                       const TargetRegisterInfo *TRI) {
4152   MVT FoundVT = MVT::Other;
4153   const TargetRegisterClass *FoundRC = 0;
4154   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4155        E = TRI->regclass_end(); RCI != E; ++RCI) {
4156     MVT ThisVT = MVT::Other;
4157
4158     const TargetRegisterClass *RC = *RCI;
4159     // If none of the the value types for this register class are valid, we 
4160     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4161     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4162          I != E; ++I) {
4163       if (TLI.isTypeLegal(*I)) {
4164         // If we have already found this register in a different register class,
4165         // choose the one with the largest VT specified.  For example, on
4166         // PowerPC, we favor f64 register classes over f32.
4167         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4168           ThisVT = *I;
4169           break;
4170         }
4171       }
4172     }
4173     
4174     if (ThisVT == MVT::Other) continue;
4175     
4176     // NOTE: This isn't ideal.  In particular, this might allocate the
4177     // frame pointer in functions that need it (due to them not being taken
4178     // out of allocation, because a variable sized allocation hasn't been seen
4179     // yet).  This is a slight code pessimization, but should still work.
4180     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4181          E = RC->allocation_order_end(MF); I != E; ++I)
4182       if (*I == Reg) {
4183         // We found a matching register class.  Keep looking at others in case
4184         // we find one with larger registers that this physreg is also in.
4185         FoundRC = RC;
4186         FoundVT = ThisVT;
4187         break;
4188       }
4189   }
4190   return FoundRC;
4191 }    
4192
4193
4194 namespace {
4195 /// AsmOperandInfo - This contains information for each constraint that we are
4196 /// lowering.
4197 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
4198   /// CallOperand - If this is the result output operand or a clobber
4199   /// this is null, otherwise it is the incoming operand to the CallInst.
4200   /// This gets modified as the asm is processed.
4201   SDValue CallOperand;
4202
4203   /// AssignedRegs - If this is a register or register class operand, this
4204   /// contains the set of register corresponding to the operand.
4205   RegsForValue AssignedRegs;
4206   
4207   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4208     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4209   }
4210   
4211   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4212   /// busy in OutputRegs/InputRegs.
4213   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4214                          std::set<unsigned> &OutputRegs, 
4215                          std::set<unsigned> &InputRegs,
4216                          const TargetRegisterInfo &TRI) const {
4217     if (isOutReg) {
4218       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4219         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4220     }
4221     if (isInReg) {
4222       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4223         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4224     }
4225   }
4226   
4227 private:
4228   /// MarkRegAndAliases - Mark the specified register and all aliases in the
4229   /// specified set.
4230   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 
4231                                 const TargetRegisterInfo &TRI) {
4232     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4233     Regs.insert(Reg);
4234     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4235       for (; *Aliases; ++Aliases)
4236         Regs.insert(*Aliases);
4237   }
4238 };
4239 } // end anon namespace.
4240
4241
4242 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4243 /// specified operand.  We prefer to assign virtual registers, to allow the
4244 /// register allocator handle the assignment process.  However, if the asm uses
4245 /// features that we can't model on machineinstrs, we have SDISel do the
4246 /// allocation.  This produces generally horrible, but correct, code.
4247 ///
4248 ///   OpInfo describes the operand.
4249 ///   HasEarlyClobber is true if there are any early clobber constraints (=&r)
4250 ///     or any explicitly clobbered registers.
4251 ///   Input and OutputRegs are the set of already allocated physical registers.
4252 ///
4253 void SelectionDAGLowering::
4254 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
4255                      std::set<unsigned> &OutputRegs, 
4256                      std::set<unsigned> &InputRegs) {
4257   // Compute whether this value requires an input register, an output register,
4258   // or both.
4259   bool isOutReg = false;
4260   bool isInReg = false;
4261   switch (OpInfo.Type) {
4262   case InlineAsm::isOutput:
4263     isOutReg = true;
4264     
4265     // If this is an early-clobber output, or if there is an input
4266     // constraint that matches this, we need to reserve the input register
4267     // so no other inputs allocate to it.
4268     isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
4269     break;
4270   case InlineAsm::isInput:
4271     isInReg = true;
4272     isOutReg = false;
4273     break;
4274   case InlineAsm::isClobber:
4275     isOutReg = true;
4276     isInReg = true;
4277     break;
4278   }
4279   
4280   
4281   MachineFunction &MF = DAG.getMachineFunction();
4282   SmallVector<unsigned, 4> Regs;
4283   
4284   // If this is a constraint for a single physreg, or a constraint for a
4285   // register class, find it.
4286   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
4287     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4288                                      OpInfo.ConstraintVT);
4289
4290   unsigned NumRegs = 1;
4291   if (OpInfo.ConstraintVT != MVT::Other)
4292     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4293   MVT RegVT;
4294   MVT ValueVT = OpInfo.ConstraintVT;
4295   
4296
4297   // If this is a constraint for a specific physical register, like {r17},
4298   // assign it now.
4299   if (PhysReg.first) {
4300     if (OpInfo.ConstraintVT == MVT::Other)
4301       ValueVT = *PhysReg.second->vt_begin();
4302     
4303     // Get the actual register value type.  This is important, because the user
4304     // may have asked for (e.g.) the AX register in i32 type.  We need to
4305     // remember that AX is actually i16 to get the right extension.
4306     RegVT = *PhysReg.second->vt_begin();
4307     
4308     // This is a explicit reference to a physical register.
4309     Regs.push_back(PhysReg.first);
4310
4311     // If this is an expanded reference, add the rest of the regs to Regs.
4312     if (NumRegs != 1) {
4313       TargetRegisterClass::iterator I = PhysReg.second->begin();
4314       for (; *I != PhysReg.first; ++I)
4315         assert(I != PhysReg.second->end() && "Didn't find reg!"); 
4316       
4317       // Already added the first reg.
4318       --NumRegs; ++I;
4319       for (; NumRegs; --NumRegs, ++I) {
4320         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4321         Regs.push_back(*I);
4322       }
4323     }
4324     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4325     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4326     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4327     return;
4328   }
4329   
4330   // Otherwise, if this was a reference to an LLVM register class, create vregs
4331   // for this reference.
4332   std::vector<unsigned> RegClassRegs;
4333   const TargetRegisterClass *RC = PhysReg.second;
4334   if (RC) {
4335     // If this is an early clobber or tied register, our regalloc doesn't know
4336     // how to maintain the constraint.  If it isn't, go ahead and create vreg
4337     // and let the regalloc do the right thing.
4338     if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4339         // If there is some other early clobber and this is an input register,
4340         // then we are forced to pre-allocate the input reg so it doesn't
4341         // conflict with the earlyclobber.
4342         !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4343       RegVT = *PhysReg.second->vt_begin();
4344       
4345       if (OpInfo.ConstraintVT == MVT::Other)
4346         ValueVT = RegVT;
4347
4348       // Create the appropriate number of virtual registers.
4349       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4350       for (; NumRegs; --NumRegs)
4351         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4352       
4353       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4354       return;
4355     }
4356     
4357     // Otherwise, we can't allocate it.  Let the code below figure out how to
4358     // maintain these constraints.
4359     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4360     
4361   } else {
4362     // This is a reference to a register class that doesn't directly correspond
4363     // to an LLVM register class.  Allocate NumRegs consecutive, available,
4364     // registers from the class.
4365     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4366                                                          OpInfo.ConstraintVT);
4367   }
4368   
4369   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4370   unsigned NumAllocated = 0;
4371   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4372     unsigned Reg = RegClassRegs[i];
4373     // See if this register is available.
4374     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4375         (isInReg  && InputRegs.count(Reg))) {    // Already used.
4376       // Make sure we find consecutive registers.
4377       NumAllocated = 0;
4378       continue;
4379     }
4380     
4381     // Check to see if this register is allocatable (i.e. don't give out the
4382     // stack pointer).
4383     if (RC == 0) {
4384       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4385       if (!RC) {        // Couldn't allocate this register.
4386         // Reset NumAllocated to make sure we return consecutive registers.
4387         NumAllocated = 0;
4388         continue;
4389       }
4390     }
4391     
4392     // Okay, this register is good, we can use it.
4393     ++NumAllocated;
4394
4395     // If we allocated enough consecutive registers, succeed.
4396     if (NumAllocated == NumRegs) {
4397       unsigned RegStart = (i-NumAllocated)+1;
4398       unsigned RegEnd   = i+1;
4399       // Mark all of the allocated registers used.
4400       for (unsigned i = RegStart; i != RegEnd; ++i)
4401         Regs.push_back(RegClassRegs[i]);
4402       
4403       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 
4404                                          OpInfo.ConstraintVT);
4405       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4406       return;
4407     }
4408   }
4409   
4410   // Otherwise, we couldn't allocate enough registers for this.
4411 }
4412
4413
4414 /// visitInlineAsm - Handle a call to an InlineAsm object.
4415 ///
4416 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4417   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4418
4419   /// ConstraintOperands - Information about all of the constraints.
4420   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4421   
4422   SDValue Chain = getRoot();
4423   SDValue Flag;
4424   
4425   std::set<unsigned> OutputRegs, InputRegs;
4426
4427   // Do a prepass over the constraints, canonicalizing them, and building up the
4428   // ConstraintOperands list.
4429   std::vector<InlineAsm::ConstraintInfo>
4430     ConstraintInfos = IA->ParseConstraints();
4431
4432   // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4433   // constraint.  If so, we can't let the register allocator allocate any input
4434   // registers, because it will not know to avoid the earlyclobbered output reg.
4435   bool SawEarlyClobber = false;
4436   
4437   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
4438   unsigned ResNo = 0;   // ResNo - The result number of the next output.
4439   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4440     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4441     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4442     
4443     MVT OpVT = MVT::Other;
4444
4445     // Compute the value type for each operand.
4446     switch (OpInfo.Type) {
4447     case InlineAsm::isOutput:
4448       // Indirect outputs just consume an argument.
4449       if (OpInfo.isIndirect) {
4450         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4451         break;
4452       }
4453       // The return value of the call is this value.  As such, there is no
4454       // corresponding argument.
4455       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4456       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4457         OpVT = TLI.getValueType(STy->getElementType(ResNo));
4458       } else {
4459         assert(ResNo == 0 && "Asm only has one result!");
4460         OpVT = TLI.getValueType(CS.getType());
4461       }
4462       ++ResNo;
4463       break;
4464     case InlineAsm::isInput:
4465       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4466       break;
4467     case InlineAsm::isClobber:
4468       // Nothing to do.
4469       break;
4470     }
4471
4472     // If this is an input or an indirect output, process the call argument.
4473     // BasicBlocks are labels, currently appearing only in asm's.
4474     if (OpInfo.CallOperandVal) {
4475       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4476         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4477       else {
4478         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4479         const Type *OpTy = OpInfo.CallOperandVal->getType();
4480         // If this is an indirect operand, the operand is a pointer to the
4481         // accessed type.
4482         if (OpInfo.isIndirect)
4483           OpTy = cast<PointerType>(OpTy)->getElementType();
4484
4485         // If OpTy is not a single value, it may be a struct/union that we
4486         // can tile with integers.
4487         if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4488           unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4489           switch (BitSize) {
4490           default: break;
4491           case 1:
4492           case 8:
4493           case 16:
4494           case 32:
4495           case 64:
4496             OpTy = IntegerType::get(BitSize);
4497             break;
4498           }
4499         }
4500
4501         OpVT = TLI.getValueType(OpTy, true);
4502       }
4503     }
4504     
4505     OpInfo.ConstraintVT = OpVT;
4506     
4507     // Compute the constraint code and ConstraintType to use.
4508     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4509
4510     // Keep track of whether we see an earlyclobber.
4511     SawEarlyClobber |= OpInfo.isEarlyClobber;
4512     
4513     // If we see a clobber of a register, it is an early clobber.
4514     if (!SawEarlyClobber &&
4515         OpInfo.Type == InlineAsm::isClobber &&
4516         OpInfo.ConstraintType == TargetLowering::C_Register) {
4517       // Note that we want to ignore things that we don't track here, like
4518       // dirflag, fpsr, flags, etc.
4519       std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
4520         TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4521                                          OpInfo.ConstraintVT);
4522       if (PhysReg.first || PhysReg.second) {
4523         // This is a register we know of.
4524         SawEarlyClobber = true;
4525       }
4526     }
4527     
4528     // If this is a memory input, and if the operand is not indirect, do what we
4529     // need to to provide an address for the memory input.
4530     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4531         !OpInfo.isIndirect) {
4532       assert(OpInfo.Type == InlineAsm::isInput &&
4533              "Can only indirectify direct input operands!");
4534       
4535       // Memory operands really want the address of the value.  If we don't have
4536       // an indirect input, put it in the constpool if we can, otherwise spill
4537       // it to a stack slot.
4538       
4539       // If the operand is a float, integer, or vector constant, spill to a
4540       // constant pool entry to get its address.
4541       Value *OpVal = OpInfo.CallOperandVal;
4542       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4543           isa<ConstantVector>(OpVal)) {
4544         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4545                                                  TLI.getPointerTy());
4546       } else {
4547         // Otherwise, create a stack slot and emit a store to it before the
4548         // asm.
4549         const Type *Ty = OpVal->getType();
4550         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4551         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4552         MachineFunction &MF = DAG.getMachineFunction();
4553         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4554         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4555         Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4556         OpInfo.CallOperand = StackSlot;
4557       }
4558      
4559       // There is no longer a Value* corresponding to this operand.
4560       OpInfo.CallOperandVal = 0;
4561       // It is now an indirect operand.
4562       OpInfo.isIndirect = true;
4563     }
4564     
4565     // If this constraint is for a specific register, allocate it before
4566     // anything else.
4567     if (OpInfo.ConstraintType == TargetLowering::C_Register)
4568       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4569   }
4570   ConstraintInfos.clear();
4571   
4572   
4573   // Second pass - Loop over all of the operands, assigning virtual or physregs
4574   // to registerclass operands.
4575   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4576     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4577     
4578     // C_Register operands have already been allocated, Other/Memory don't need
4579     // to be.
4580     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4581       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4582   }    
4583   
4584   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4585   std::vector<SDValue> AsmNodeOperands;
4586   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
4587   AsmNodeOperands.push_back(
4588           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4589   
4590   
4591   // Loop over all of the inputs, copying the operand values into the
4592   // appropriate registers and processing the output regs.
4593   RegsForValue RetValRegs;
4594  
4595   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4596   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4597   
4598   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4599     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4600
4601     switch (OpInfo.Type) {
4602     case InlineAsm::isOutput: {
4603       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4604           OpInfo.ConstraintType != TargetLowering::C_Register) {
4605         // Memory output, or 'other' output (e.g. 'X' constraint).
4606         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4607
4608         // Add information to the INLINEASM node to know about this output.
4609         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4610         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4611                                                         TLI.getPointerTy()));
4612         AsmNodeOperands.push_back(OpInfo.CallOperand);
4613         break;
4614       }
4615
4616       // Otherwise, this is a register or register class output.
4617
4618       // Copy the output from the appropriate register.  Find a register that
4619       // we can use.
4620       if (OpInfo.AssignedRegs.Regs.empty()) {
4621         cerr << "Couldn't allocate output reg for constraint '"
4622              << OpInfo.ConstraintCode << "'!\n";
4623         exit(1);
4624       }
4625
4626       // If this is an indirect operand, store through the pointer after the
4627       // asm.
4628       if (OpInfo.isIndirect) {
4629         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4630                                                       OpInfo.CallOperandVal));
4631       } else {
4632         // This is the result value of the call.
4633         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4634         // Concatenate this output onto the outputs list.
4635         RetValRegs.append(OpInfo.AssignedRegs);
4636       }
4637       
4638       // Add information to the INLINEASM node to know that this register is
4639       // set.
4640       OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4641                                                AsmNodeOperands);
4642       break;
4643     }
4644     case InlineAsm::isInput: {
4645       SDValue InOperandVal = OpInfo.CallOperand;
4646       
4647       if (isdigit(OpInfo.ConstraintCode[0])) {    // Matching constraint?
4648         // If this is required to match an output register we have already set,
4649         // just use its register.
4650         unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4651         
4652         // Scan until we find the definition we already emitted of this operand.
4653         // When we find it, create a RegsForValue operand.
4654         unsigned CurOp = 2;  // The first operand.
4655         for (; OperandNo; --OperandNo) {
4656           // Advance to the next operand.
4657           unsigned NumOps = 
4658             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4659           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4660                   (NumOps & 7) == 4 /*MEM*/) &&
4661                  "Skipped past definitions?");
4662           CurOp += (NumOps>>3)+1;
4663         }
4664
4665         unsigned NumOps = 
4666           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4667         if ((NumOps & 7) == 2 /*REGDEF*/) {
4668           // Add NumOps>>3 registers to MatchedRegs.
4669           RegsForValue MatchedRegs;
4670           MatchedRegs.TLI = &TLI;
4671           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4672           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4673           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4674             unsigned Reg =
4675               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4676             MatchedRegs.Regs.push_back(Reg);
4677           }
4678         
4679           // Use the produced MatchedRegs object to 
4680           MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4681           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4682           break;
4683         } else {
4684           assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4685           assert((NumOps >> 3) == 1 && "Unexpected number of operands"); 
4686           // Add information to the INLINEASM node to know about this input.
4687           unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4688           AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4689                                                           TLI.getPointerTy()));
4690           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4691           break;
4692         }
4693       }
4694       
4695       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4696         assert(!OpInfo.isIndirect && 
4697                "Don't know how to handle indirect other inputs yet!");
4698         
4699         std::vector<SDValue> Ops;
4700         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4701                                          Ops, DAG);
4702         if (Ops.empty()) {
4703           cerr << "Invalid operand for inline asm constraint '"
4704                << OpInfo.ConstraintCode << "'!\n";
4705           exit(1);
4706         }
4707         
4708         // Add information to the INLINEASM node to know about this input.
4709         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4710         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4711                                                         TLI.getPointerTy()));
4712         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4713         break;
4714       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4715         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4716         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4717                "Memory operands expect pointer values");
4718                
4719         // Add information to the INLINEASM node to know about this input.
4720         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4721         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4722                                                         TLI.getPointerTy()));
4723         AsmNodeOperands.push_back(InOperandVal);
4724         break;
4725       }
4726         
4727       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4728               OpInfo.ConstraintType == TargetLowering::C_Register) &&
4729              "Unknown constraint type!");
4730       assert(!OpInfo.isIndirect && 
4731              "Don't know how to handle indirect register inputs yet!");
4732
4733       // Copy the input into the appropriate registers.
4734       assert(!OpInfo.AssignedRegs.Regs.empty() &&
4735              "Couldn't allocate input reg!");
4736
4737       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4738       
4739       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4740                                                AsmNodeOperands);
4741       break;
4742     }
4743     case InlineAsm::isClobber: {
4744       // Add the clobbered value to the operand list, so that the register
4745       // allocator is aware that the physreg got clobbered.
4746       if (!OpInfo.AssignedRegs.Regs.empty())
4747         OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4748                                                  AsmNodeOperands);
4749       break;
4750     }
4751     }
4752   }
4753   
4754   // Finish up input operands.
4755   AsmNodeOperands[0] = Chain;
4756   if (Flag.Val) AsmNodeOperands.push_back(Flag);
4757   
4758   Chain = DAG.getNode(ISD::INLINEASM, 
4759                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4760                       &AsmNodeOperands[0], AsmNodeOperands.size());
4761   Flag = Chain.getValue(1);
4762
4763   // If this asm returns a register value, copy the result from that register
4764   // and set it as the value of the call.
4765   if (!RetValRegs.Regs.empty()) {
4766     SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4767
4768     // If any of the results of the inline asm is a vector, it may have the
4769     // wrong width/num elts.  This can happen for register classes that can
4770     // contain multiple different value types.  The preg or vreg allocated may
4771     // not have the same VT as was expected.  Convert it to the right type with
4772     // bit_convert.
4773     if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4774       for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4775         if (Val.Val->getValueType(i).isVector())
4776           Val = DAG.getNode(ISD::BIT_CONVERT,
4777                             TLI.getValueType(ResSTy->getElementType(i)), Val);
4778       }
4779     } else {
4780       if (Val.getValueType().isVector())
4781         Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4782                           Val);
4783     }
4784
4785     setValue(CS.getInstruction(), Val);
4786   }
4787   
4788   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
4789   
4790   // Process indirect outputs, first output all of the flagged copies out of
4791   // physregs.
4792   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4793     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4794     Value *Ptr = IndirectStoresToEmit[i].second;
4795     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4796     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4797   }
4798   
4799   // Emit the non-flagged stores from the physregs.
4800   SmallVector<SDValue, 8> OutChains;
4801   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4802     OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4803                                     getValue(StoresToEmit[i].second),
4804                                     StoresToEmit[i].second, 0));
4805   if (!OutChains.empty())
4806     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4807                         &OutChains[0], OutChains.size());
4808   DAG.setRoot(Chain);
4809 }
4810
4811
4812 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4813   SDValue Src = getValue(I.getOperand(0));
4814
4815   MVT IntPtr = TLI.getPointerTy();
4816
4817   if (IntPtr.bitsLT(Src.getValueType()))
4818     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4819   else if (IntPtr.bitsGT(Src.getValueType()))
4820     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4821
4822   // Scale the source by the type size.
4823   uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4824   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4825                     Src, DAG.getIntPtrConstant(ElementSize));
4826
4827   TargetLowering::ArgListTy Args;
4828   TargetLowering::ArgListEntry Entry;
4829   Entry.Node = Src;
4830   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4831   Args.push_back(Entry);
4832
4833   std::pair<SDValue,SDValue> Result =
4834     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4835                     true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4836   setValue(&I, Result.first);  // Pointers always fit in registers
4837   DAG.setRoot(Result.second);
4838 }
4839
4840 void SelectionDAGLowering::visitFree(FreeInst &I) {
4841   TargetLowering::ArgListTy Args;
4842   TargetLowering::ArgListEntry Entry;
4843   Entry.Node = getValue(I.getOperand(0));
4844   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4845   Args.push_back(Entry);
4846   MVT IntPtr = TLI.getPointerTy();
4847   std::pair<SDValue,SDValue> Result =
4848     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4849                     CallingConv::C, true,
4850                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4851   DAG.setRoot(Result.second);
4852 }
4853
4854 // EmitInstrWithCustomInserter - This method should be implemented by targets
4855 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
4856 // instructions are special in various ways, which require special support to
4857 // insert.  The specified MachineInstr is created but not inserted into any
4858 // basic blocks, and the scheduler passes ownership of it to this method.
4859 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4860                                                        MachineBasicBlock *MBB) {
4861   cerr << "If a target marks an instruction with "
4862        << "'usesCustomDAGSchedInserter', it must implement "
4863        << "TargetLowering::EmitInstrWithCustomInserter!\n";
4864   abort();
4865   return 0;  
4866 }
4867
4868 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4869   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
4870                           getValue(I.getOperand(1)), 
4871                           DAG.getSrcValue(I.getOperand(1))));
4872 }
4873
4874 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4875   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4876                              getValue(I.getOperand(0)),
4877                              DAG.getSrcValue(I.getOperand(0)));
4878   setValue(&I, V);
4879   DAG.setRoot(V.getValue(1));
4880 }
4881
4882 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4883   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4884                           getValue(I.getOperand(1)), 
4885                           DAG.getSrcValue(I.getOperand(1))));
4886 }
4887
4888 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4889   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
4890                           getValue(I.getOperand(1)), 
4891                           getValue(I.getOperand(2)),
4892                           DAG.getSrcValue(I.getOperand(1)),
4893                           DAG.getSrcValue(I.getOperand(2))));
4894 }
4895
4896 /// TargetLowering::LowerArguments - This is the default LowerArguments
4897 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
4898 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
4899 /// integrated into SDISel.
4900 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4901                                     SmallVectorImpl<SDValue> &ArgValues) {
4902   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4903   SmallVector<SDValue, 3+16> Ops;
4904   Ops.push_back(DAG.getRoot());
4905   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4906   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4907
4908   // Add one result value for each formal argument.
4909   SmallVector<MVT, 16> RetVals;
4910   unsigned j = 1;
4911   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4912        I != E; ++I, ++j) {
4913     SmallVector<MVT, 4> ValueVTs;
4914     ComputeValueVTs(*this, I->getType(), ValueVTs);
4915     for (unsigned Value = 0, NumValues = ValueVTs.size();
4916          Value != NumValues; ++Value) {
4917       MVT VT = ValueVTs[Value];
4918       const Type *ArgTy = VT.getTypeForMVT();
4919       ISD::ArgFlagsTy Flags;
4920       unsigned OriginalAlignment =
4921         getTargetData()->getABITypeAlignment(ArgTy);
4922
4923       if (F.paramHasAttr(j, ParamAttr::ZExt))
4924         Flags.setZExt();
4925       if (F.paramHasAttr(j, ParamAttr::SExt))
4926         Flags.setSExt();
4927       if (F.paramHasAttr(j, ParamAttr::InReg))
4928         Flags.setInReg();
4929       if (F.paramHasAttr(j, ParamAttr::StructRet))
4930         Flags.setSRet();
4931       if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4932         Flags.setByVal();
4933         const PointerType *Ty = cast<PointerType>(I->getType());
4934         const Type *ElementTy = Ty->getElementType();
4935         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4936         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4937         // For ByVal, alignment should be passed from FE.  BE will guess if
4938         // this info is not there but there are cases it cannot get right.
4939         if (F.getParamAlignment(j))
4940           FrameAlign = F.getParamAlignment(j);
4941         Flags.setByValAlign(FrameAlign);
4942         Flags.setByValSize(FrameSize);
4943       }
4944       if (F.paramHasAttr(j, ParamAttr::Nest))
4945         Flags.setNest();
4946       Flags.setOrigAlign(OriginalAlignment);
4947
4948       MVT RegisterVT = getRegisterType(VT);
4949       unsigned NumRegs = getNumRegisters(VT);
4950       for (unsigned i = 0; i != NumRegs; ++i) {
4951         RetVals.push_back(RegisterVT);
4952         ISD::ArgFlagsTy MyFlags = Flags;
4953         if (NumRegs > 1 && i == 0)
4954           MyFlags.setSplit();
4955         // if it isn't first piece, alignment must be 1
4956         else if (i > 0)
4957           MyFlags.setOrigAlign(1);
4958         Ops.push_back(DAG.getArgFlags(MyFlags));
4959       }
4960     }
4961   }
4962
4963   RetVals.push_back(MVT::Other);
4964   
4965   // Create the node.
4966   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4967                                DAG.getVTList(&RetVals[0], RetVals.size()),
4968                                &Ops[0], Ops.size()).Val;
4969   
4970   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
4971   // allows exposing the loads that may be part of the argument access to the
4972   // first DAGCombiner pass.
4973   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
4974   
4975   // The number of results should match up, except that the lowered one may have
4976   // an extra flag result.
4977   assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4978           (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4979            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4980          && "Lowering produced unexpected number of results!");
4981
4982   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4983   if (Result != TmpRes.Val && Result->use_empty()) {
4984     HandleSDNode Dummy(DAG.getRoot());
4985     DAG.RemoveDeadNode(Result);
4986   }
4987
4988   Result = TmpRes.Val;
4989   
4990   unsigned NumArgRegs = Result->getNumValues() - 1;
4991   DAG.setRoot(SDValue(Result, NumArgRegs));
4992
4993   // Set up the return result vector.
4994   unsigned i = 0;
4995   unsigned Idx = 1;
4996   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 
4997       ++I, ++Idx) {
4998     SmallVector<MVT, 4> ValueVTs;
4999     ComputeValueVTs(*this, I->getType(), ValueVTs);
5000     for (unsigned Value = 0, NumValues = ValueVTs.size();
5001          Value != NumValues; ++Value) {
5002       MVT VT = ValueVTs[Value];
5003       MVT PartVT = getRegisterType(VT);
5004
5005       unsigned NumParts = getNumRegisters(VT);
5006       SmallVector<SDValue, 4> Parts(NumParts);
5007       for (unsigned j = 0; j != NumParts; ++j)
5008         Parts[j] = SDValue(Result, i++);
5009
5010       ISD::NodeType AssertOp = ISD::DELETED_NODE;
5011       if (F.paramHasAttr(Idx, ParamAttr::SExt))
5012         AssertOp = ISD::AssertSext;
5013       else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
5014         AssertOp = ISD::AssertZext;
5015
5016       ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5017                                            AssertOp));
5018     }
5019   }
5020   assert(i == NumArgRegs && "Argument register count mismatch!");
5021 }
5022
5023
5024 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5025 /// implementation, which just inserts an ISD::CALL node, which is later custom
5026 /// lowered by the target to something concrete.  FIXME: When all targets are
5027 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5028 std::pair<SDValue, SDValue>
5029 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5030                             bool RetSExt, bool RetZExt, bool isVarArg,
5031                             unsigned CallingConv, bool isTailCall,
5032                             SDValue Callee,
5033                             ArgListTy &Args, SelectionDAG &DAG) {
5034   SmallVector<SDValue, 32> Ops;
5035   Ops.push_back(Chain);   // Op#0 - Chain
5036   Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
5037   Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
5038   Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
5039   Ops.push_back(Callee);
5040   
5041   // Handle all of the outgoing arguments.
5042   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5043     SmallVector<MVT, 4> ValueVTs;
5044     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5045     for (unsigned Value = 0, NumValues = ValueVTs.size();
5046          Value != NumValues; ++Value) {
5047       MVT VT = ValueVTs[Value];
5048       const Type *ArgTy = VT.getTypeForMVT();
5049       SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.getResNo() + Value);
5050       ISD::ArgFlagsTy Flags;
5051       unsigned OriginalAlignment =
5052         getTargetData()->getABITypeAlignment(ArgTy);
5053
5054       if (Args[i].isZExt)
5055         Flags.setZExt();
5056       if (Args[i].isSExt)
5057         Flags.setSExt();
5058       if (Args[i].isInReg)
5059         Flags.setInReg();
5060       if (Args[i].isSRet)
5061         Flags.setSRet();
5062       if (Args[i].isByVal) {
5063         Flags.setByVal();
5064         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5065         const Type *ElementTy = Ty->getElementType();
5066         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5067         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
5068         // For ByVal, alignment should come from FE.  BE will guess if this
5069         // info is not there but there are cases it cannot get right.
5070         if (Args[i].Alignment)
5071           FrameAlign = Args[i].Alignment;
5072         Flags.setByValAlign(FrameAlign);
5073         Flags.setByValSize(FrameSize);
5074       }
5075       if (Args[i].isNest)
5076         Flags.setNest();
5077       Flags.setOrigAlign(OriginalAlignment);
5078
5079       MVT PartVT = getRegisterType(VT);
5080       unsigned NumParts = getNumRegisters(VT);
5081       SmallVector<SDValue, 4> Parts(NumParts);
5082       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5083
5084       if (Args[i].isSExt)
5085         ExtendKind = ISD::SIGN_EXTEND;
5086       else if (Args[i].isZExt)
5087         ExtendKind = ISD::ZERO_EXTEND;
5088
5089       getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5090
5091       for (unsigned i = 0; i != NumParts; ++i) {
5092         // if it isn't first piece, alignment must be 1
5093         ISD::ArgFlagsTy MyFlags = Flags;
5094         if (NumParts > 1 && i == 0)
5095           MyFlags.setSplit();
5096         else if (i != 0)
5097           MyFlags.setOrigAlign(1);
5098
5099         Ops.push_back(Parts[i]);
5100         Ops.push_back(DAG.getArgFlags(MyFlags));
5101       }
5102     }
5103   }
5104   
5105   // Figure out the result value types. We start by making a list of
5106   // the potentially illegal return value types.
5107   SmallVector<MVT, 4> LoweredRetTys;
5108   SmallVector<MVT, 4> RetTys;
5109   ComputeValueVTs(*this, RetTy, RetTys);
5110
5111   // Then we translate that to a list of legal types.
5112   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5113     MVT VT = RetTys[I];
5114     MVT RegisterVT = getRegisterType(VT);
5115     unsigned NumRegs = getNumRegisters(VT);
5116     for (unsigned i = 0; i != NumRegs; ++i)
5117       LoweredRetTys.push_back(RegisterVT);
5118   }
5119   
5120   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
5121   
5122   // Create the CALL node.
5123   SDValue Res = DAG.getNode(ISD::CALL,
5124                               DAG.getVTList(&LoweredRetTys[0],
5125                                             LoweredRetTys.size()),
5126                               &Ops[0], Ops.size());
5127   Chain = Res.getValue(LoweredRetTys.size() - 1);
5128
5129   // Gather up the call result into a single value.
5130   if (RetTy != Type::VoidTy) {
5131     ISD::NodeType AssertOp = ISD::DELETED_NODE;
5132
5133     if (RetSExt)
5134       AssertOp = ISD::AssertSext;
5135     else if (RetZExt)
5136       AssertOp = ISD::AssertZext;
5137
5138     SmallVector<SDValue, 4> ReturnValues;
5139     unsigned RegNo = 0;
5140     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5141       MVT VT = RetTys[I];
5142       MVT RegisterVT = getRegisterType(VT);
5143       unsigned NumRegs = getNumRegisters(VT);
5144       unsigned RegNoEnd = NumRegs + RegNo;
5145       SmallVector<SDValue, 4> Results;
5146       for (; RegNo != RegNoEnd; ++RegNo)
5147         Results.push_back(Res.getValue(RegNo));
5148       SDValue ReturnValue =
5149         getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5150                          AssertOp);
5151       ReturnValues.push_back(ReturnValue);
5152     }
5153     Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5154                              &ReturnValues[0], ReturnValues.size());
5155   }
5156
5157   return std::make_pair(Res, Chain);
5158 }
5159
5160 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5161   assert(0 && "LowerOperation not implemented for this target!");
5162   abort();
5163   return SDValue();
5164 }
5165
5166
5167 //===----------------------------------------------------------------------===//
5168 // SelectionDAGISel code
5169 //===----------------------------------------------------------------------===//
5170
5171 SelectionDAGISel::SelectionDAGISel(TargetLowering &tli, bool fast) :
5172   FunctionPass((intptr_t)&ID), TLI(tli),
5173   FuncInfo(new FunctionLoweringInfo(TLI)),
5174   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
5175   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
5176   GFI(),
5177   Fast(fast),
5178   DAGSize(0)
5179 {}
5180
5181 SelectionDAGISel::~SelectionDAGISel() {
5182   delete SDL;
5183   delete CurDAG;
5184   delete FuncInfo;
5185 }
5186
5187 unsigned SelectionDAGISel::MakeReg(MVT VT) {
5188   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
5189 }
5190
5191 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
5192   AU.addRequired<AliasAnalysis>();
5193   AU.addRequired<GCModuleInfo>();
5194   AU.setPreservesAll();
5195 }
5196
5197 bool SelectionDAGISel::runOnFunction(Function &Fn) {
5198   // Get alias analysis for load/store combining.
5199   AA = &getAnalysis<AliasAnalysis>();
5200
5201   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
5202   if (MF.getFunction()->hasGC())
5203     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
5204   else
5205     GFI = 0;
5206   RegInfo = &MF.getRegInfo();
5207   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
5208
5209   FuncInfo->set(Fn, MF);
5210   CurDAG->init(MF, getAnalysisToUpdate<MachineModuleInfo>());
5211   SDL->init(GFI, *AA);
5212
5213   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
5214     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
5215       // Mark landing pad.
5216       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
5217
5218   SelectAllBasicBlocks(Fn, MF);
5219
5220   // Add function live-ins to entry block live-in set.
5221   BasicBlock *EntryBB = &Fn.getEntryBlock();
5222   BB = FuncInfo->MBBMap[EntryBB];
5223   if (!RegInfo->livein_empty())
5224     for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
5225            E = RegInfo->livein_end(); I != E; ++I)
5226       BB->addLiveIn(I->first);
5227
5228 #ifndef NDEBUG
5229   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
5230          "Not all catch info was assigned to a landing pad!");
5231 #endif
5232
5233   FuncInfo->clear();
5234
5235   return true;
5236 }
5237
5238 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5239   SDValue Op = getValue(V);
5240   assert((Op.getOpcode() != ISD::CopyFromReg ||
5241           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5242          "Copy from a reg to the same reg!");
5243   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5244
5245   RegsForValue RFV(TLI, Reg, V->getType());
5246   SDValue Chain = DAG.getEntryNode();
5247   RFV.getCopyToRegs(Op, DAG, Chain, 0);
5248   PendingExports.push_back(Chain);
5249 }
5250
5251 void SelectionDAGISel::
5252 LowerArguments(BasicBlock *LLVMBB) {
5253   // If this is the entry block, emit arguments.
5254   Function &F = *LLVMBB->getParent();
5255   SDValue OldRoot = SDL->DAG.getRoot();
5256   SmallVector<SDValue, 16> Args;
5257   TLI.LowerArguments(F, SDL->DAG, Args);
5258
5259   unsigned a = 0;
5260   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5261        AI != E; ++AI) {
5262     SmallVector<MVT, 4> ValueVTs;
5263     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5264     unsigned NumValues = ValueVTs.size();
5265     if (!AI->use_empty()) {
5266       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5267       // If this argument is live outside of the entry block, insert a copy from
5268       // whereever we got it to the vreg that other BB's will reference it as.
5269       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5270       if (VMI != FuncInfo->ValueMap.end()) {
5271         SDL->CopyValueToVirtualRegister(AI, VMI->second);
5272       }
5273     }
5274     a += NumValues;
5275   }
5276
5277   // Finally, if the target has anything special to do, allow it to do so.
5278   // FIXME: this should insert code into the DAG!
5279   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5280 }
5281
5282 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
5283                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
5284   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
5285     if (isSelector(I)) {
5286       // Apply the catch info to DestBB.
5287       addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
5288 #ifndef NDEBUG
5289       if (!FLI.MBBMap[SrcBB]->isLandingPad())
5290         FLI.CatchInfoFound.insert(I);
5291 #endif
5292     }
5293 }
5294
5295 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
5296 /// whether object offset >= 0.
5297 static bool
5298 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
5299   if (!isa<FrameIndexSDNode>(Op)) return false;
5300
5301   FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
5302   int FrameIdx =  FrameIdxNode->getIndex();
5303   return MFI->isFixedObjectIndex(FrameIdx) &&
5304     MFI->getObjectOffset(FrameIdx) >= 0;
5305 }
5306
5307 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5308 /// possibly be overwritten when lowering the outgoing arguments in a tail
5309 /// call. Currently the implementation of this call is very conservative and
5310 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5311 /// virtual registers would be overwritten by direct lowering.
5312 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
5313                                                     MachineFrameInfo * MFI) {
5314   RegisterSDNode * OpReg = NULL;
5315   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5316       (Op.getOpcode()== ISD::CopyFromReg &&
5317        (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5318        (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5319       (Op.getOpcode() == ISD::LOAD &&
5320        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5321       (Op.getOpcode() == ISD::MERGE_VALUES &&
5322        Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
5323        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
5324                                        getOperand(1))))
5325     return true;
5326   return false;
5327 }
5328
5329 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
5330 /// DAG and fixes their tailcall attribute operand.
5331 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 
5332                                            TargetLowering& TLI) {
5333   SDNode * Ret = NULL;
5334   SDValue Terminator = DAG.getRoot();
5335
5336   // Find RET node.
5337   if (Terminator.getOpcode() == ISD::RET) {
5338     Ret = Terminator.Val;
5339   }
5340  
5341   // Fix tail call attribute of CALL nodes.
5342   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
5343          BI = DAG.allnodes_end(); BI != BE; ) {
5344     --BI;
5345     if (BI->getOpcode() == ISD::CALL) {
5346       SDValue OpRet(Ret, 0);
5347       SDValue OpCall(BI, 0);
5348       bool isMarkedTailCall = 
5349         cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5350       // If CALL node has tail call attribute set to true and the call is not
5351       // eligible (no RET or the target rejects) the attribute is fixed to
5352       // false. The TargetLowering::IsEligibleForTailCallOptimization function
5353       // must correctly identify tail call optimizable calls.
5354       if (!isMarkedTailCall) continue;
5355       if (Ret==NULL ||
5356           !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5357         // Not eligible. Mark CALL node as non tail call.
5358         SmallVector<SDValue, 32> Ops;
5359         unsigned idx=0;
5360         for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5361               E = OpCall.Val->op_end(); I != E; I++, idx++) {
5362           if (idx!=3)
5363             Ops.push_back(*I);
5364           else
5365             Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5366         }
5367         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5368       } else {
5369         // Look for tail call clobbered arguments. Emit a series of
5370         // copyto/copyfrom virtual register nodes to protect them.
5371         SmallVector<SDValue, 32> Ops;
5372         SDValue Chain = OpCall.getOperand(0), InFlag;
5373         unsigned idx=0;
5374         for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5375               E = OpCall.Val->op_end(); I != E; I++, idx++) {
5376           SDValue Arg = *I;
5377           if (idx > 4 && (idx % 2)) {
5378             bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5379               getArgFlags().isByVal();
5380             MachineFunction &MF = DAG.getMachineFunction();
5381             MachineFrameInfo *MFI = MF.getFrameInfo();
5382             if (!isByVal &&
5383                 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5384               MVT VT = Arg.getValueType();
5385               unsigned VReg = MF.getRegInfo().
5386                 createVirtualRegister(TLI.getRegClassFor(VT));
5387               Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5388               InFlag = Chain.getValue(1);
5389               Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5390               Chain = Arg.getValue(1);
5391               InFlag = Arg.getValue(2);
5392             }
5393           }
5394           Ops.push_back(Arg);
5395         }
5396         // Link in chain of CopyTo/CopyFromReg.
5397         Ops[0] = Chain;
5398         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5399       }
5400     }
5401   }
5402 }
5403
5404 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5405 /// ensure constants are generated when needed.  Remember the virtual registers
5406 /// that need to be added to the Machine PHI nodes as input.  We cannot just
5407 /// directly add them, because expansion might result in multiple MBB's for one
5408 /// BB.  As such, the start of the BB might correspond to a different MBB than
5409 /// the end.
5410 ///
5411 void
5412 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5413   TerminatorInst *TI = LLVMBB->getTerminator();
5414
5415   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5416
5417   // Check successor nodes' PHI nodes that expect a constant to be available
5418   // from this block.
5419   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5420     BasicBlock *SuccBB = TI->getSuccessor(succ);
5421     if (!isa<PHINode>(SuccBB->begin())) continue;
5422     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5423     
5424     // If this terminator has multiple identical successors (common for
5425     // switches), only handle each succ once.
5426     if (!SuccsHandled.insert(SuccMBB)) continue;
5427     
5428     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5429     PHINode *PN;
5430
5431     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5432     // nodes and Machine PHI nodes, but the incoming operands have not been
5433     // emitted yet.
5434     for (BasicBlock::iterator I = SuccBB->begin();
5435          (PN = dyn_cast<PHINode>(I)); ++I) {
5436       // Ignore dead phi's.
5437       if (PN->use_empty()) continue;
5438
5439       unsigned Reg;
5440       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5441
5442       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5443         unsigned &RegOut = SDL->ConstantsOut[C];
5444         if (RegOut == 0) {
5445           RegOut = FuncInfo->CreateRegForValue(C);
5446           SDL->CopyValueToVirtualRegister(C, RegOut);
5447         }
5448         Reg = RegOut;
5449       } else {
5450         Reg = FuncInfo->ValueMap[PHIOp];
5451         if (Reg == 0) {
5452           assert(isa<AllocaInst>(PHIOp) &&
5453                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5454                  "Didn't codegen value into a register!??");
5455           Reg = FuncInfo->CreateRegForValue(PHIOp);
5456           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5457         }
5458       }
5459
5460       // Remember that this register needs to added to the machine PHI node as
5461       // the input for this MBB.
5462       SmallVector<MVT, 4> ValueVTs;
5463       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5464       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5465         MVT VT = ValueVTs[vti];
5466         unsigned NumRegisters = TLI.getNumRegisters(VT);
5467         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5468           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5469         Reg += NumRegisters;
5470       }
5471     }
5472   }
5473   SDL->ConstantsOut.clear();
5474
5475   // Lower the terminator after the copies are emitted.
5476   SDL->visit(*LLVMBB->getTerminator());
5477 }
5478
5479 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
5480                                         BasicBlock::iterator Begin,
5481                                         BasicBlock::iterator End,
5482                                         bool DoArgs) {
5483   // Lower any arguments needed in this block if this is the entry block.
5484   if (DoArgs)
5485     LowerArguments(LLVMBB);
5486
5487   SDL->setCurrentBasicBlock(BB);
5488
5489   MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
5490
5491   if (MMI && BB->isLandingPad()) {
5492     // Add a label to mark the beginning of the landing pad.  Deletion of the
5493     // landing pad can thus be detected via the MachineModuleInfo.
5494     unsigned LabelID = MMI->addLandingPad(BB);
5495     CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
5496                                      CurDAG->getEntryNode(), LabelID));
5497
5498     // Mark exception register as live in.
5499     unsigned Reg = TLI.getExceptionAddressRegister();
5500     if (Reg) BB->addLiveIn(Reg);
5501
5502     // Mark exception selector register as live in.
5503     Reg = TLI.getExceptionSelectorRegister();
5504     if (Reg) BB->addLiveIn(Reg);
5505
5506     // FIXME: Hack around an exception handling flaw (PR1508): the personality
5507     // function and list of typeids logically belong to the invoke (or, if you
5508     // like, the basic block containing the invoke), and need to be associated
5509     // with it in the dwarf exception handling tables.  Currently however the
5510     // information is provided by an intrinsic (eh.selector) that can be moved
5511     // to unexpected places by the optimizers: if the unwind edge is critical,
5512     // then breaking it can result in the intrinsics being in the successor of
5513     // the landing pad, not the landing pad itself.  This results in exceptions
5514     // not being caught because no typeids are associated with the invoke.
5515     // This may not be the only way things can go wrong, but it is the only way
5516     // we try to work around for the moment.
5517     BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5518
5519     if (Br && Br->isUnconditional()) { // Critical edge?
5520       BasicBlock::iterator I, E;
5521       for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5522         if (isSelector(I))
5523           break;
5524
5525       if (I == E)
5526         // No catch info found - try to extract some from the successor.
5527         copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
5528     }
5529   }
5530
5531   // Lower all of the non-terminator instructions.
5532   for (BasicBlock::iterator I = Begin; I != End; ++I)
5533     if (!isa<TerminatorInst>(I))
5534       SDL->visit(*I);
5535
5536   // Ensure that all instructions which are used outside of their defining
5537   // blocks are available as virtual registers.  Invoke is handled elsewhere.
5538   for (BasicBlock::iterator I = Begin; I != End; ++I)
5539     if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5540       DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
5541       if (VMI != FuncInfo->ValueMap.end())
5542         SDL->CopyValueToVirtualRegister(I, VMI->second);
5543     }
5544
5545   // Handle PHI nodes in successor blocks.
5546   if (Begin != End && End == LLVMBB->end())
5547     HandlePHINodesInSuccessorBlocks(LLVMBB);
5548     
5549   // Make sure the root of the DAG is up-to-date.
5550   CurDAG->setRoot(SDL->getControlRoot());
5551
5552   // Check whether calls in this block are real tail calls. Fix up CALL nodes
5553   // with correct tailcall attribute so that the target can rely on the tailcall
5554   // attribute indicating whether the call is really eligible for tail call
5555   // optimization.
5556   CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
5557
5558   // Final step, emit the lowered DAG as machine code.
5559   CodeGenAndEmitDAG();
5560   SDL->clear();
5561 }
5562
5563 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
5564   SmallPtrSet<SDNode*, 128> VisitedNodes;
5565   SmallVector<SDNode*, 128> Worklist;
5566   
5567   Worklist.push_back(CurDAG->getRoot().Val);
5568   
5569   APInt Mask;
5570   APInt KnownZero;
5571   APInt KnownOne;
5572   
5573   while (!Worklist.empty()) {
5574     SDNode *N = Worklist.back();
5575     Worklist.pop_back();
5576     
5577     // If we've already seen this node, ignore it.
5578     if (!VisitedNodes.insert(N))
5579       continue;
5580     
5581     // Otherwise, add all chain operands to the worklist.
5582     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5583       if (N->getOperand(i).getValueType() == MVT::Other)
5584         Worklist.push_back(N->getOperand(i).Val);
5585     
5586     // If this is a CopyToReg with a vreg dest, process it.
5587     if (N->getOpcode() != ISD::CopyToReg)
5588       continue;
5589     
5590     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5591     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5592       continue;
5593     
5594     // Ignore non-scalar or non-integer values.
5595     SDValue Src = N->getOperand(2);
5596     MVT SrcVT = Src.getValueType();
5597     if (!SrcVT.isInteger() || SrcVT.isVector())
5598       continue;
5599     
5600     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
5601     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5602     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5603     
5604     // Only install this information if it tells us something.
5605     if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5606       DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5607       FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
5608       if (DestReg >= FLI.LiveOutRegInfo.size())
5609         FLI.LiveOutRegInfo.resize(DestReg+1);
5610       FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5611       LOI.NumSignBits = NumSignBits;
5612       LOI.KnownOne = NumSignBits;
5613       LOI.KnownZero = NumSignBits;
5614     }
5615   }
5616 }
5617
5618 void SelectionDAGISel::CodeGenAndEmitDAG() {
5619   std::string GroupName;
5620   if (TimePassesIsEnabled)
5621     GroupName = "Instruction Selection and Scheduling";
5622   std::string BlockName;
5623   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5624       ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
5625     BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
5626                 BB->getBasicBlock()->getName();
5627
5628   DOUT << "Initial selection DAG:\n";
5629   DEBUG(CurDAG->dump());
5630
5631   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
5632
5633   // Run the DAG combiner in pre-legalize mode.
5634   if (TimePassesIsEnabled) {
5635     NamedRegionTimer T("DAG Combining 1", GroupName);
5636     CurDAG->Combine(false, *AA, Fast);
5637   } else {
5638     CurDAG->Combine(false, *AA, Fast);
5639   }
5640   
5641   DOUT << "Optimized lowered selection DAG:\n";
5642   DEBUG(CurDAG->dump());
5643   
5644   // Second step, hack on the DAG until it only uses operations and types that
5645   // the target supports.
5646   if (EnableLegalizeTypes) {// Enable this some day.
5647     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
5648                                                  BlockName);
5649
5650     if (TimePassesIsEnabled) {
5651       NamedRegionTimer T("Type Legalization", GroupName);
5652       CurDAG->LegalizeTypes();
5653     } else {
5654       CurDAG->LegalizeTypes();
5655     }
5656
5657     DOUT << "Type-legalized selection DAG:\n";
5658     DEBUG(CurDAG->dump());
5659
5660     // TODO: enable a dag combine pass here.
5661   }
5662   
5663   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
5664
5665   if (TimePassesIsEnabled) {
5666     NamedRegionTimer T("DAG Legalization", GroupName);
5667     CurDAG->Legalize();
5668   } else {
5669     CurDAG->Legalize();
5670   }
5671   
5672   DOUT << "Legalized selection DAG:\n";
5673   DEBUG(CurDAG->dump());
5674   
5675   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
5676
5677   // Run the DAG combiner in post-legalize mode.
5678   if (TimePassesIsEnabled) {
5679     NamedRegionTimer T("DAG Combining 2", GroupName);
5680     CurDAG->Combine(true, *AA, Fast);
5681   } else {
5682     CurDAG->Combine(true, *AA, Fast);
5683   }
5684   
5685   DOUT << "Optimized legalized selection DAG:\n";
5686   DEBUG(CurDAG->dump());
5687
5688   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
5689   
5690   if (!Fast && EnableValueProp)
5691     ComputeLiveOutVRegInfo();
5692
5693   // Third, instruction select all of the operations to machine code, adding the
5694   // code to the MachineBasicBlock.
5695   if (TimePassesIsEnabled) {
5696     NamedRegionTimer T("Instruction Selection", GroupName);
5697     InstructionSelect();
5698   } else {
5699     InstructionSelect();
5700   }
5701
5702   DOUT << "Selected selection DAG:\n";
5703   DEBUG(CurDAG->dump());
5704
5705   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
5706
5707   // Schedule machine code.
5708   ScheduleDAG *Scheduler;
5709   if (TimePassesIsEnabled) {
5710     NamedRegionTimer T("Instruction Scheduling", GroupName);
5711     Scheduler = Schedule();
5712   } else {
5713     Scheduler = Schedule();
5714   }
5715
5716   if (ViewSUnitDAGs) Scheduler->viewGraph();
5717
5718   // Emit machine code to BB.  This can change 'BB' to the last block being 
5719   // inserted into.
5720   if (TimePassesIsEnabled) {
5721     NamedRegionTimer T("Instruction Creation", GroupName);
5722     BB = Scheduler->EmitSchedule();
5723   } else {
5724     BB = Scheduler->EmitSchedule();
5725   }
5726
5727   // Free the scheduler state.
5728   if (TimePassesIsEnabled) {
5729     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5730     delete Scheduler;
5731   } else {
5732     delete Scheduler;
5733   }
5734
5735   DOUT << "Selected machine code:\n";
5736   DEBUG(BB->dump());
5737 }  
5738
5739 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF) {
5740   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5741     BasicBlock *LLVMBB = &*I;
5742     BB = FuncInfo->MBBMap[LLVMBB];
5743
5744     BasicBlock::iterator Begin = LLVMBB->begin();
5745     BasicBlock::iterator End = LLVMBB->end();
5746     bool DoArgs = LLVMBB == &Fn.getEntryBlock();
5747
5748     // Before doing SelectionDAG ISel, see if FastISel has been requested.
5749     // FastISel doesn't support EH landing pads, which require special handling.
5750     if (EnableFastISel && !BB->isLandingPad()) {
5751       if (FastISel *F = TLI.createFastISel(*FuncInfo->MF)) {
5752         while (Begin != End) {
5753           Begin = F->SelectInstructions(Begin, End, FuncInfo->ValueMap,
5754                                         FuncInfo->MBBMap, BB);
5755
5756           if (Begin == End)
5757             // The "fast" selector selected the entire block, so we're done.
5758             break;
5759
5760           // Handle certain instructions as single-LLVM-Instruction blocks.
5761           if (isa<CallInst>(Begin) || isa<LoadInst>(Begin) ||
5762               isa<StoreInst>(Begin)) {
5763             if (Begin->getType() != Type::VoidTy) {
5764               unsigned &R = FuncInfo->ValueMap[Begin];
5765               if (!R)
5766                 R = FuncInfo->CreateRegForValue(Begin);
5767             }
5768
5769             SelectBasicBlock(LLVMBB, Begin, next(Begin), DoArgs);
5770
5771             ++Begin;
5772             DoArgs = false;
5773             continue;
5774           }
5775
5776           if (!DisableFastISelAbort &&
5777               // For now, don't abort on non-conditional-branch terminators.
5778               (!isa<TerminatorInst>(Begin) ||
5779                (isa<BranchInst>(Begin) &&
5780                 cast<BranchInst>(Begin)->isUnconditional()))) {
5781             // The "fast" selector couldn't handle something and bailed.
5782             // For the purpose of debugging, just abort.
5783 #ifndef NDEBUG
5784               Begin->dump();
5785 #endif
5786             assert(0 && "FastISel didn't select the entire block");
5787           }
5788           break;
5789         }
5790         delete F;
5791       }
5792     }
5793
5794     if (Begin != End || DoArgs)
5795       SelectBasicBlock(LLVMBB, Begin, End, DoArgs);
5796
5797     FinishBasicBlock();
5798   }
5799 }
5800
5801 void
5802 SelectionDAGISel::FinishBasicBlock() {
5803
5804   // Perform target specific isel post processing.
5805   InstructionSelectPostProcessing();
5806   
5807   DOUT << "Target-post-processed machine code:\n";
5808   DEBUG(BB->dump());
5809
5810   DOUT << "Total amount of phi nodes to update: "
5811        << SDL->PHINodesToUpdate.size() << "\n";
5812   DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
5813           DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
5814                << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
5815   
5816   // Next, now that we know what the last MBB the LLVM BB expanded is, update
5817   // PHI nodes in successors.
5818   if (SDL->SwitchCases.empty() &&
5819       SDL->JTCases.empty() &&
5820       SDL->BitTestCases.empty()) {
5821     for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5822       MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
5823       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5824              "This is not a machine PHI node that we are updating!");
5825       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
5826                                                 false));
5827       PHI->addOperand(MachineOperand::CreateMBB(BB));
5828     }
5829     SDL->PHINodesToUpdate.clear();
5830     return;
5831   }
5832
5833   for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
5834     // Lower header first, if it wasn't already lowered
5835     if (!SDL->BitTestCases[i].Emitted) {
5836       // Set the current basic block to the mbb we wish to insert the code into
5837       BB = SDL->BitTestCases[i].Parent;
5838       SDL->setCurrentBasicBlock(BB);
5839       // Emit the code
5840       SDL->visitBitTestHeader(SDL->BitTestCases[i]);
5841       CurDAG->setRoot(SDL->getRoot());
5842       CodeGenAndEmitDAG();
5843       SDL->clear();
5844     }    
5845
5846     for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
5847       // Set the current basic block to the mbb we wish to insert the code into
5848       BB = SDL->BitTestCases[i].Cases[j].ThisBB;
5849       SDL->setCurrentBasicBlock(BB);
5850       // Emit the code
5851       if (j+1 != ej)
5852         SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
5853                               SDL->BitTestCases[i].Reg,
5854                               SDL->BitTestCases[i].Cases[j]);
5855       else
5856         SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
5857                               SDL->BitTestCases[i].Reg,
5858                               SDL->BitTestCases[i].Cases[j]);
5859         
5860         
5861       CurDAG->setRoot(SDL->getRoot());
5862       CodeGenAndEmitDAG();
5863       SDL->clear();
5864     }
5865
5866     // Update PHI Nodes
5867     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5868       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
5869       MachineBasicBlock *PHIBB = PHI->getParent();
5870       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5871              "This is not a machine PHI node that we are updating!");
5872       // This is "default" BB. We have two jumps to it. From "header" BB and
5873       // from last "case" BB.
5874       if (PHIBB == SDL->BitTestCases[i].Default) {
5875         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
5876                                                   false));
5877         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
5878         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
5879                                                   false));
5880         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
5881                                                   back().ThisBB));
5882       }
5883       // One of "cases" BB.
5884       for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
5885            j != ej; ++j) {
5886         MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
5887         if (cBB->succ_end() !=
5888             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5889           PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
5890                                                     false));
5891           PHI->addOperand(MachineOperand::CreateMBB(cBB));
5892         }
5893       }
5894     }
5895   }
5896   SDL->BitTestCases.clear();
5897
5898   // If the JumpTable record is filled in, then we need to emit a jump table.
5899   // Updating the PHI nodes is tricky in this case, since we need to determine
5900   // whether the PHI is a successor of the range check MBB or the jump table MBB
5901   for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
5902     // Lower header first, if it wasn't already lowered
5903     if (!SDL->JTCases[i].first.Emitted) {
5904       // Set the current basic block to the mbb we wish to insert the code into
5905       BB = SDL->JTCases[i].first.HeaderBB;
5906       SDL->setCurrentBasicBlock(BB);
5907       // Emit the code
5908       SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
5909       CurDAG->setRoot(SDL->getRoot());
5910       CodeGenAndEmitDAG();
5911       SDL->clear();
5912     }
5913     
5914     // Set the current basic block to the mbb we wish to insert the code into
5915     BB = SDL->JTCases[i].second.MBB;
5916     SDL->setCurrentBasicBlock(BB);
5917     // Emit the code
5918     SDL->visitJumpTable(SDL->JTCases[i].second);
5919     CurDAG->setRoot(SDL->getRoot());
5920     CodeGenAndEmitDAG();
5921     SDL->clear();
5922     
5923     // Update PHI Nodes
5924     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5925       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
5926       MachineBasicBlock *PHIBB = PHI->getParent();
5927       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5928              "This is not a machine PHI node that we are updating!");
5929       // "default" BB. We can go there only from header BB.
5930       if (PHIBB == SDL->JTCases[i].second.Default) {
5931         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
5932                                                   false));
5933         PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
5934       }
5935       // JT BB. Just iterate over successors here
5936       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5937         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
5938                                                   false));
5939         PHI->addOperand(MachineOperand::CreateMBB(BB));
5940       }
5941     }
5942   }
5943   SDL->JTCases.clear();
5944   
5945   // If the switch block involved a branch to one of the actual successors, we
5946   // need to update PHI nodes in that block.
5947   for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5948     MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
5949     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5950            "This is not a machine PHI node that we are updating!");
5951     if (BB->isSuccessor(PHI->getParent())) {
5952       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
5953                                                 false));
5954       PHI->addOperand(MachineOperand::CreateMBB(BB));
5955     }
5956   }
5957   
5958   // If we generated any switch lowering information, build and codegen any
5959   // additional DAGs necessary.
5960   for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
5961     // Set the current basic block to the mbb we wish to insert the code into
5962     BB = SDL->SwitchCases[i].ThisBB;
5963     SDL->setCurrentBasicBlock(BB);
5964     
5965     // Emit the code
5966     SDL->visitSwitchCase(SDL->SwitchCases[i]);
5967     CurDAG->setRoot(SDL->getRoot());
5968     CodeGenAndEmitDAG();
5969     SDL->clear();
5970     
5971     // Handle any PHI nodes in successors of this chunk, as if we were coming
5972     // from the original BB before switch expansion.  Note that PHI nodes can
5973     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
5974     // handle them the right number of times.
5975     while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
5976       for (MachineBasicBlock::iterator Phi = BB->begin();
5977            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5978         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5979         for (unsigned pn = 0; ; ++pn) {
5980           assert(pn != SDL->PHINodesToUpdate.size() &&
5981                  "Didn't find PHI entry!");
5982           if (SDL->PHINodesToUpdate[pn].first == Phi) {
5983             Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
5984                                                       second, false));
5985             Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
5986             break;
5987           }
5988         }
5989       }
5990       
5991       // Don't process RHS if same block as LHS.
5992       if (BB == SDL->SwitchCases[i].FalseBB)
5993         SDL->SwitchCases[i].FalseBB = 0;
5994       
5995       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
5996       SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
5997       SDL->SwitchCases[i].FalseBB = 0;
5998     }
5999     assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
6000   }
6001   SDL->SwitchCases.clear();
6002
6003   SDL->PHINodesToUpdate.clear();
6004 }
6005
6006
6007 /// Schedule - Pick a safe ordering for instructions for each
6008 /// target node in the graph.
6009 ///
6010 ScheduleDAG *SelectionDAGISel::Schedule() {
6011   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
6012   
6013   if (!Ctor) {
6014     Ctor = ISHeuristic;
6015     RegisterScheduler::setDefault(Ctor);
6016   }
6017   
6018   ScheduleDAG *Scheduler = Ctor(this, CurDAG, BB, Fast);
6019   Scheduler->Run();
6020
6021   return Scheduler;
6022 }
6023
6024
6025 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
6026   return new HazardRecognizer();
6027 }
6028
6029 //===----------------------------------------------------------------------===//
6030 // Helper functions used by the generated instruction selector.
6031 //===----------------------------------------------------------------------===//
6032 // Calls to these methods are generated by tblgen.
6033
6034 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
6035 /// the dag combiner simplified the 255, we still want to match.  RHS is the
6036 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
6037 /// specified in the .td file (e.g. 255).
6038 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 
6039                                     int64_t DesiredMaskS) const {
6040   const APInt &ActualMask = RHS->getAPIntValue();
6041   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
6042   
6043   // If the actual mask exactly matches, success!
6044   if (ActualMask == DesiredMask)
6045     return true;
6046   
6047   // If the actual AND mask is allowing unallowed bits, this doesn't match.
6048   if (ActualMask.intersects(~DesiredMask))
6049     return false;
6050   
6051   // Otherwise, the DAG Combiner may have proven that the value coming in is
6052   // either already zero or is not demanded.  Check for known zero input bits.
6053   APInt NeededMask = DesiredMask & ~ActualMask;
6054   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
6055     return true;
6056   
6057   // TODO: check to see if missing bits are just not demanded.
6058
6059   // Otherwise, this pattern doesn't match.
6060   return false;
6061 }
6062
6063 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
6064 /// the dag combiner simplified the 255, we still want to match.  RHS is the
6065 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
6066 /// specified in the .td file (e.g. 255).
6067 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 
6068                                    int64_t DesiredMaskS) const {
6069   const APInt &ActualMask = RHS->getAPIntValue();
6070   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
6071   
6072   // If the actual mask exactly matches, success!
6073   if (ActualMask == DesiredMask)
6074     return true;
6075   
6076   // If the actual AND mask is allowing unallowed bits, this doesn't match.
6077   if (ActualMask.intersects(~DesiredMask))
6078     return false;
6079   
6080   // Otherwise, the DAG Combiner may have proven that the value coming in is
6081   // either already zero or is not demanded.  Check for known zero input bits.
6082   APInt NeededMask = DesiredMask & ~ActualMask;
6083   
6084   APInt KnownZero, KnownOne;
6085   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
6086   
6087   // If all the missing bits in the or are already known to be set, match!
6088   if ((NeededMask & KnownOne) == NeededMask)
6089     return true;
6090   
6091   // TODO: check to see if missing bits are just not demanded.
6092   
6093   // Otherwise, this pattern doesn't match.
6094   return false;
6095 }
6096
6097
6098 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
6099 /// by tblgen.  Others should not call it.
6100 void SelectionDAGISel::
6101 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
6102   std::vector<SDValue> InOps;
6103   std::swap(InOps, Ops);
6104
6105   Ops.push_back(InOps[0]);  // input chain.
6106   Ops.push_back(InOps[1]);  // input asm string.
6107
6108   unsigned i = 2, e = InOps.size();
6109   if (InOps[e-1].getValueType() == MVT::Flag)
6110     --e;  // Don't process a flag operand if it is here.
6111   
6112   while (i != e) {
6113     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
6114     if ((Flags & 7) != 4 /*MEM*/) {
6115       // Just skip over this operand, copying the operands verbatim.
6116       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
6117       i += (Flags >> 3) + 1;
6118     } else {
6119       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
6120       // Otherwise, this is a memory operand.  Ask the target to select it.
6121       std::vector<SDValue> SelOps;
6122       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
6123         cerr << "Could not match memory address.  Inline asm failure!\n";
6124         exit(1);
6125       }
6126       
6127       // Add this to the output node.
6128       MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
6129       Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
6130                                               IntPtrTy));
6131       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
6132       i += 2;
6133     }
6134   }
6135   
6136   // Add the flag input back if present.
6137   if (e != InOps.size())
6138     Ops.push_back(InOps.back());
6139 }
6140
6141 char SelectionDAGISel::ID = 0;