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