If the target cannot issue a copy for the given source and dest registers, abort...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.h
1 //===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
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 routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef SELECTIONDAGBUILD_H
15 #define SELECTIONDAGBUILD_H
16
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/DenseMap.h"
20 #ifndef NDEBUG
21 #include "llvm/ADT/SmallSet.h"
22 #endif
23 #include "llvm/CodeGen/SelectionDAGNodes.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/Support/CallSite.h"
26 #include <vector>
27 #include <set>
28
29 namespace llvm {
30
31 class AliasAnalysis;
32 class AllocaInst;
33 class BasicBlock;
34 class BitCastInst;
35 class BranchInst;
36 class CallInst;
37 class ExtractElementInst;
38 class ExtractValueInst;
39 class FCmpInst;
40 class FPExtInst;
41 class FPToSIInst;
42 class FPToUIInst;
43 class FPTruncInst;
44 class FreeInst;
45 class Function;
46 class GetElementPtrInst;
47 class GCFunctionInfo;
48 class ICmpInst;
49 class IntToPtrInst;
50 class InvokeInst;
51 class InsertElementInst;
52 class InsertValueInst;
53 class Instruction;
54 class LoadInst;
55 class MachineBasicBlock;
56 class MachineFunction;
57 class MachineInstr;
58 class MachineModuleInfo;
59 class MachineRegisterInfo;
60 class MallocInst;
61 class PHINode;
62 class PtrToIntInst;
63 class ReturnInst;
64 class SDISelAsmOperandInfo;
65 class SExtInst;
66 class SelectInst;
67 class ShuffleVectorInst;
68 class SIToFPInst;
69 class StoreInst;
70 class SwitchInst;
71 class TargetData;
72 class TargetLowering;
73 class TruncInst;
74 class UIToFPInst;
75 class UnreachableInst;
76 class UnwindInst;
77 class VICmpInst;
78 class VFCmpInst;
79 class VAArgInst;
80 class ZExtInst;
81
82 //===--------------------------------------------------------------------===//
83 /// FunctionLoweringInfo - This contains information that is global to a
84 /// function that is used when lowering a region of the function.
85 ///
86 class FunctionLoweringInfo {
87 public:
88   TargetLowering &TLI;
89   Function *Fn;
90   MachineFunction *MF;
91   MachineRegisterInfo *RegInfo;
92
93   explicit FunctionLoweringInfo(TargetLowering &TLI);
94
95   /// set - Initialize this FunctionLoweringInfo with the given Function
96   /// and its associated MachineFunction.
97   ///
98   void set(Function &Fn, MachineFunction &MF, SelectionDAG &DAG,
99            bool EnableFastISel);
100
101   /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
102   DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
103
104   /// ValueMap - Since we emit code for the function a basic block at a time,
105   /// we must remember which virtual registers hold the values for
106   /// cross-basic-block values.
107   DenseMap<const Value*, unsigned> ValueMap;
108
109   /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
110   /// the entry block.  This allows the allocas to be efficiently referenced
111   /// anywhere in the function.
112   DenseMap<const AllocaInst*, int> StaticAllocaMap;
113
114 #ifndef NDEBUG
115   SmallSet<Instruction*, 8> CatchInfoLost;
116   SmallSet<Instruction*, 8> CatchInfoFound;
117 #endif
118
119   unsigned MakeReg(MVT VT);
120   
121   /// isExportedInst - Return true if the specified value is an instruction
122   /// exported from its block.
123   bool isExportedInst(const Value *V) {
124     return ValueMap.count(V);
125   }
126
127   unsigned CreateRegForValue(const Value *V);
128   
129   unsigned InitializeRegForValue(const Value *V) {
130     unsigned &R = ValueMap[V];
131     assert(R == 0 && "Already initialized this value register!");
132     return R = CreateRegForValue(V);
133   }
134   
135   struct LiveOutInfo {
136     unsigned NumSignBits;
137     APInt KnownOne, KnownZero;
138     LiveOutInfo() : NumSignBits(0) {}
139   };
140   
141   /// LiveOutRegInfo - Information about live out vregs, indexed by their
142   /// register number offset by 'FirstVirtualRegister'.
143   std::vector<LiveOutInfo> LiveOutRegInfo;
144
145   /// clear - Clear out all the function-specific state. This returns this
146   /// FunctionLoweringInfo to an empty state, ready to be used for a
147   /// different function.
148   void clear() {
149     MBBMap.clear();
150     ValueMap.clear();
151     StaticAllocaMap.clear();
152 #ifndef NDEBUG
153     CatchInfoLost.clear();
154     CatchInfoFound.clear();
155 #endif
156     LiveOutRegInfo.clear();
157   }
158 };
159
160 //===----------------------------------------------------------------------===//
161 /// SelectionDAGLowering - This is the common target-independent lowering
162 /// implementation that is parameterized by a TargetLowering object.
163 /// Also, targets can overload any lowering method.
164 ///
165 class SelectionDAGLowering {
166   MachineBasicBlock *CurMBB;
167
168   /// CurDebugLoc - current file + line number.  Changes as we build the DAG.
169   DebugLoc CurDebugLoc;
170
171   DenseMap<const Value*, SDValue> NodeMap;
172
173   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
174   /// them up and then emit token factor nodes when possible.  This allows us to
175   /// get simple disambiguation between loads without worrying about alias
176   /// analysis.
177   SmallVector<SDValue, 8> PendingLoads;
178
179   /// PendingExports - CopyToReg nodes that copy values to virtual registers
180   /// for export to other blocks need to be emitted before any terminator
181   /// instruction, but they have no other ordering requirements. We bunch them
182   /// up and the emit a single tokenfactor for them just before terminator
183   /// instructions.
184   SmallVector<SDValue, 8> PendingExports;
185
186   /// Case - A struct to record the Value for a switch case, and the
187   /// case's target basic block.
188   struct Case {
189     Constant* Low;
190     Constant* High;
191     MachineBasicBlock* BB;
192
193     Case() : Low(0), High(0), BB(0) { }
194     Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
195       Low(low), High(high), BB(bb) { }
196     uint64_t size() const {
197       uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
198       uint64_t rLow  = cast<ConstantInt>(Low)->getSExtValue();
199       return (rHigh - rLow + 1ULL);
200     }
201   };
202
203   struct CaseBits {
204     uint64_t Mask;
205     MachineBasicBlock* BB;
206     unsigned Bits;
207
208     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
209       Mask(mask), BB(bb), Bits(bits) { }
210   };
211
212   typedef std::vector<Case>           CaseVector;
213   typedef std::vector<CaseBits>       CaseBitsVector;
214   typedef CaseVector::iterator        CaseItr;
215   typedef std::pair<CaseItr, CaseItr> CaseRange;
216
217   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
218   /// of conditional branches.
219   struct CaseRec {
220     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
221     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
222
223     /// CaseBB - The MBB in which to emit the compare and branch
224     MachineBasicBlock *CaseBB;
225     /// LT, GE - If nonzero, we know the current case value must be less-than or
226     /// greater-than-or-equal-to these Constants.
227     Constant *LT;
228     Constant *GE;
229     /// Range - A pair of iterators representing the range of case values to be
230     /// processed at this point in the binary search tree.
231     CaseRange Range;
232   };
233
234   typedef std::vector<CaseRec> CaseRecVector;
235
236   /// The comparison function for sorting the switch case values in the vector.
237   /// WARNING: Case ranges should be disjoint!
238   struct CaseCmp {
239     bool operator () (const Case& C1, const Case& C2) {
240       assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
241       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
242       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
243       return CI1->getValue().slt(CI2->getValue());
244     }
245   };
246
247   struct CaseBitsCmp {
248     bool operator () (const CaseBits& C1, const CaseBits& C2) {
249       return C1.Bits > C2.Bits;
250     }
251   };
252
253   size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
254
255   /// CaseBlock - This structure is used to communicate between SDLowering and
256   /// SDISel for the code generation of additional basic blocks needed by multi-
257   /// case switch statements.
258   struct CaseBlock {
259     CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
260               MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
261               MachineBasicBlock *me)
262       : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
263         TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
264     // CC - the condition code to use for the case block's setcc node
265     ISD::CondCode CC;
266     // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
267     // Emit by default LHS op RHS. MHS is used for range comparisons:
268     // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
269     Value *CmpLHS, *CmpMHS, *CmpRHS;
270     // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
271     MachineBasicBlock *TrueBB, *FalseBB;
272     // ThisBB - the block into which to emit the code for the setcc and branches
273     MachineBasicBlock *ThisBB;
274   };
275   struct JumpTable {
276     JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
277               MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
278   
279     /// Reg - the virtual register containing the index of the jump table entry
280     //. to jump to.
281     unsigned Reg;
282     /// JTI - the JumpTableIndex for this jump table in the function.
283     unsigned JTI;
284     /// MBB - the MBB into which to emit the code for the indirect jump.
285     MachineBasicBlock *MBB;
286     /// Default - the MBB of the default bb, which is a successor of the range
287     /// check MBB.  This is when updating PHI nodes in successors.
288     MachineBasicBlock *Default;
289   };
290   struct JumpTableHeader {
291     JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
292                     bool E = false):
293       First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
294     APInt First;
295     APInt Last;
296     Value *SValue;
297     MachineBasicBlock *HeaderBB;
298     bool Emitted;
299   };
300   typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
301
302   struct BitTestCase {
303     BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
304       Mask(M), ThisBB(T), TargetBB(Tr) { }
305     uint64_t Mask;
306     MachineBasicBlock* ThisBB;
307     MachineBasicBlock* TargetBB;
308   };
309
310   typedef SmallVector<BitTestCase, 3> BitTestInfo;
311
312   struct BitTestBlock {
313     BitTestBlock(APInt F, APInt R, Value* SV,
314                  unsigned Rg, bool E,
315                  MachineBasicBlock* P, MachineBasicBlock* D,
316                  const BitTestInfo& C):
317       First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
318       Parent(P), Default(D), Cases(C) { }
319     APInt First;
320     APInt Range;
321     Value  *SValue;
322     unsigned Reg;
323     bool Emitted;
324     MachineBasicBlock *Parent;
325     MachineBasicBlock *Default;
326     BitTestInfo Cases;
327   };
328
329 public:
330   // TLI - This is information that describes the available target features we
331   // need for lowering.  This indicates when operations are unavailable,
332   // implemented with a libcall, etc.
333   TargetLowering &TLI;
334   SelectionDAG &DAG;
335   const TargetData *TD;
336   AliasAnalysis *AA;
337
338   /// SwitchCases - Vector of CaseBlock structures used to communicate
339   /// SwitchInst code generation information.
340   std::vector<CaseBlock> SwitchCases;
341   /// JTCases - Vector of JumpTable structures used to communicate
342   /// SwitchInst code generation information.
343   std::vector<JumpTableBlock> JTCases;
344   /// BitTestCases - Vector of BitTestBlock structures used to communicate
345   /// SwitchInst code generation information.
346   std::vector<BitTestBlock> BitTestCases;
347   
348   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
349
350   // Emit PHI-node-operand constants only once even if used by multiple
351   // PHI nodes.
352   DenseMap<Constant*, unsigned> ConstantsOut;
353
354   /// FuncInfo - Information about the function as a whole.
355   ///
356   FunctionLoweringInfo &FuncInfo;
357   
358   /// GFI - Garbage collection metadata for the function.
359   GCFunctionInfo *GFI;
360
361   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
362                        FunctionLoweringInfo &funcinfo)
363     : CurDebugLoc(DebugLoc::getUnknownLoc()), 
364       TLI(tli), DAG(dag), FuncInfo(funcinfo) {
365   }
366
367   void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
368
369   /// clear - Clear out the curret SelectionDAG and the associated
370   /// state and prepare this SelectionDAGLowering object to be used
371   /// for a new block. This doesn't clear out information about
372   /// additional blocks that are needed to complete switch lowering
373   /// or PHI node updating; that information is cleared out as it is
374   /// consumed.
375   void clear();
376
377   /// getRoot - Return the current virtual root of the Selection DAG,
378   /// flushing any PendingLoad items. This must be done before emitting
379   /// a store or any other node that may need to be ordered after any
380   /// prior load instructions.
381   ///
382   SDValue getRoot();
383
384   /// getControlRoot - Similar to getRoot, but instead of flushing all the
385   /// PendingLoad items, flush all the PendingExports items. It is necessary
386   /// to do this before emitting a terminator instruction.
387   ///
388   SDValue getControlRoot();
389
390   DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
391
392   void CopyValueToVirtualRegister(Value *V, unsigned Reg);
393
394   void visit(Instruction &I);
395
396   void visit(unsigned Opcode, User &I);
397
398   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
399
400   SDValue getValue(const Value *V);
401
402   void setValue(const Value *V, SDValue NewN) {
403     SDValue &N = NodeMap[V];
404     assert(N.getNode() == 0 && "Already set a value for this node!");
405     N = NewN;
406   }
407   
408   void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
409                             std::set<unsigned> &OutputRegs, 
410                             std::set<unsigned> &InputRegs);
411
412   void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
413                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
414                             unsigned Opc);
415   void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
416                                     MachineBasicBlock *FBB,
417                                     MachineBasicBlock *CurBB);
418   bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
419   bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
420   void ExportFromCurrentBlock(Value *V);
421   void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
422                    MachineBasicBlock *LandingPad = NULL);
423
424 private:
425   // Terminator instructions.
426   void visitRet(ReturnInst &I);
427   void visitBr(BranchInst &I);
428   void visitSwitch(SwitchInst &I);
429   void visitUnreachable(UnreachableInst &I) { /* noop */ }
430
431   // Helpers for visitSwitch
432   bool handleSmallSwitchRange(CaseRec& CR,
433                               CaseRecVector& WorkList,
434                               Value* SV,
435                               MachineBasicBlock* Default);
436   bool handleJTSwitchCase(CaseRec& CR,
437                           CaseRecVector& WorkList,
438                           Value* SV,
439                           MachineBasicBlock* Default);
440   bool handleBTSplitSwitchCase(CaseRec& CR,
441                                CaseRecVector& WorkList,
442                                Value* SV,
443                                MachineBasicBlock* Default);
444   bool handleBitTestsSwitchCase(CaseRec& CR,
445                                 CaseRecVector& WorkList,
446                                 Value* SV,
447                                 MachineBasicBlock* Default);  
448 public:
449   void visitSwitchCase(CaseBlock &CB);
450   void visitBitTestHeader(BitTestBlock &B);
451   void visitBitTestCase(MachineBasicBlock* NextMBB,
452                         unsigned Reg,
453                         BitTestCase &B);
454   void visitJumpTable(JumpTable &JT);
455   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
456   
457 private:
458   // These all get lowered before this pass.
459   void visitInvoke(InvokeInst &I);
460   void visitUnwind(UnwindInst &I);
461
462   void visitBinary(User &I, unsigned OpCode);
463   void visitShift(User &I, unsigned Opcode);
464   void visitAdd(User &I);
465   void visitSub(User &I);
466   void visitMul(User &I);
467   void visitURem(User &I) { visitBinary(I, ISD::UREM); }
468   void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
469   void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
470   void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
471   void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
472   void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
473   void visitAnd (User &I) { visitBinary(I, ISD::AND); }
474   void visitOr  (User &I) { visitBinary(I, ISD::OR); }
475   void visitXor (User &I) { visitBinary(I, ISD::XOR); }
476   void visitShl (User &I) { visitShift(I, ISD::SHL); }
477   void visitLShr(User &I) { visitShift(I, ISD::SRL); }
478   void visitAShr(User &I) { visitShift(I, ISD::SRA); }
479   void visitICmp(User &I);
480   void visitFCmp(User &I);
481   void visitVICmp(User &I);
482   void visitVFCmp(User &I);
483   // Visit the conversion instructions
484   void visitTrunc(User &I);
485   void visitZExt(User &I);
486   void visitSExt(User &I);
487   void visitFPTrunc(User &I);
488   void visitFPExt(User &I);
489   void visitFPToUI(User &I);
490   void visitFPToSI(User &I);
491   void visitUIToFP(User &I);
492   void visitSIToFP(User &I);
493   void visitPtrToInt(User &I);
494   void visitIntToPtr(User &I);
495   void visitBitCast(User &I);
496
497   void visitExtractElement(User &I);
498   void visitInsertElement(User &I);
499   void visitShuffleVector(User &I);
500
501   void visitExtractValue(ExtractValueInst &I);
502   void visitInsertValue(InsertValueInst &I);
503
504   void visitGetElementPtr(User &I);
505   void visitSelect(User &I);
506
507   void visitMalloc(MallocInst &I);
508   void visitFree(FreeInst &I);
509   void visitAlloca(AllocaInst &I);
510   void visitLoad(LoadInst &I);
511   void visitStore(StoreInst &I);
512   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
513   void visitCall(CallInst &I);
514   void visitInlineAsm(CallSite CS);
515   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
516   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
517
518   void visitPow(CallInst &I);
519   void visitExp2(CallInst &I);
520   void visitExp(CallInst &I);
521   void visitLog(CallInst &I);
522   void visitLog2(CallInst &I);
523   void visitLog10(CallInst &I);
524
525   void visitVAStart(CallInst &I);
526   void visitVAArg(VAArgInst &I);
527   void visitVAEnd(CallInst &I);
528   void visitVACopy(CallInst &I);
529
530   void visitUserOp1(Instruction &I) {
531     assert(0 && "UserOp1 should not exist at instruction selection time!");
532     abort();
533   }
534   void visitUserOp2(Instruction &I) {
535     assert(0 && "UserOp2 should not exist at instruction selection time!");
536     abort();
537   }
538   
539   const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
540   const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
541
542   void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
543 };
544
545 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
546 /// call, and add them to the specified machine basic block.
547 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
548                   MachineBasicBlock *MBB);
549
550 } // end namespace llvm
551
552 #endif