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