Add convenience functions for creating nsw add operators.
[oota-llvm.git] / include / llvm / InstrTypes.h
1 //===-- llvm/InstrTypes.h - Important Instruction subclasses ----*- 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 file defines various meta classes of instructions that exist in the VM
11 // representation.  Specific concrete subclasses of these may be found in the
12 // i*.h files...
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_INSTRUCTION_TYPES_H
17 #define LLVM_INSTRUCTION_TYPES_H
18
19 #include "llvm/Instruction.h"
20 #include "llvm/OperandTraits.h"
21 #include "llvm/Operator.h"
22 #include "llvm/DerivedTypes.h"
23
24 namespace llvm {
25
26 class LLVMContext;
27
28 //===----------------------------------------------------------------------===//
29 //                            TerminatorInst Class
30 //===----------------------------------------------------------------------===//
31
32 /// TerminatorInst - Subclasses of this class are all able to terminate a basic
33 /// block.  Thus, these are all the flow control type of operations.
34 ///
35 class TerminatorInst : public Instruction {
36 protected:
37   TerminatorInst(const Type *Ty, Instruction::TermOps iType,
38                  Use *Ops, unsigned NumOps,
39                  Instruction *InsertBefore = 0)
40     : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
41
42   TerminatorInst(const Type *Ty, Instruction::TermOps iType,
43                  Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
44     : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
45
46   // Out of line virtual method, so the vtable, etc has a home.
47   ~TerminatorInst();
48
49   /// Virtual methods - Terminators should overload these and provide inline
50   /// overrides of non-V methods.
51   virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
52   virtual unsigned getNumSuccessorsV() const = 0;
53   virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
54 public:
55
56   virtual Instruction *clone(LLVMContext &Context) const = 0;
57
58   /// getNumSuccessors - Return the number of successors that this terminator
59   /// has.
60   unsigned getNumSuccessors() const {
61     return getNumSuccessorsV();
62   }
63
64   /// getSuccessor - Return the specified successor.
65   ///
66   BasicBlock *getSuccessor(unsigned idx) const {
67     return getSuccessorV(idx);
68   }
69
70   /// setSuccessor - Update the specified successor to point at the provided
71   /// block.
72   void setSuccessor(unsigned idx, BasicBlock *B) {
73     setSuccessorV(idx, B);
74   }
75
76   // Methods for support type inquiry through isa, cast, and dyn_cast:
77   static inline bool classof(const TerminatorInst *) { return true; }
78   static inline bool classof(const Instruction *I) {
79     return I->isTerminator();
80   }
81   static inline bool classof(const Value *V) {
82     return isa<Instruction>(V) && classof(cast<Instruction>(V));
83   }
84 };
85
86
87 //===----------------------------------------------------------------------===//
88 //                          UnaryInstruction Class
89 //===----------------------------------------------------------------------===//
90
91 class UnaryInstruction : public Instruction {
92   void *operator new(size_t, unsigned);      // Do not implement
93   UnaryInstruction(const UnaryInstruction&); // Do not implement
94
95 protected:
96   UnaryInstruction(const Type *Ty, unsigned iType, Value *V,
97                    Instruction *IB = 0)
98     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
99     Op<0>() = V;
100   }
101   UnaryInstruction(const Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
102     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
103     Op<0>() = V;
104   }
105 public:
106   // allocate space for exactly one operand
107   void *operator new(size_t s) {
108     return User::operator new(s, 1);
109   }
110
111   // Out of line virtual method, so the vtable, etc has a home.
112   ~UnaryInstruction();
113
114   /// Transparently provide more efficient getOperand methods.
115   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
116
117   // Methods for support type inquiry through isa, cast, and dyn_cast:
118   static inline bool classof(const UnaryInstruction *) { return true; }
119   static inline bool classof(const Instruction *I) {
120     return I->getOpcode() == Instruction::Malloc ||
121            I->getOpcode() == Instruction::Alloca ||
122            I->getOpcode() == Instruction::Free ||
123            I->getOpcode() == Instruction::Load ||
124            I->getOpcode() == Instruction::VAArg ||
125            I->getOpcode() == Instruction::ExtractValue ||
126            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
127   }
128   static inline bool classof(const Value *V) {
129     return isa<Instruction>(V) && classof(cast<Instruction>(V));
130   }
131 };
132
133 template <>
134 struct OperandTraits<UnaryInstruction> : FixedNumOperandTraits<1> {
135 };
136
137 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
138
139 //===----------------------------------------------------------------------===//
140 //                           BinaryOperator Class
141 //===----------------------------------------------------------------------===//
142
143 class BinaryOperator : public Instruction {
144   void *operator new(size_t, unsigned); // Do not implement
145 protected:
146   void init(BinaryOps iType);
147   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, const Type *Ty,
148                  const Twine &Name, Instruction *InsertBefore);
149   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, const Type *Ty,
150                  const Twine &Name, BasicBlock *InsertAtEnd);
151 public:
152   // allocate space for exactly two operands
153   void *operator new(size_t s) {
154     return User::operator new(s, 2);
155   }
156
157   /// Transparently provide more efficient getOperand methods.
158   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
159
160   /// Create() - Construct a binary instruction, given the opcode and the two
161   /// operands.  Optionally (if InstBefore is specified) insert the instruction
162   /// into a BasicBlock right before the specified instruction.  The specified
163   /// Instruction is allowed to be a dereferenced end iterator.
164   ///
165   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
166                                 const Twine &Name = "",
167                                 Instruction *InsertBefore = 0);
168
169   /// Create() - Construct a binary instruction, given the opcode and the two
170   /// operands.  Also automatically insert this instruction to the end of the
171   /// BasicBlock specified.
172   ///
173   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
174                                 const Twine &Name, BasicBlock *InsertAtEnd);
175
176   /// Create* - These methods just forward to Create, and are useful when you
177   /// statically know what type of instruction you're going to create.  These
178   /// helpers just save some typing.
179 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
180   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
181                                      const Twine &Name = "") {\
182     return Create(Instruction::OPC, V1, V2, Name);\
183   }
184 #include "llvm/Instruction.def"
185 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
186   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
187                                      const Twine &Name, BasicBlock *BB) {\
188     return Create(Instruction::OPC, V1, V2, Name, BB);\
189   }
190 #include "llvm/Instruction.def"
191 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
192   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
193                                      const Twine &Name, Instruction *I) {\
194     return Create(Instruction::OPC, V1, V2, Name, I);\
195   }
196 #include "llvm/Instruction.def"
197
198
199   /// CreateNSWAdd - Create an Add operator with the NSW flag set.
200   ///
201   static BinaryOperator *CreateNSWAdd(Value *V1, Value *V2,
202                                       const Twine &Name = "") {
203     BinaryOperator *BO = CreateAdd(V1, V2, Name);
204     cast<AddOperator>(BO)->setHasNoSignedOverflow(true);
205     return BO;
206   }
207   static BinaryOperator *CreateNSWAdd(Value *V1, Value *V2,
208                                       const Twine &Name, BasicBlock *BB) {
209     BinaryOperator *BO = CreateAdd(V1, V2, Name, BB);
210     cast<AddOperator>(BO)->setHasNoSignedOverflow(true);
211     return BO;
212   }
213   static BinaryOperator *CreateNSWAdd(Value *V1, Value *V2,
214                                       const Twine &Name, Instruction *I) {
215     BinaryOperator *BO = CreateAdd(V1, V2, Name, I);
216     cast<AddOperator>(BO)->setHasNoSignedOverflow(true);
217     return BO;
218   }
219
220   /// CreateExactSDiv - Create an SDiv operator with the exact flag set.
221   ///
222   static BinaryOperator *CreateExactSDiv(Value *V1, Value *V2,
223                                          const Twine &Name = "") {
224     BinaryOperator *BO = CreateSDiv(V1, V2, Name);
225     cast<SDivOperator>(BO)->setIsExact(true);
226     return BO;
227   }
228   static BinaryOperator *CreateExactSDiv(Value *V1, Value *V2,
229                                          const Twine &Name, BasicBlock *BB) {
230     BinaryOperator *BO = CreateSDiv(V1, V2, Name, BB);
231     cast<SDivOperator>(BO)->setIsExact(true);
232     return BO;
233   }
234   static BinaryOperator *CreateExactSDiv(Value *V1, Value *V2,
235                                          const Twine &Name, Instruction *I) {
236     BinaryOperator *BO = CreateSDiv(V1, V2, Name, I);
237     cast<SDivOperator>(BO)->setIsExact(true);
238     return BO;
239   }
240
241   /// Helper functions to construct and inspect unary operations (NEG and NOT)
242   /// via binary operators SUB and XOR:
243   ///
244   /// CreateNeg, CreateNot - Create the NEG and NOT
245   ///     instructions out of SUB and XOR instructions.
246   ///
247   static BinaryOperator *CreateNeg(LLVMContext &Context,
248                                    Value *Op, const Twine &Name = "",
249                                    Instruction *InsertBefore = 0);
250   static BinaryOperator *CreateNeg(LLVMContext &Context,
251                                    Value *Op, const Twine &Name,
252                                    BasicBlock *InsertAtEnd);
253   static BinaryOperator *CreateFNeg(LLVMContext &Context, 
254                                     Value *Op, const Twine &Name = "",
255                                     Instruction *InsertBefore = 0);
256   static BinaryOperator *CreateFNeg(LLVMContext &Context,
257                                     Value *Op, const Twine &Name,
258                                     BasicBlock *InsertAtEnd);
259   static BinaryOperator *CreateNot(LLVMContext &Context,
260                                    Value *Op, const Twine &Name = "",
261                                    Instruction *InsertBefore = 0);
262   static BinaryOperator *CreateNot(LLVMContext &Context,
263                                    Value *Op, const Twine &Name,
264                                    BasicBlock *InsertAtEnd);
265
266   /// isNeg, isFNeg, isNot - Check if the given Value is a
267   /// NEG, FNeg, or NOT instruction.
268   ///
269   static bool isNeg(const Value *V);
270   static bool isFNeg(const Value *V);
271   static bool isNot(const Value *V);
272
273   /// getNegArgument, getNotArgument - Helper functions to extract the
274   ///     unary argument of a NEG, FNEG or NOT operation implemented via
275   ///     Sub, FSub, or Xor.
276   ///
277   static const Value *getNegArgument(const Value *BinOp);
278   static       Value *getNegArgument(      Value *BinOp);
279   static const Value *getFNegArgument(const Value *BinOp);
280   static       Value *getFNegArgument(      Value *BinOp);
281   static const Value *getNotArgument(const Value *BinOp);
282   static       Value *getNotArgument(      Value *BinOp);
283
284   BinaryOps getOpcode() const {
285     return static_cast<BinaryOps>(Instruction::getOpcode());
286   }
287
288   virtual BinaryOperator *clone(LLVMContext &Context) const;
289
290   /// swapOperands - Exchange the two operands to this instruction.
291   /// This instruction is safe to use on any binary instruction and
292   /// does not modify the semantics of the instruction.  If the instruction
293   /// cannot be reversed (ie, it's a Div), then return true.
294   ///
295   bool swapOperands();
296
297   // Methods for support type inquiry through isa, cast, and dyn_cast:
298   static inline bool classof(const BinaryOperator *) { return true; }
299   static inline bool classof(const Instruction *I) {
300     return I->isBinaryOp();
301   }
302   static inline bool classof(const Value *V) {
303     return isa<Instruction>(V) && classof(cast<Instruction>(V));
304   }
305 };
306
307 template <>
308 struct OperandTraits<BinaryOperator> : FixedNumOperandTraits<2> {
309 };
310
311 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
312
313 //===----------------------------------------------------------------------===//
314 //                               CastInst Class
315 //===----------------------------------------------------------------------===//
316
317 /// CastInst - This is the base class for all instructions that perform data
318 /// casts. It is simply provided so that instruction category testing
319 /// can be performed with code like:
320 ///
321 /// if (isa<CastInst>(Instr)) { ... }
322 /// @brief Base class of casting instructions.
323 class CastInst : public UnaryInstruction {
324   /// @brief Copy constructor
325   CastInst(const CastInst &CI)
326     : UnaryInstruction(CI.getType(), CI.getOpcode(), CI.getOperand(0)) {
327   }
328   /// @brief Do not allow default construction
329   CastInst();
330 protected:
331   /// @brief Constructor with insert-before-instruction semantics for subclasses
332   CastInst(const Type *Ty, unsigned iType, Value *S,
333            const Twine &NameStr = "", Instruction *InsertBefore = 0)
334     : UnaryInstruction(Ty, iType, S, InsertBefore) {
335     setName(NameStr);
336   }
337   /// @brief Constructor with insert-at-end-of-block semantics for subclasses
338   CastInst(const Type *Ty, unsigned iType, Value *S,
339            const Twine &NameStr, BasicBlock *InsertAtEnd)
340     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
341     setName(NameStr);
342   }
343 public:
344   /// Provides a way to construct any of the CastInst subclasses using an
345   /// opcode instead of the subclass's constructor. The opcode must be in the
346   /// CastOps category (Instruction::isCast(opcode) returns true). This
347   /// constructor has insert-before-instruction semantics to automatically
348   /// insert the new CastInst before InsertBefore (if it is non-null).
349   /// @brief Construct any of the CastInst subclasses
350   static CastInst *Create(
351     Instruction::CastOps,    ///< The opcode of the cast instruction
352     Value *S,                ///< The value to be casted (operand 0)
353     const Type *Ty,          ///< The type to which cast should be made
354     const Twine &Name = "", ///< Name for the instruction
355     Instruction *InsertBefore = 0 ///< Place to insert the instruction
356   );
357   /// Provides a way to construct any of the CastInst subclasses using an
358   /// opcode instead of the subclass's constructor. The opcode must be in the
359   /// CastOps category. This constructor has insert-at-end-of-block semantics
360   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
361   /// its non-null).
362   /// @brief Construct any of the CastInst subclasses
363   static CastInst *Create(
364     Instruction::CastOps,    ///< The opcode for the cast instruction
365     Value *S,                ///< The value to be casted (operand 0)
366     const Type *Ty,          ///< The type to which operand is casted
367     const Twine &Name, ///< The name for the instruction
368     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
369   );
370
371   /// @brief Create a ZExt or BitCast cast instruction
372   static CastInst *CreateZExtOrBitCast(
373     Value *S,                ///< The value to be casted (operand 0)
374     const Type *Ty,          ///< The type to which cast should be made
375     const Twine &Name = "", ///< Name for the instruction
376     Instruction *InsertBefore = 0 ///< Place to insert the instruction
377   );
378
379   /// @brief Create a ZExt or BitCast cast instruction
380   static CastInst *CreateZExtOrBitCast(
381     Value *S,                ///< The value to be casted (operand 0)
382     const Type *Ty,          ///< The type to which operand is casted
383     const Twine &Name, ///< The name for the instruction
384     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
385   );
386
387   /// @brief Create a SExt or BitCast cast instruction
388   static CastInst *CreateSExtOrBitCast(
389     Value *S,                ///< The value to be casted (operand 0)
390     const Type *Ty,          ///< The type to which cast should be made
391     const Twine &Name = "", ///< Name for the instruction
392     Instruction *InsertBefore = 0 ///< Place to insert the instruction
393   );
394
395   /// @brief Create a SExt or BitCast cast instruction
396   static CastInst *CreateSExtOrBitCast(
397     Value *S,                ///< The value to be casted (operand 0)
398     const Type *Ty,          ///< The type to which operand is casted
399     const Twine &Name, ///< The name for the instruction
400     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
401   );
402
403   /// @brief Create a BitCast or a PtrToInt cast instruction
404   static CastInst *CreatePointerCast(
405     Value *S,                ///< The pointer value to be casted (operand 0)
406     const Type *Ty,          ///< The type to which operand is casted
407     const Twine &Name, ///< The name for the instruction
408     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
409   );
410
411   /// @brief Create a BitCast or a PtrToInt cast instruction
412   static CastInst *CreatePointerCast(
413     Value *S,                ///< The pointer value to be casted (operand 0)
414     const Type *Ty,          ///< The type to which cast should be made
415     const Twine &Name = "", ///< Name for the instruction
416     Instruction *InsertBefore = 0 ///< Place to insert the instruction
417   );
418
419   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
420   static CastInst *CreateIntegerCast(
421     Value *S,                ///< The pointer value to be casted (operand 0)
422     const Type *Ty,          ///< The type to which cast should be made
423     bool isSigned,           ///< Whether to regard S as signed or not
424     const Twine &Name = "", ///< Name for the instruction
425     Instruction *InsertBefore = 0 ///< Place to insert the instruction
426   );
427
428   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
429   static CastInst *CreateIntegerCast(
430     Value *S,                ///< The integer value to be casted (operand 0)
431     const Type *Ty,          ///< The integer type to which operand is casted
432     bool isSigned,           ///< Whether to regard S as signed or not
433     const Twine &Name, ///< The name for the instruction
434     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
435   );
436
437   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
438   static CastInst *CreateFPCast(
439     Value *S,                ///< The floating point value to be casted
440     const Type *Ty,          ///< The floating point type to cast to
441     const Twine &Name = "", ///< Name for the instruction
442     Instruction *InsertBefore = 0 ///< Place to insert the instruction
443   );
444
445   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
446   static CastInst *CreateFPCast(
447     Value *S,                ///< The floating point value to be casted
448     const Type *Ty,          ///< The floating point type to cast to
449     const Twine &Name, ///< The name for the instruction
450     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
451   );
452
453   /// @brief Create a Trunc or BitCast cast instruction
454   static CastInst *CreateTruncOrBitCast(
455     Value *S,                ///< The value to be casted (operand 0)
456     const Type *Ty,          ///< The type to which cast should be made
457     const Twine &Name = "", ///< Name for the instruction
458     Instruction *InsertBefore = 0 ///< Place to insert the instruction
459   );
460
461   /// @brief Create a Trunc or BitCast cast instruction
462   static CastInst *CreateTruncOrBitCast(
463     Value *S,                ///< The value to be casted (operand 0)
464     const Type *Ty,          ///< The type to which operand is casted
465     const Twine &Name, ///< The name for the instruction
466     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
467   );
468
469   /// @brief Check whether it is valid to call getCastOpcode for these types.
470   static bool isCastable(
471     const Type *SrcTy, ///< The Type from which the value should be cast.
472     const Type *DestTy ///< The Type to which the value should be cast.
473   );
474
475   /// Returns the opcode necessary to cast Val into Ty using usual casting
476   /// rules.
477   /// @brief Infer the opcode for cast operand and type
478   static Instruction::CastOps getCastOpcode(
479     const Value *Val, ///< The value to cast
480     bool SrcIsSigned, ///< Whether to treat the source as signed
481     const Type *Ty,   ///< The Type to which the value should be casted
482     bool DstIsSigned  ///< Whether to treate the dest. as signed
483   );
484
485   /// There are several places where we need to know if a cast instruction
486   /// only deals with integer source and destination types. To simplify that
487   /// logic, this method is provided.
488   /// @returns true iff the cast has only integral typed operand and dest type.
489   /// @brief Determine if this is an integer-only cast.
490   bool isIntegerCast() const;
491
492   /// A lossless cast is one that does not alter the basic value. It implies
493   /// a no-op cast but is more stringent, preventing things like int->float,
494   /// long->double, int->ptr, or vector->anything.
495   /// @returns true iff the cast is lossless.
496   /// @brief Determine if this is a lossless cast.
497   bool isLosslessCast() const;
498
499   /// A no-op cast is one that can be effected without changing any bits.
500   /// It implies that the source and destination types are the same size. The
501   /// IntPtrTy argument is used to make accurate determinations for casts
502   /// involving Integer and Pointer types. They are no-op casts if the integer
503   /// is the same size as the pointer. However, pointer size varies with
504   /// platform. Generally, the result of TargetData::getIntPtrType() should be
505   /// passed in. If that's not available, use Type::Int64Ty, which will make
506   /// the isNoopCast call conservative.
507   /// @brief Determine if this cast is a no-op cast.
508   bool isNoopCast(
509     const Type *IntPtrTy ///< Integer type corresponding to pointer
510   ) const;
511
512   /// Determine how a pair of casts can be eliminated, if they can be at all.
513   /// This is a helper function for both CastInst and ConstantExpr.
514   /// @returns 0 if the CastInst pair can't be eliminated
515   /// @returns Instruction::CastOps value for a cast that can replace
516   /// the pair, casting SrcTy to DstTy.
517   /// @brief Determine if a cast pair is eliminable
518   static unsigned isEliminableCastPair(
519     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
520     Instruction::CastOps secondOpcode, ///< Opcode of second cast
521     const Type *SrcTy, ///< SrcTy of 1st cast
522     const Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
523     const Type *DstTy, ///< DstTy of 2nd cast
524     const Type *IntPtrTy ///< Integer type corresponding to Ptr types, or null
525   );
526
527   /// @brief Return the opcode of this CastInst
528   Instruction::CastOps getOpcode() const {
529     return Instruction::CastOps(Instruction::getOpcode());
530   }
531
532   /// @brief Return the source type, as a convenience
533   const Type* getSrcTy() const { return getOperand(0)->getType(); }
534   /// @brief Return the destination type, as a convenience
535   const Type* getDestTy() const { return getType(); }
536
537   /// This method can be used to determine if a cast from S to DstTy using
538   /// Opcode op is valid or not.
539   /// @returns true iff the proposed cast is valid.
540   /// @brief Determine if a cast is valid without creating one.
541   static bool castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy);
542
543   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
544   static inline bool classof(const CastInst *) { return true; }
545   static inline bool classof(const Instruction *I) {
546     return I->isCast();
547   }
548   static inline bool classof(const Value *V) {
549     return isa<Instruction>(V) && classof(cast<Instruction>(V));
550   }
551 };
552
553 //===----------------------------------------------------------------------===//
554 //                               CmpInst Class
555 //===----------------------------------------------------------------------===//
556
557 /// This class is the base class for the comparison instructions.
558 /// @brief Abstract base class of comparison instructions.
559 // FIXME: why not derive from BinaryOperator?
560 class CmpInst: public Instruction {
561   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
562   CmpInst(); // do not implement
563 protected:
564   CmpInst(const Type *ty, Instruction::OtherOps op, unsigned short pred,
565           Value *LHS, Value *RHS, const Twine &Name = "",
566           Instruction *InsertBefore = 0);
567
568   CmpInst(const Type *ty, Instruction::OtherOps op, unsigned short pred,
569           Value *LHS, Value *RHS, const Twine &Name,
570           BasicBlock *InsertAtEnd);
571
572 public:
573   /// This enumeration lists the possible predicates for CmpInst subclasses.
574   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
575   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
576   /// predicate values are not overlapping between the classes.
577   enum Predicate {
578     // Opcode             U L G E    Intuitive operation
579     FCMP_FALSE =  0,  /// 0 0 0 0    Always false (always folded)
580     FCMP_OEQ   =  1,  /// 0 0 0 1    True if ordered and equal
581     FCMP_OGT   =  2,  /// 0 0 1 0    True if ordered and greater than
582     FCMP_OGE   =  3,  /// 0 0 1 1    True if ordered and greater than or equal
583     FCMP_OLT   =  4,  /// 0 1 0 0    True if ordered and less than
584     FCMP_OLE   =  5,  /// 0 1 0 1    True if ordered and less than or equal
585     FCMP_ONE   =  6,  /// 0 1 1 0    True if ordered and operands are unequal
586     FCMP_ORD   =  7,  /// 0 1 1 1    True if ordered (no nans)
587     FCMP_UNO   =  8,  /// 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
588     FCMP_UEQ   =  9,  /// 1 0 0 1    True if unordered or equal
589     FCMP_UGT   = 10,  /// 1 0 1 0    True if unordered or greater than
590     FCMP_UGE   = 11,  /// 1 0 1 1    True if unordered, greater than, or equal
591     FCMP_ULT   = 12,  /// 1 1 0 0    True if unordered or less than
592     FCMP_ULE   = 13,  /// 1 1 0 1    True if unordered, less than, or equal
593     FCMP_UNE   = 14,  /// 1 1 1 0    True if unordered or not equal
594     FCMP_TRUE  = 15,  /// 1 1 1 1    Always true (always folded)
595     FIRST_FCMP_PREDICATE = FCMP_FALSE,
596     LAST_FCMP_PREDICATE = FCMP_TRUE,
597     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
598     ICMP_EQ    = 32,  /// equal
599     ICMP_NE    = 33,  /// not equal
600     ICMP_UGT   = 34,  /// unsigned greater than
601     ICMP_UGE   = 35,  /// unsigned greater or equal
602     ICMP_ULT   = 36,  /// unsigned less than
603     ICMP_ULE   = 37,  /// unsigned less or equal
604     ICMP_SGT   = 38,  /// signed greater than
605     ICMP_SGE   = 39,  /// signed greater or equal
606     ICMP_SLT   = 40,  /// signed less than
607     ICMP_SLE   = 41,  /// signed less or equal
608     FIRST_ICMP_PREDICATE = ICMP_EQ,
609     LAST_ICMP_PREDICATE = ICMP_SLE,
610     BAD_ICMP_PREDICATE = ICMP_SLE + 1
611   };
612
613   // allocate space for exactly two operands
614   void *operator new(size_t s) {
615     return User::operator new(s, 2);
616   }
617   /// Construct a compare instruction, given the opcode, the predicate and
618   /// the two operands.  Optionally (if InstBefore is specified) insert the
619   /// instruction into a BasicBlock right before the specified instruction.
620   /// The specified Instruction is allowed to be a dereferenced end iterator.
621   /// @brief Create a CmpInst
622   static CmpInst *Create(LLVMContext &Context, OtherOps Op,
623                          unsigned short predicate, Value *S1,
624                          Value *S2, const Twine &Name = "",
625                          Instruction *InsertBefore = 0);
626
627   /// Construct a compare instruction, given the opcode, the predicate and the
628   /// two operands.  Also automatically insert this instruction to the end of
629   /// the BasicBlock specified.
630   /// @brief Create a CmpInst
631   static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
632                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
633
634   /// @brief Get the opcode casted to the right type
635   OtherOps getOpcode() const {
636     return static_cast<OtherOps>(Instruction::getOpcode());
637   }
638
639   /// @brief Return the predicate for this instruction.
640   Predicate getPredicate() const { return Predicate(SubclassData); }
641
642   /// @brief Set the predicate for this instruction to the specified value.
643   void setPredicate(Predicate P) { SubclassData = P; }
644
645   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
646   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
647   /// @returns the inverse predicate for the instruction's current predicate.
648   /// @brief Return the inverse of the instruction's predicate.
649   Predicate getInversePredicate() const {
650     return getInversePredicate(getPredicate());
651   }
652
653   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
654   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
655   /// @returns the inverse predicate for predicate provided in \p pred.
656   /// @brief Return the inverse of a given predicate
657   static Predicate getInversePredicate(Predicate pred);
658
659   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
660   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
661   /// @returns the predicate that would be the result of exchanging the two
662   /// operands of the CmpInst instruction without changing the result
663   /// produced.
664   /// @brief Return the predicate as if the operands were swapped
665   Predicate getSwappedPredicate() const {
666     return getSwappedPredicate(getPredicate());
667   }
668
669   /// This is a static version that you can use without an instruction
670   /// available.
671   /// @brief Return the predicate as if the operands were swapped.
672   static Predicate getSwappedPredicate(Predicate pred);
673
674   /// @brief Provide more efficient getOperand methods.
675   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
676
677   /// This is just a convenience that dispatches to the subclasses.
678   /// @brief Swap the operands and adjust predicate accordingly to retain
679   /// the same comparison.
680   void swapOperands();
681
682   /// This is just a convenience that dispatches to the subclasses.
683   /// @brief Determine if this CmpInst is commutative.
684   bool isCommutative();
685
686   /// This is just a convenience that dispatches to the subclasses.
687   /// @brief Determine if this is an equals/not equals predicate.
688   bool isEquality();
689
690   /// @returns true if the predicate is unsigned, false otherwise.
691   /// @brief Determine if the predicate is an unsigned operation.
692   static bool isUnsigned(unsigned short predicate);
693
694   /// @returns true if the predicate is signed, false otherwise.
695   /// @brief Determine if the predicate is an signed operation.
696   static bool isSigned(unsigned short predicate);
697
698   /// @brief Determine if the predicate is an ordered operation.
699   static bool isOrdered(unsigned short predicate);
700
701   /// @brief Determine if the predicate is an unordered operation.
702   static bool isUnordered(unsigned short predicate);
703
704   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
705   static inline bool classof(const CmpInst *) { return true; }
706   static inline bool classof(const Instruction *I) {
707     return I->getOpcode() == Instruction::ICmp ||
708            I->getOpcode() == Instruction::FCmp;
709   }
710   static inline bool classof(const Value *V) {
711     return isa<Instruction>(V) && classof(cast<Instruction>(V));
712   }
713   
714   /// @brief Create a result type for fcmp/icmp
715   static const Type* makeCmpResultType(const Type* opnd_type) {
716     if (const VectorType* vt = dyn_cast<const VectorType>(opnd_type)) {
717       return VectorType::get(Type::Int1Ty, vt->getNumElements());
718     }
719     return Type::Int1Ty;
720   }
721 };
722
723
724 // FIXME: these are redundant if CmpInst < BinaryOperator
725 template <>
726 struct OperandTraits<CmpInst> : FixedNumOperandTraits<2> {
727 };
728
729 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
730
731 } // End llvm namespace
732
733 #endif