Switch lowering: extract jump tables and bit tests before building binary tree (PR22262)
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.h
1 //===-- SelectionDAGBuilder.h - Selection-DAG building --------*- C++ -*---===//
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 LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
15 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
16
17 #include "StatepointLowering.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SelectionDAGNodes.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Statepoint.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include <vector>
28
29 namespace llvm {
30
31 class AddrSpaceCastInst;
32 class AliasAnalysis;
33 class AllocaInst;
34 class BasicBlock;
35 class BitCastInst;
36 class BranchInst;
37 class CallInst;
38 class DbgValueInst;
39 class ExtractElementInst;
40 class ExtractValueInst;
41 class FCmpInst;
42 class FPExtInst;
43 class FPToSIInst;
44 class FPToUIInst;
45 class FPTruncInst;
46 class Function;
47 class FunctionLoweringInfo;
48 class GetElementPtrInst;
49 class GCFunctionInfo;
50 class ICmpInst;
51 class IntToPtrInst;
52 class IndirectBrInst;
53 class InvokeInst;
54 class InsertElementInst;
55 class InsertValueInst;
56 class Instruction;
57 class LoadInst;
58 class MachineBasicBlock;
59 class MachineInstr;
60 class MachineRegisterInfo;
61 class MDNode;
62 class MVT;
63 class PHINode;
64 class PtrToIntInst;
65 class ReturnInst;
66 class SDDbgValue;
67 class SExtInst;
68 class SelectInst;
69 class ShuffleVectorInst;
70 class SIToFPInst;
71 class StoreInst;
72 class SwitchInst;
73 class DataLayout;
74 class TargetLibraryInfo;
75 class TargetLowering;
76 class TruncInst;
77 class UIToFPInst;
78 class UnreachableInst;
79 class VAArgInst;
80 class ZExtInst;
81
82 //===----------------------------------------------------------------------===//
83 /// SelectionDAGBuilder - This is the common target-independent lowering
84 /// implementation that is parameterized by a TargetLowering object.
85 ///
86 class SelectionDAGBuilder {
87   /// CurInst - The current instruction being visited
88   const Instruction *CurInst;
89
90   DenseMap<const Value*, SDValue> NodeMap;
91
92   /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
93   /// to preserve debug information for incoming arguments.
94   DenseMap<const Value*, SDValue> UnusedArgNodeMap;
95
96   /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
97   class DanglingDebugInfo {
98     const DbgValueInst* DI;
99     DebugLoc dl;
100     unsigned SDNodeOrder;
101   public:
102     DanglingDebugInfo() : DI(nullptr), dl(DebugLoc()), SDNodeOrder(0) { }
103     DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) :
104       DI(di), dl(DL), SDNodeOrder(SDNO) { }
105     const DbgValueInst* getDI() { return DI; }
106     DebugLoc getdl() { return dl; }
107     unsigned getSDNodeOrder() { return SDNodeOrder; }
108   };
109
110   /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
111   /// yet seen the referent.  We defer handling these until we do see it.
112   DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
113
114 public:
115   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
116   /// them up and then emit token factor nodes when possible.  This allows us to
117   /// get simple disambiguation between loads without worrying about alias
118   /// analysis.
119   SmallVector<SDValue, 8> PendingLoads;
120
121   /// State used while lowering a statepoint sequence (gc_statepoint,
122   /// gc_relocate, and gc_result).  See StatepointLowering.hpp/cpp for details.
123   StatepointLoweringState StatepointLowering;
124 private:
125
126   /// PendingExports - CopyToReg nodes that copy values to virtual registers
127   /// for export to other blocks need to be emitted before any terminator
128   /// instruction, but they have no other ordering requirements. We bunch them
129   /// up and the emit a single tokenfactor for them just before terminator
130   /// instructions.
131   SmallVector<SDValue, 8> PendingExports;
132
133   /// SDNodeOrder - A unique monotonically increasing number used to order the
134   /// SDNodes we create.
135   unsigned SDNodeOrder;
136
137   enum CaseClusterKind {
138     /// A cluster of adjacent case labels with the same destination, or just one
139     /// case.
140     CC_Range,
141     /// A cluster of cases suitable for jump table lowering.
142     CC_JumpTable,
143     /// A cluster of cases suitable for bit test lowering.
144     CC_BitTests
145   };
146
147   /// A cluster of case labels.
148   struct CaseCluster {
149     CaseClusterKind Kind;
150     const ConstantInt *Low, *High;
151     union {
152       MachineBasicBlock *MBB;
153       unsigned JTCasesIndex;
154       unsigned BTCasesIndex;
155     };
156     uint64_t Weight;
157
158     static CaseCluster range(const ConstantInt *Low, const ConstantInt *High,
159                              MachineBasicBlock *MBB, uint32_t Weight) {
160       CaseCluster C;
161       C.Kind = CC_Range;
162       C.Low = Low;
163       C.High = High;
164       C.MBB = MBB;
165       C.Weight = Weight;
166       return C;
167     }
168
169     static CaseCluster jumpTable(const ConstantInt *Low,
170                                  const ConstantInt *High, unsigned JTCasesIndex,
171                                  uint32_t Weight) {
172       CaseCluster C;
173       C.Kind = CC_JumpTable;
174       C.Low = Low;
175       C.High = High;
176       C.JTCasesIndex = JTCasesIndex;
177       C.Weight = Weight;
178       return C;
179     }
180
181     static CaseCluster bitTests(const ConstantInt *Low, const ConstantInt *High,
182                                 unsigned BTCasesIndex, uint32_t Weight) {
183       CaseCluster C;
184       C.Kind = CC_BitTests;
185       C.Low = Low;
186       C.High = High;
187       C.BTCasesIndex = BTCasesIndex;
188       C.Weight = Weight;
189       return C;
190     }
191   };
192
193   typedef std::vector<CaseCluster> CaseClusterVector;
194   typedef CaseClusterVector::iterator CaseClusterIt;
195
196   struct CaseBits {
197     uint64_t Mask;
198     MachineBasicBlock* BB;
199     unsigned Bits;
200     uint32_t ExtraWeight;
201
202     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits,
203              uint32_t Weight):
204       Mask(mask), BB(bb), Bits(bits), ExtraWeight(Weight) { }
205
206     CaseBits() : Mask(0), BB(nullptr), Bits(0), ExtraWeight(0) {}
207   };
208
209   typedef std::vector<CaseBits> CaseBitsVector;
210
211   /// Sort Clusters and merge adjacent cases.
212   void sortAndRangeify(CaseClusterVector &Clusters);
213
214   /// CaseBlock - This structure is used to communicate between
215   /// SelectionDAGBuilder and SDISel for the code generation of additional basic
216   /// blocks needed by multi-case switch statements.
217   struct CaseBlock {
218     CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
219               const Value *cmpmiddle,
220               MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
221               MachineBasicBlock *me,
222               uint32_t trueweight = 0, uint32_t falseweight = 0)
223       : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
224         TrueBB(truebb), FalseBB(falsebb), ThisBB(me),
225         TrueWeight(trueweight), FalseWeight(falseweight) { }
226
227     // CC - the condition code to use for the case block's setcc node
228     ISD::CondCode CC;
229
230     // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
231     // Emit by default LHS op RHS. MHS is used for range comparisons:
232     // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
233     const Value *CmpLHS, *CmpMHS, *CmpRHS;
234
235     // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
236     MachineBasicBlock *TrueBB, *FalseBB;
237
238     // ThisBB - the block into which to emit the code for the setcc and branches
239     MachineBasicBlock *ThisBB;
240
241     // TrueWeight/FalseWeight - branch weights.
242     uint32_t TrueWeight, FalseWeight;
243   };
244
245   struct JumpTable {
246     JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
247               MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
248
249     /// Reg - the virtual register containing the index of the jump table entry
250     //. to jump to.
251     unsigned Reg;
252     /// JTI - the JumpTableIndex for this jump table in the function.
253     unsigned JTI;
254     /// MBB - the MBB into which to emit the code for the indirect jump.
255     MachineBasicBlock *MBB;
256     /// Default - the MBB of the default bb, which is a successor of the range
257     /// check MBB.  This is when updating PHI nodes in successors.
258     MachineBasicBlock *Default;
259   };
260   struct JumpTableHeader {
261     JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
262                     bool E = false):
263       First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
264     APInt First;
265     APInt Last;
266     const Value *SValue;
267     MachineBasicBlock *HeaderBB;
268     bool Emitted;
269   };
270   typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
271
272   struct BitTestCase {
273     BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr,
274                 uint32_t Weight):
275       Mask(M), ThisBB(T), TargetBB(Tr), ExtraWeight(Weight) { }
276     uint64_t Mask;
277     MachineBasicBlock *ThisBB;
278     MachineBasicBlock *TargetBB;
279     uint32_t ExtraWeight;
280   };
281
282   typedef SmallVector<BitTestCase, 3> BitTestInfo;
283
284   struct BitTestBlock {
285     BitTestBlock(APInt F, APInt R, const Value* SV,
286                  unsigned Rg, MVT RgVT, bool E,
287                  MachineBasicBlock* P, MachineBasicBlock* D,
288                  BitTestInfo C):
289       First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E),
290       Parent(P), Default(D), Cases(std::move(C)) { }
291     APInt First;
292     APInt Range;
293     const Value *SValue;
294     unsigned Reg;
295     MVT RegVT;
296     bool Emitted;
297     MachineBasicBlock *Parent;
298     MachineBasicBlock *Default;
299     BitTestInfo Cases;
300   };
301
302   /// Minimum jump table density, in percent.
303   enum { MinJumpTableDensity = 40 };
304
305   /// Check whether a range of clusters is dense enough for a jump table.
306   bool isDense(const CaseClusterVector &Clusters, unsigned *TotalCases,
307                unsigned First, unsigned Last);
308
309   /// Build a jump table cluster from Clusters[First..Last]. Returns false if it
310   /// decides it's not a good idea.
311   bool buildJumpTable(CaseClusterVector &Clusters, unsigned First,
312                       unsigned Last, const SwitchInst *SI,
313                       MachineBasicBlock *DefaultMBB, CaseCluster &JTCluster);
314
315   /// Find clusters of cases suitable for jump table lowering.
316   void findJumpTables(CaseClusterVector &Clusters, const SwitchInst *SI,
317                       MachineBasicBlock *DefaultMBB);
318
319   /// Check whether the range [Low,High] fits in a machine word.
320   bool rangeFitsInWord(const APInt &Low, const APInt &High);
321
322   /// Check whether these clusters are suitable for lowering with bit tests based
323   /// on the number of destinations, comparison metric, and range.
324   bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
325                              const APInt &Low, const APInt &High);
326
327   /// Build a bit test cluster from Clusters[First..Last]. Returns false if it
328   /// decides it's not a good idea.
329   bool buildBitTests(CaseClusterVector &Clusters, unsigned First, unsigned Last,
330                      const SwitchInst *SI, CaseCluster &BTCluster);
331
332   /// Find clusters of cases suitable for bit test lowering.
333   void findBitTestClusters(CaseClusterVector &Clusters, const SwitchInst *SI);
334
335   struct SwitchWorkListItem {
336     MachineBasicBlock *MBB;
337     CaseClusterIt FirstCluster;
338     CaseClusterIt LastCluster;
339     const ConstantInt *GE;
340     const ConstantInt *LT;
341   };
342   typedef SmallVector<SwitchWorkListItem, 4> SwitchWorkList;
343
344   /// Emit comparison and split W into two subtrees.
345   void splitWorkItem(SwitchWorkList &WorkList, const SwitchWorkListItem &W,
346                      Value *Cond, MachineBasicBlock *SwitchMBB);
347
348   /// Lower W.
349   void lowerWorkItem(SwitchWorkListItem W, Value *Cond,
350                      MachineBasicBlock *SwitchMBB,
351                      MachineBasicBlock *DefaultMBB);
352
353
354   /// A class which encapsulates all of the information needed to generate a
355   /// stack protector check and signals to isel via its state being initialized
356   /// that a stack protector needs to be generated.
357   ///
358   /// *NOTE* The following is a high level documentation of SelectionDAG Stack
359   /// Protector Generation. The reason that it is placed here is for a lack of
360   /// other good places to stick it.
361   ///
362   /// High Level Overview of SelectionDAG Stack Protector Generation:
363   ///
364   /// Previously, generation of stack protectors was done exclusively in the
365   /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated
366   /// splitting basic blocks at the IR level to create the success/failure basic
367   /// blocks in the tail of the basic block in question. As a result of this,
368   /// calls that would have qualified for the sibling call optimization were no
369   /// longer eligible for optimization since said calls were no longer right in
370   /// the "tail position" (i.e. the immediate predecessor of a ReturnInst
371   /// instruction).
372   ///
373   /// Then it was noticed that since the sibling call optimization causes the
374   /// callee to reuse the caller's stack, if we could delay the generation of
375   /// the stack protector check until later in CodeGen after the sibling call
376   /// decision was made, we get both the tail call optimization and the stack
377   /// protector check!
378   ///
379   /// A few goals in solving this problem were:
380   ///
381   ///   1. Preserve the architecture independence of stack protector generation.
382   ///
383   ///   2. Preserve the normal IR level stack protector check for platforms like
384   ///      OpenBSD for which we support platform-specific stack protector
385   ///      generation.
386   ///
387   /// The main problem that guided the present solution is that one can not
388   /// solve this problem in an architecture independent manner at the IR level
389   /// only. This is because:
390   ///
391   ///   1. The decision on whether or not to perform a sibling call on certain
392   ///      platforms (for instance i386) requires lower level information
393   ///      related to available registers that can not be known at the IR level.
394   ///
395   ///   2. Even if the previous point were not true, the decision on whether to
396   ///      perform a tail call is done in LowerCallTo in SelectionDAG which
397   ///      occurs after the Stack Protector Pass. As a result, one would need to
398   ///      put the relevant callinst into the stack protector check success
399   ///      basic block (where the return inst is placed) and then move it back
400   ///      later at SelectionDAG/MI time before the stack protector check if the
401   ///      tail call optimization failed. The MI level option was nixed
402   ///      immediately since it would require platform-specific pattern
403   ///      matching. The SelectionDAG level option was nixed because
404   ///      SelectionDAG only processes one IR level basic block at a time
405   ///      implying one could not create a DAG Combine to move the callinst.
406   ///
407   /// To get around this problem a few things were realized:
408   ///
409   ///   1. While one can not handle multiple IR level basic blocks at the
410   ///      SelectionDAG Level, one can generate multiple machine basic blocks
411   ///      for one IR level basic block. This is how we handle bit tests and
412   ///      switches.
413   ///
414   ///   2. At the MI level, tail calls are represented via a special return
415   ///      MIInst called "tcreturn". Thus if we know the basic block in which we
416   ///      wish to insert the stack protector check, we get the correct behavior
417   ///      by always inserting the stack protector check right before the return
418   ///      statement. This is a "magical transformation" since no matter where
419   ///      the stack protector check intrinsic is, we always insert the stack
420   ///      protector check code at the end of the BB.
421   ///
422   /// Given the aforementioned constraints, the following solution was devised:
423   ///
424   ///   1. On platforms that do not support SelectionDAG stack protector check
425   ///      generation, allow for the normal IR level stack protector check
426   ///      generation to continue.
427   ///
428   ///   2. On platforms that do support SelectionDAG stack protector check
429   ///      generation:
430   ///
431   ///     a. Use the IR level stack protector pass to decide if a stack
432   ///        protector is required/which BB we insert the stack protector check
433   ///        in by reusing the logic already therein. If we wish to generate a
434   ///        stack protector check in a basic block, we place a special IR
435   ///        intrinsic called llvm.stackprotectorcheck right before the BB's
436   ///        returninst or if there is a callinst that could potentially be
437   ///        sibling call optimized, before the call inst.
438   ///
439   ///     b. Then when a BB with said intrinsic is processed, we codegen the BB
440   ///        normally via SelectBasicBlock. In said process, when we visit the
441   ///        stack protector check, we do not actually emit anything into the
442   ///        BB. Instead, we just initialize the stack protector descriptor
443   ///        class (which involves stashing information/creating the success
444   ///        mbbb and the failure mbb if we have not created one for this
445   ///        function yet) and export the guard variable that we are going to
446   ///        compare.
447   ///
448   ///     c. After we finish selecting the basic block, in FinishBasicBlock if
449   ///        the StackProtectorDescriptor attached to the SelectionDAGBuilder is
450   ///        initialized, we first find a splice point in the parent basic block
451   ///        before the terminator and then splice the terminator of said basic
452   ///        block into the success basic block. Then we code-gen a new tail for
453   ///        the parent basic block consisting of the two loads, the comparison,
454   ///        and finally two branches to the success/failure basic blocks. We
455   ///        conclude by code-gening the failure basic block if we have not
456   ///        code-gened it already (all stack protector checks we generate in
457   ///        the same function, use the same failure basic block).
458   class StackProtectorDescriptor {
459   public:
460     StackProtectorDescriptor() : ParentMBB(nullptr), SuccessMBB(nullptr),
461                                  FailureMBB(nullptr), Guard(nullptr),
462                                  GuardReg(0) { }
463
464     /// Returns true if all fields of the stack protector descriptor are
465     /// initialized implying that we should/are ready to emit a stack protector.
466     bool shouldEmitStackProtector() const {
467       return ParentMBB && SuccessMBB && FailureMBB && Guard;
468     }
469
470     /// Initialize the stack protector descriptor structure for a new basic
471     /// block.
472     void initialize(const BasicBlock *BB,
473                     MachineBasicBlock *MBB,
474                     const CallInst &StackProtCheckCall) {
475       // Make sure we are not initialized yet.
476       assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is "
477              "already initialized!");
478       ParentMBB = MBB;
479       SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true);
480       FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB);
481       if (!Guard)
482         Guard = StackProtCheckCall.getArgOperand(0);
483     }
484
485     /// Reset state that changes when we handle different basic blocks.
486     ///
487     /// This currently includes:
488     ///
489     /// 1. The specific basic block we are generating a
490     /// stack protector for (ParentMBB).
491     ///
492     /// 2. The successor machine basic block that will contain the tail of
493     /// parent mbb after we create the stack protector check (SuccessMBB). This
494     /// BB is visited only on stack protector check success.
495     void resetPerBBState() {
496       ParentMBB = nullptr;
497       SuccessMBB = nullptr;
498     }
499
500     /// Reset state that only changes when we switch functions.
501     ///
502     /// This currently includes:
503     ///
504     /// 1. FailureMBB since we reuse the failure code path for all stack
505     /// protector checks created in an individual function.
506     ///
507     /// 2.The guard variable since the guard variable we are checking against is
508     /// always the same.
509     void resetPerFunctionState() {
510       FailureMBB = nullptr;
511       Guard = nullptr;
512     }
513
514     MachineBasicBlock *getParentMBB() { return ParentMBB; }
515     MachineBasicBlock *getSuccessMBB() { return SuccessMBB; }
516     MachineBasicBlock *getFailureMBB() { return FailureMBB; }
517     const Value *getGuard() { return Guard; }
518
519     unsigned getGuardReg() const { return GuardReg; }
520     void setGuardReg(unsigned R) { GuardReg = R; }
521
522   private:
523     /// The basic block for which we are generating the stack protector.
524     ///
525     /// As a result of stack protector generation, we will splice the
526     /// terminators of this basic block into the successor mbb SuccessMBB and
527     /// replace it with a compare/branch to the successor mbbs
528     /// SuccessMBB/FailureMBB depending on whether or not the stack protector
529     /// was violated.
530     MachineBasicBlock *ParentMBB;
531
532     /// A basic block visited on stack protector check success that contains the
533     /// terminators of ParentMBB.
534     MachineBasicBlock *SuccessMBB;
535
536     /// This basic block visited on stack protector check failure that will
537     /// contain a call to __stack_chk_fail().
538     MachineBasicBlock *FailureMBB;
539
540     /// The guard variable which we will compare against the stored value in the
541     /// stack protector stack slot.
542     const Value *Guard;
543
544     /// The virtual register holding the stack guard value.
545     unsigned GuardReg;
546
547     /// Add a successor machine basic block to ParentMBB. If the successor mbb
548     /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic
549     /// block will be created. Assign a large weight if IsLikely is true.
550     MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB,
551                                        MachineBasicBlock *ParentMBB,
552                                        bool IsLikely,
553                                        MachineBasicBlock *SuccMBB = nullptr);
554   };
555
556 private:
557   const TargetMachine &TM;
558 public:
559   /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
560   /// nodes without a corresponding SDNode.
561   static const unsigned LowestSDNodeOrder = 1;
562
563   SelectionDAG &DAG;
564   const DataLayout *DL;
565   AliasAnalysis *AA;
566   const TargetLibraryInfo *LibInfo;
567
568   /// SwitchCases - Vector of CaseBlock structures used to communicate
569   /// SwitchInst code generation information.
570   std::vector<CaseBlock> SwitchCases;
571   /// JTCases - Vector of JumpTable structures used to communicate
572   /// SwitchInst code generation information.
573   std::vector<JumpTableBlock> JTCases;
574   /// BitTestCases - Vector of BitTestBlock structures used to communicate
575   /// SwitchInst code generation information.
576   std::vector<BitTestBlock> BitTestCases;
577   /// A StackProtectorDescriptor structure used to communicate stack protector
578   /// information in between SelectBasicBlock and FinishBasicBlock.
579   StackProtectorDescriptor SPDescriptor;
580
581   // Emit PHI-node-operand constants only once even if used by multiple
582   // PHI nodes.
583   DenseMap<const Constant *, unsigned> ConstantsOut;
584
585   /// FuncInfo - Information about the function as a whole.
586   ///
587   FunctionLoweringInfo &FuncInfo;
588
589   /// OptLevel - What optimization level we're generating code for.
590   ///
591   CodeGenOpt::Level OptLevel;
592
593   /// GFI - Garbage collection metadata for the function.
594   GCFunctionInfo *GFI;
595
596   /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
597   DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
598
599   /// HasTailCall - This is set to true if a call in the current
600   /// block has been translated as a tail call. In this case,
601   /// no subsequent DAG nodes should be created.
602   ///
603   bool HasTailCall;
604
605   LLVMContext *Context;
606
607   SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
608                       CodeGenOpt::Level ol)
609     : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()),
610       DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
611       HasTailCall(false) {
612   }
613
614   void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
615             const TargetLibraryInfo *li);
616
617   /// clear - Clear out the current SelectionDAG and the associated
618   /// state and prepare this SelectionDAGBuilder object to be used
619   /// for a new block. This doesn't clear out information about
620   /// additional blocks that are needed to complete switch lowering
621   /// or PHI node updating; that information is cleared out as it is
622   /// consumed.
623   void clear();
624
625   /// clearDanglingDebugInfo - Clear the dangling debug information
626   /// map. This function is separated from the clear so that debug
627   /// information that is dangling in a basic block can be properly
628   /// resolved in a different basic block. This allows the
629   /// SelectionDAG to resolve dangling debug information attached
630   /// to PHI nodes.
631   void clearDanglingDebugInfo();
632
633   /// getRoot - Return the current virtual root of the Selection DAG,
634   /// flushing any PendingLoad items. This must be done before emitting
635   /// a store or any other node that may need to be ordered after any
636   /// prior load instructions.
637   ///
638   SDValue getRoot();
639
640   /// getControlRoot - Similar to getRoot, but instead of flushing all the
641   /// PendingLoad items, flush all the PendingExports items. It is necessary
642   /// to do this before emitting a terminator instruction.
643   ///
644   SDValue getControlRoot();
645
646   SDLoc getCurSDLoc() const {
647     return SDLoc(CurInst, SDNodeOrder);
648   }
649
650   DebugLoc getCurDebugLoc() const {
651     return CurInst ? CurInst->getDebugLoc() : DebugLoc();
652   }
653
654   unsigned getSDNodeOrder() const { return SDNodeOrder; }
655
656   void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
657
658   void visit(const Instruction &I);
659
660   void visit(unsigned Opcode, const User &I);
661
662   /// getCopyFromRegs - If there was virtual register allocated for the value V
663   /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
664   SDValue getCopyFromRegs(const Value *V, Type *Ty);
665
666   // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
667   // generate the debug data structures now that we've seen its definition.
668   void resolveDanglingDebugInfo(const Value *V, SDValue Val);
669   SDValue getValue(const Value *V);
670   SDValue getNonRegisterValue(const Value *V);
671   SDValue getValueImpl(const Value *V);
672
673   void setValue(const Value *V, SDValue NewN) {
674     SDValue &N = NodeMap[V];
675     assert(!N.getNode() && "Already set a value for this node!");
676     N = NewN;
677   }
678
679   void removeValue(const Value *V) {
680     // This is to support hack in lowerCallFromStatepoint
681     // Should be removed when hack is resolved
682     NodeMap.erase(V);
683   }
684
685   void setUnusedArgValue(const Value *V, SDValue NewN) {
686     SDValue &N = UnusedArgNodeMap[V];
687     assert(!N.getNode() && "Already set a value for this node!");
688     N = NewN;
689   }
690
691   void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
692                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
693                             MachineBasicBlock *SwitchBB, unsigned Opc,
694                             uint32_t TW, uint32_t FW);
695   void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
696                                     MachineBasicBlock *FBB,
697                                     MachineBasicBlock *CurBB,
698                                     MachineBasicBlock *SwitchBB,
699                                     uint32_t TW, uint32_t FW);
700   bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
701   bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
702   void CopyToExportRegsIfNeeded(const Value *V);
703   void ExportFromCurrentBlock(const Value *V);
704   void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
705                    MachineBasicBlock *LandingPad = nullptr);
706
707   std::pair<SDValue, SDValue> lowerCallOperands(
708           ImmutableCallSite CS,
709           unsigned ArgIdx,
710           unsigned NumArgs,
711           SDValue Callee,
712           bool UseVoidTy = false,
713           MachineBasicBlock *LandingPad = nullptr,
714           bool IsPatchPoint = false);
715
716   /// UpdateSplitBlock - When an MBB was split during scheduling, update the
717   /// references that need to refer to the last resulting block.
718   void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
719
720   // This function is responsible for the whole statepoint lowering process.
721   // It uniformly handles invoke and call statepoints.
722   void LowerStatepoint(ImmutableStatepoint Statepoint,
723                        MachineBasicBlock *LandingPad = nullptr);
724 private:
725   std::pair<SDValue, SDValue> lowerInvokable(
726           TargetLowering::CallLoweringInfo &CLI,
727           MachineBasicBlock *LandingPad);
728
729   // Terminator instructions.
730   void visitRet(const ReturnInst &I);
731   void visitBr(const BranchInst &I);
732   void visitSwitch(const SwitchInst &I);
733   void visitIndirectBr(const IndirectBrInst &I);
734   void visitUnreachable(const UnreachableInst &I);
735
736   uint32_t getEdgeWeight(const MachineBasicBlock *Src,
737                          const MachineBasicBlock *Dst) const;
738   void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
739                               uint32_t Weight = 0);
740 public:
741   void visitSwitchCase(CaseBlock &CB,
742                        MachineBasicBlock *SwitchBB);
743   void visitSPDescriptorParent(StackProtectorDescriptor &SPD,
744                                MachineBasicBlock *ParentBB);
745   void visitSPDescriptorFailure(StackProtectorDescriptor &SPD);
746   void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
747   void visitBitTestCase(BitTestBlock &BB,
748                         MachineBasicBlock* NextMBB,
749                         uint32_t BranchWeightToNext,
750                         unsigned Reg,
751                         BitTestCase &B,
752                         MachineBasicBlock *SwitchBB);
753   void visitJumpTable(JumpTable &JT);
754   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
755                             MachineBasicBlock *SwitchBB);
756   unsigned visitLandingPadClauseBB(GlobalValue *ClauseGV,
757                                    MachineBasicBlock *LPadMBB);
758
759 private:
760   // These all get lowered before this pass.
761   void visitInvoke(const InvokeInst &I);
762   void visitResume(const ResumeInst &I);
763
764   void visitBinary(const User &I, unsigned OpCode);
765   void visitShift(const User &I, unsigned Opcode);
766   void visitAdd(const User &I)  { visitBinary(I, ISD::ADD); }
767   void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
768   void visitSub(const User &I)  { visitBinary(I, ISD::SUB); }
769   void visitFSub(const User &I);
770   void visitMul(const User &I)  { visitBinary(I, ISD::MUL); }
771   void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
772   void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
773   void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
774   void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
775   void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
776   void visitSDiv(const User &I);
777   void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
778   void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
779   void visitOr  (const User &I) { visitBinary(I, ISD::OR); }
780   void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
781   void visitShl (const User &I) { visitShift(I, ISD::SHL); }
782   void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
783   void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
784   void visitICmp(const User &I);
785   void visitFCmp(const User &I);
786   // Visit the conversion instructions
787   void visitTrunc(const User &I);
788   void visitZExt(const User &I);
789   void visitSExt(const User &I);
790   void visitFPTrunc(const User &I);
791   void visitFPExt(const User &I);
792   void visitFPToUI(const User &I);
793   void visitFPToSI(const User &I);
794   void visitUIToFP(const User &I);
795   void visitSIToFP(const User &I);
796   void visitPtrToInt(const User &I);
797   void visitIntToPtr(const User &I);
798   void visitBitCast(const User &I);
799   void visitAddrSpaceCast(const User &I);
800
801   void visitExtractElement(const User &I);
802   void visitInsertElement(const User &I);
803   void visitShuffleVector(const User &I);
804
805   void visitExtractValue(const ExtractValueInst &I);
806   void visitInsertValue(const InsertValueInst &I);
807   void visitLandingPad(const LandingPadInst &I);
808
809   void visitGetElementPtr(const User &I);
810   void visitSelect(const User &I);
811
812   void visitAlloca(const AllocaInst &I);
813   void visitLoad(const LoadInst &I);
814   void visitStore(const StoreInst &I);
815   void visitMaskedLoad(const CallInst &I);
816   void visitMaskedStore(const CallInst &I);
817   void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
818   void visitAtomicRMW(const AtomicRMWInst &I);
819   void visitFence(const FenceInst &I);
820   void visitPHI(const PHINode &I);
821   void visitCall(const CallInst &I);
822   bool visitMemCmpCall(const CallInst &I);
823   bool visitMemChrCall(const CallInst &I);
824   bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
825   bool visitStrCmpCall(const CallInst &I);
826   bool visitStrLenCall(const CallInst &I);
827   bool visitStrNLenCall(const CallInst &I);
828   bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
829   bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode);
830   void visitAtomicLoad(const LoadInst &I);
831   void visitAtomicStore(const StoreInst &I);
832
833   void visitInlineAsm(ImmutableCallSite CS);
834   const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
835   void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
836
837   void visitVAStart(const CallInst &I);
838   void visitVAArg(const VAArgInst &I);
839   void visitVAEnd(const CallInst &I);
840   void visitVACopy(const CallInst &I);
841   void visitStackmap(const CallInst &I);
842   void visitPatchpoint(ImmutableCallSite CS,
843                        MachineBasicBlock *LandingPad = nullptr);
844
845   // These three are implemented in StatepointLowering.cpp
846   void visitStatepoint(const CallInst &I);
847   void visitGCRelocate(const CallInst &I);
848   void visitGCResult(const CallInst &I);
849
850   void visitUserOp1(const Instruction &I) {
851     llvm_unreachable("UserOp1 should not exist at instruction selection time!");
852   }
853   void visitUserOp2(const Instruction &I) {
854     llvm_unreachable("UserOp2 should not exist at instruction selection time!");
855   }
856
857   void processIntegerCallValue(const Instruction &I,
858                                SDValue Value, bool IsSigned);
859
860   void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
861
862   /// EmitFuncArgumentDbgValue - If V is an function argument then create
863   /// corresponding DBG_VALUE machine instruction for it now. At the end of
864   /// instruction selection, they will be inserted to the entry BB.
865   bool EmitFuncArgumentDbgValue(const Value *V, MDLocalVariable *Variable,
866                                 MDExpression *Expr, MDLocation *DL,
867                                 int64_t Offset, bool IsIndirect,
868                                 const SDValue &N);
869
870   /// Return the next block after MBB, or nullptr if there is none.
871   MachineBasicBlock *NextBlock(MachineBasicBlock *MBB);
872
873   /// Update the DAG and DAG builder with the relevant information after
874   /// a new root node has been created which could be a tail call.
875   void updateDAGForMaybeTailCall(SDValue MaybeTC);
876 };
877
878 } // end namespace llvm
879
880 #endif