Fix typos found by http://github.com/lyda/misspell-check
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.h
1 //===-- SelectionDAGBuilder.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 SELECTIONDAGBUILDER_H
15 #define SELECTIONDAGBUILDER_H
16
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/CodeGen/SelectionDAGNodes.h"
22 #include "llvm/CodeGen/ValueTypes.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <vector>
26
27 namespace llvm {
28
29 class AliasAnalysis;
30 class AllocaInst;
31 class BasicBlock;
32 class BitCastInst;
33 class BranchInst;
34 class CallInst;
35 class DbgValueInst;
36 class ExtractElementInst;
37 class ExtractValueInst;
38 class FCmpInst;
39 class FPExtInst;
40 class FPToSIInst;
41 class FPToUIInst;
42 class FPTruncInst;
43 class Function;
44 class FunctionLoweringInfo;
45 class GetElementPtrInst;
46 class GCFunctionInfo;
47 class ICmpInst;
48 class IntToPtrInst;
49 class IndirectBrInst;
50 class InvokeInst;
51 class InsertElementInst;
52 class InsertValueInst;
53 class Instruction;
54 class LoadInst;
55 class MachineBasicBlock;
56 class MachineInstr;
57 class MachineRegisterInfo;
58 class MDNode;
59 class PHINode;
60 class PtrToIntInst;
61 class ReturnInst;
62 class SDDbgValue;
63 class SExtInst;
64 class SelectInst;
65 class ShuffleVectorInst;
66 class SIToFPInst;
67 class StoreInst;
68 class SwitchInst;
69 class TargetData;
70 class TargetLibraryInfo;
71 class TargetLowering;
72 class TruncInst;
73 class UIToFPInst;
74 class UnreachableInst;
75 class VAArgInst;
76 class ZExtInst;
77
78 //===----------------------------------------------------------------------===//
79 /// SelectionDAGBuilder - This is the common target-independent lowering
80 /// implementation that is parameterized by a TargetLowering object.
81 ///
82 class SelectionDAGBuilder {
83   /// CurDebugLoc - current file + line number.  Changes as we build the DAG.
84   DebugLoc CurDebugLoc;
85
86   DenseMap<const Value*, SDValue> NodeMap;
87   
88   /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
89   /// to preserve debug information for incoming arguments.
90   DenseMap<const Value*, SDValue> UnusedArgNodeMap;
91
92   /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
93   class DanglingDebugInfo {
94     const DbgValueInst* DI;
95     DebugLoc dl;
96     unsigned SDNodeOrder;
97   public:
98     DanglingDebugInfo() : DI(0), dl(DebugLoc()), SDNodeOrder(0) { }
99     DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) :
100       DI(di), dl(DL), SDNodeOrder(SDNO) { }
101     const DbgValueInst* getDI() { return DI; }
102     DebugLoc getdl() { return dl; }
103     unsigned getSDNodeOrder() { return SDNodeOrder; }
104   };
105
106   /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
107   /// yet seen the referent.  We defer handling these until we do see it.
108   DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
109
110 public:
111   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
112   /// them up and then emit token factor nodes when possible.  This allows us to
113   /// get simple disambiguation between loads without worrying about alias
114   /// analysis.
115   SmallVector<SDValue, 8> PendingLoads;
116 private:
117
118   /// PendingExports - CopyToReg nodes that copy values to virtual registers
119   /// for export to other blocks need to be emitted before any terminator
120   /// instruction, but they have no other ordering requirements. We bunch them
121   /// up and the emit a single tokenfactor for them just before terminator
122   /// instructions.
123   SmallVector<SDValue, 8> PendingExports;
124
125   /// SDNodeOrder - A unique monotonically increasing number used to order the
126   /// SDNodes we create.
127   unsigned SDNodeOrder;
128
129   /// Case - A struct to record the Value for a switch case, and the
130   /// case's target basic block.
131   struct Case {
132     const Constant *Low;
133     const Constant *High;
134     MachineBasicBlock* BB;
135     uint32_t ExtraWeight;
136
137     Case() : Low(0), High(0), BB(0), ExtraWeight(0) { }
138     Case(const Constant *low, const Constant *high, MachineBasicBlock *bb,
139          uint32_t extraweight) : Low(low), High(high), BB(bb),
140          ExtraWeight(extraweight) { }
141
142     APInt size() const {
143       const APInt &rHigh = cast<ConstantInt>(High)->getValue();
144       const APInt &rLow  = cast<ConstantInt>(Low)->getValue();
145       return (rHigh - rLow + 1ULL);
146     }
147   };
148
149   struct CaseBits {
150     uint64_t Mask;
151     MachineBasicBlock* BB;
152     unsigned Bits;
153
154     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
155       Mask(mask), BB(bb), Bits(bits) { }
156   };
157
158   typedef std::vector<Case>           CaseVector;
159   typedef std::vector<CaseBits>       CaseBitsVector;
160   typedef CaseVector::iterator        CaseItr;
161   typedef std::pair<CaseItr, CaseItr> CaseRange;
162
163   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
164   /// of conditional branches.
165   struct CaseRec {
166     CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge,
167             CaseRange r) :
168     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
169
170     /// CaseBB - The MBB in which to emit the compare and branch
171     MachineBasicBlock *CaseBB;
172     /// LT, GE - If nonzero, we know the current case value must be less-than or
173     /// greater-than-or-equal-to these Constants.
174     const Constant *LT;
175     const Constant *GE;
176     /// Range - A pair of iterators representing the range of case values to be
177     /// processed at this point in the binary search tree.
178     CaseRange Range;
179   };
180
181   typedef std::vector<CaseRec> CaseRecVector;
182
183   struct CaseBitsCmp {
184     bool operator()(const CaseBits &C1, const CaseBits &C2) {
185       return C1.Bits > C2.Bits;
186     }
187   };
188
189   size_t Clusterify(CaseVector &Cases, const SwitchInst &SI);
190
191   /// CaseBlock - This structure is used to communicate between
192   /// SelectionDAGBuilder and SDISel for the code generation of additional basic
193   /// blocks needed by multi-case switch statements.
194   struct CaseBlock {
195     CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
196               const Value *cmpmiddle,
197               MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
198               MachineBasicBlock *me,
199               uint32_t trueweight = 0, uint32_t falseweight = 0)
200       : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
201         TrueBB(truebb), FalseBB(falsebb), ThisBB(me),
202         TrueWeight(trueweight), FalseWeight(falseweight) { }
203
204     // CC - the condition code to use for the case block's setcc node
205     ISD::CondCode CC;
206
207     // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
208     // Emit by default LHS op RHS. MHS is used for range comparisons:
209     // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
210     const Value *CmpLHS, *CmpMHS, *CmpRHS;
211
212     // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
213     MachineBasicBlock *TrueBB, *FalseBB;
214
215     // ThisBB - the block into which to emit the code for the setcc and branches
216     MachineBasicBlock *ThisBB;
217
218     // TrueWeight/FalseWeight - branch weights.
219     uint32_t TrueWeight, FalseWeight;
220   };
221
222   struct JumpTable {
223     JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
224               MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
225   
226     /// Reg - the virtual register containing the index of the jump table entry
227     //. to jump to.
228     unsigned Reg;
229     /// JTI - the JumpTableIndex for this jump table in the function.
230     unsigned JTI;
231     /// MBB - the MBB into which to emit the code for the indirect jump.
232     MachineBasicBlock *MBB;
233     /// Default - the MBB of the default bb, which is a successor of the range
234     /// check MBB.  This is when updating PHI nodes in successors.
235     MachineBasicBlock *Default;
236   };
237   struct JumpTableHeader {
238     JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
239                     bool E = false):
240       First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
241     APInt First;
242     APInt Last;
243     const Value *SValue;
244     MachineBasicBlock *HeaderBB;
245     bool Emitted;
246   };
247   typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
248
249   struct BitTestCase {
250     BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
251       Mask(M), ThisBB(T), TargetBB(Tr) { }
252     uint64_t Mask;
253     MachineBasicBlock *ThisBB;
254     MachineBasicBlock *TargetBB;
255   };
256
257   typedef SmallVector<BitTestCase, 3> BitTestInfo;
258
259   struct BitTestBlock {
260     BitTestBlock(APInt F, APInt R, const Value* SV,
261                  unsigned Rg, EVT RgVT, bool E,
262                  MachineBasicBlock* P, MachineBasicBlock* D,
263                  const BitTestInfo& C):
264       First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E),
265       Parent(P), Default(D), Cases(C) { }
266     APInt First;
267     APInt Range;
268     const Value *SValue;
269     unsigned Reg;
270     EVT RegVT;
271     bool Emitted;
272     MachineBasicBlock *Parent;
273     MachineBasicBlock *Default;
274     BitTestInfo Cases;
275   };
276
277 public:
278   // TLI - This is information that describes the available target features we
279   // need for lowering.  This indicates when operations are unavailable,
280   // implemented with a libcall, etc.
281   const TargetMachine &TM;
282   const TargetLowering &TLI;
283   SelectionDAG &DAG;
284   const TargetData *TD;
285   AliasAnalysis *AA;
286   const TargetLibraryInfo *LibInfo;
287
288   /// SwitchCases - Vector of CaseBlock structures used to communicate
289   /// SwitchInst code generation information.
290   std::vector<CaseBlock> SwitchCases;
291   /// JTCases - Vector of JumpTable structures used to communicate
292   /// SwitchInst code generation information.
293   std::vector<JumpTableBlock> JTCases;
294   /// BitTestCases - Vector of BitTestBlock structures used to communicate
295   /// SwitchInst code generation information.
296   std::vector<BitTestBlock> BitTestCases;
297
298   // Emit PHI-node-operand constants only once even if used by multiple
299   // PHI nodes.
300   DenseMap<const Constant *, unsigned> ConstantsOut;
301
302   /// FuncInfo - Information about the function as a whole.
303   ///
304   FunctionLoweringInfo &FuncInfo;
305
306   /// OptLevel - What optimization level we're generating code for.
307   /// 
308   CodeGenOpt::Level OptLevel;
309   
310   /// GFI - Garbage collection metadata for the function.
311   GCFunctionInfo *GFI;
312
313   /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
314   DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
315
316   /// HasTailCall - This is set to true if a call in the current
317   /// block has been translated as a tail call. In this case,
318   /// no subsequent DAG nodes should be created.
319   ///
320   bool HasTailCall;
321
322   LLVMContext *Context;
323
324   SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
325                       CodeGenOpt::Level ol)
326     : SDNodeOrder(0), TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
327       DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
328       HasTailCall(false), Context(dag.getContext()) {
329   }
330
331   void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
332             const TargetLibraryInfo *li);
333
334   /// clear - Clear out the current SelectionDAG and the associated
335   /// state and prepare this SelectionDAGBuilder object to be used
336   /// for a new block. This doesn't clear out information about
337   /// additional blocks that are needed to complete switch lowering
338   /// or PHI node updating; that information is cleared out as it is
339   /// consumed.
340   void clear();
341
342   /// clearDanglingDebugInfo - Clear the dangling debug information
343   /// map. This function is separated from the clear so that debug
344   /// information that is dangling in a basic block can be properly
345   /// resolved in a different basic block. This allows the
346   /// SelectionDAG to resolve dangling debug information attached
347   /// to PHI nodes.
348   void clearDanglingDebugInfo();
349
350   /// getRoot - Return the current virtual root of the Selection DAG,
351   /// flushing any PendingLoad items. This must be done before emitting
352   /// a store or any other node that may need to be ordered after any
353   /// prior load instructions.
354   ///
355   SDValue getRoot();
356
357   /// getControlRoot - Similar to getRoot, but instead of flushing all the
358   /// PendingLoad items, flush all the PendingExports items. It is necessary
359   /// to do this before emitting a terminator instruction.
360   ///
361   SDValue getControlRoot();
362
363   DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
364
365   unsigned getSDNodeOrder() const { return SDNodeOrder; }
366
367   void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
368
369   /// AssignOrderingToNode - Assign an ordering to the node. The order is gotten
370   /// from how the code appeared in the source. The ordering is used by the
371   /// scheduler to effectively turn off scheduling.
372   void AssignOrderingToNode(const SDNode *Node);
373
374   void visit(const Instruction &I);
375
376   void visit(unsigned Opcode, const User &I);
377
378   // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
379   // generate the debug data structures now that we've seen its definition.
380   void resolveDanglingDebugInfo(const Value *V, SDValue Val);
381   SDValue getValue(const Value *V);
382   SDValue getNonRegisterValue(const Value *V);
383   SDValue getValueImpl(const Value *V);
384
385   void setValue(const Value *V, SDValue NewN) {
386     SDValue &N = NodeMap[V];
387     assert(N.getNode() == 0 && "Already set a value for this node!");
388     N = NewN;
389   }
390   
391   void setUnusedArgValue(const Value *V, SDValue NewN) {
392     SDValue &N = UnusedArgNodeMap[V];
393     assert(N.getNode() == 0 && "Already set a value for this node!");
394     N = NewN;
395   }
396
397   void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
398                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
399                             MachineBasicBlock *SwitchBB, unsigned Opc);
400   void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
401                                     MachineBasicBlock *FBB,
402                                     MachineBasicBlock *CurBB,
403                                     MachineBasicBlock *SwitchBB);
404   bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
405   bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
406   void CopyToExportRegsIfNeeded(const Value *V);
407   void ExportFromCurrentBlock(const Value *V);
408   void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
409                    MachineBasicBlock *LandingPad = NULL);
410
411   /// UpdateSplitBlock - When an MBB was split during scheduling, update the
412   /// references that ned to refer to the last resulting block.
413   void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
414
415 private:
416   // Terminator instructions.
417   void visitRet(const ReturnInst &I);
418   void visitBr(const BranchInst &I);
419   void visitSwitch(const SwitchInst &I);
420   void visitIndirectBr(const IndirectBrInst &I);
421   void visitUnreachable(const UnreachableInst &I) { /* noop */ }
422
423   // Helpers for visitSwitch
424   bool handleSmallSwitchRange(CaseRec& CR,
425                               CaseRecVector& WorkList,
426                               const Value* SV,
427                               MachineBasicBlock* Default,
428                               MachineBasicBlock *SwitchBB);
429   bool handleJTSwitchCase(CaseRec& CR,
430                           CaseRecVector& WorkList,
431                           const Value* SV,
432                           MachineBasicBlock* Default,
433                           MachineBasicBlock *SwitchBB);
434   bool handleBTSplitSwitchCase(CaseRec& CR,
435                                CaseRecVector& WorkList,
436                                const Value* SV,
437                                MachineBasicBlock* Default,
438                                MachineBasicBlock *SwitchBB);
439   bool handleBitTestsSwitchCase(CaseRec& CR,
440                                 CaseRecVector& WorkList,
441                                 const Value* SV,
442                                 MachineBasicBlock* Default,
443                                 MachineBasicBlock *SwitchBB);
444
445   uint32_t getEdgeWeight(const MachineBasicBlock *Src,
446                          const MachineBasicBlock *Dst) const;
447   void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
448                               uint32_t Weight = 0);
449 public:
450   void visitSwitchCase(CaseBlock &CB,
451                        MachineBasicBlock *SwitchBB);
452   void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
453   void visitBitTestCase(BitTestBlock &BB,
454                         MachineBasicBlock* NextMBB,
455                         unsigned Reg,
456                         BitTestCase &B,
457                         MachineBasicBlock *SwitchBB);
458   void visitJumpTable(JumpTable &JT);
459   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
460                             MachineBasicBlock *SwitchBB);
461   
462 private:
463   // These all get lowered before this pass.
464   void visitInvoke(const InvokeInst &I);
465   void visitResume(const ResumeInst &I);
466
467   void visitBinary(const User &I, unsigned OpCode);
468   void visitShift(const User &I, unsigned Opcode);
469   void visitAdd(const User &I)  { visitBinary(I, ISD::ADD); }
470   void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
471   void visitSub(const User &I)  { visitBinary(I, ISD::SUB); }
472   void visitFSub(const User &I);
473   void visitMul(const User &I)  { visitBinary(I, ISD::MUL); }
474   void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
475   void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
476   void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
477   void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
478   void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
479   void visitSDiv(const User &I);
480   void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
481   void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
482   void visitOr  (const User &I) { visitBinary(I, ISD::OR); }
483   void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
484   void visitShl (const User &I) { visitShift(I, ISD::SHL); }
485   void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
486   void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
487   void visitICmp(const User &I);
488   void visitFCmp(const User &I);
489   // Visit the conversion instructions
490   void visitTrunc(const User &I);
491   void visitZExt(const User &I);
492   void visitSExt(const User &I);
493   void visitFPTrunc(const User &I);
494   void visitFPExt(const User &I);
495   void visitFPToUI(const User &I);
496   void visitFPToSI(const User &I);
497   void visitUIToFP(const User &I);
498   void visitSIToFP(const User &I);
499   void visitPtrToInt(const User &I);
500   void visitIntToPtr(const User &I);
501   void visitBitCast(const User &I);
502
503   void visitExtractElement(const User &I);
504   void visitInsertElement(const User &I);
505   void visitShuffleVector(const User &I);
506
507   void visitExtractValue(const ExtractValueInst &I);
508   void visitInsertValue(const InsertValueInst &I);
509   void visitLandingPad(const LandingPadInst &I);
510
511   void visitGetElementPtr(const User &I);
512   void visitSelect(const User &I);
513
514   void visitAlloca(const AllocaInst &I);
515   void visitLoad(const LoadInst &I);
516   void visitStore(const StoreInst &I);
517   void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
518   void visitAtomicRMW(const AtomicRMWInst &I);
519   void visitFence(const FenceInst &I);
520   void visitPHI(const PHINode &I);
521   void visitCall(const CallInst &I);
522   bool visitMemCmpCall(const CallInst &I);
523   void visitAtomicLoad(const LoadInst &I);
524   void visitAtomicStore(const StoreInst &I);
525
526   void visitInlineAsm(ImmutableCallSite CS);
527   const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
528   void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
529
530   void visitPow(const CallInst &I);
531   void visitExp2(const CallInst &I);
532   void visitExp(const CallInst &I);
533   void visitLog(const CallInst &I);
534   void visitLog2(const CallInst &I);
535   void visitLog10(const CallInst &I);
536
537   void visitVAStart(const CallInst &I);
538   void visitVAArg(const VAArgInst &I);
539   void visitVAEnd(const CallInst &I);
540   void visitVACopy(const CallInst &I);
541
542   void visitUserOp1(const Instruction &I) {
543     llvm_unreachable("UserOp1 should not exist at instruction selection time!");
544   }
545   void visitUserOp2(const Instruction &I) {
546     llvm_unreachable("UserOp2 should not exist at instruction selection time!");
547   }
548
549   void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
550
551   /// EmitFuncArgumentDbgValue - If V is an function argument then create
552   /// corresponding DBG_VALUE machine instruction for it now. At the end of 
553   /// instruction selection, they will be inserted to the entry BB.
554   bool EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
555                                 int64_t Offset, const SDValue &N);
556 };
557
558 } // end namespace llvm
559
560 #endif