LLVM API Documentation

TargetLowering.h

Go to the documentation of this file.
00001 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file describes how to lower LLVM code to machine code.  This has two
00011 // main components:
00012 //
00013 //  1. Which ValueTypes are natively supported by the target.
00014 //  2. Which operations are supported for supported ValueTypes.
00015 //  3. Cost thresholds for alternative implementations of certain operations.
00016 //
00017 // In addition it has a few other components, like information about FP
00018 // immediates.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #ifndef LLVM_TARGET_TARGETLOWERING_H
00023 #define LLVM_TARGET_TARGETLOWERING_H
00024 
00025 #include "llvm/Type.h"
00026 #include "llvm/CodeGen/SelectionDAGNodes.h"
00027 #include <map>
00028 
00029 namespace llvm {
00030   class Value;
00031   class Function;
00032   class TargetMachine;
00033   class TargetData;
00034   class TargetRegisterClass;
00035   class SDNode;
00036   class SDOperand;
00037   class SelectionDAG;
00038   class MachineBasicBlock;
00039   class MachineInstr;
00040 
00041 //===----------------------------------------------------------------------===//
00042 /// TargetLowering - This class defines information used to lower LLVM code to
00043 /// legal SelectionDAG operators that the target instruction selector can accept
00044 /// natively.
00045 ///
00046 /// This class also defines callbacks that targets must implement to lower
00047 /// target-specific constructs to SelectionDAG operators.
00048 ///
00049 class TargetLowering {
00050 public:
00051   /// LegalizeAction - This enum indicates whether operations are valid for a
00052   /// target, and if not, what action should be used to make them valid.
00053   enum LegalizeAction {
00054     Legal,      // The target natively supports this operation.
00055     Promote,    // This operation should be executed in a larger type.
00056     Expand,     // Try to expand this to other ops, otherwise use a libcall.
00057     Custom      // Use the LowerOperation hook to implement custom lowering.
00058   };
00059 
00060   enum OutOfRangeShiftAmount {
00061     Undefined,  // Oversized shift amounts are undefined (default).
00062     Mask,       // Shift amounts are auto masked (anded) to value size.
00063     Extend      // Oversized shift pulls in zeros or sign bits.
00064   };
00065 
00066   enum SetCCResultValue {
00067     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
00068     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
00069     ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
00070   };
00071 
00072   enum SchedPreference {
00073     SchedulingForLatency,          // Scheduling for shortest total latency.
00074     SchedulingForRegPressure       // Scheduling for lowest register pressure.
00075   };
00076 
00077   TargetLowering(TargetMachine &TM);
00078   virtual ~TargetLowering();
00079 
00080   TargetMachine &getTargetMachine() const { return TM; }
00081   const TargetData *getTargetData() const { return TD; }
00082 
00083   bool isLittleEndian() const { return IsLittleEndian; }
00084   MVT::ValueType getPointerTy() const { return PointerTy; }
00085   MVT::ValueType getShiftAmountTy() const { return ShiftAmountTy; }
00086   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
00087 
00088   /// isSetCCExpensive - Return true if the setcc operation is expensive for
00089   /// this target.
00090   bool isSetCCExpensive() const { return SetCCIsExpensive; }
00091   
00092   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
00093   /// a sequence of several shifts, adds, and multiplies for this target.
00094   bool isIntDivCheap() const { return IntDivIsCheap; }
00095 
00096   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
00097   /// srl/add/sra.
00098   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
00099   
00100   /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
00101   ///
00102   MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
00103 
00104   /// getSetCCResultContents - For targets without boolean registers, this flag
00105   /// returns information about the contents of the high-bits in the setcc
00106   /// result register.
00107   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
00108 
00109   /// getSchedulingPreference - Return target scheduling preference.
00110   SchedPreference getSchedulingPreference() const {
00111     return SchedPreferenceInfo;
00112   }
00113 
00114   /// getRegClassFor - Return the register class that should be used for the
00115   /// specified value type.  This may only be called on legal types.
00116   TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
00117     TargetRegisterClass *RC = RegClassForVT[VT];
00118     assert(RC && "This value type is not natively supported!");
00119     return RC;
00120   }
00121   
00122   /// isTypeLegal - Return true if the target has native support for the
00123   /// specified value type.  This means that it has a register that directly
00124   /// holds it without promotions or expansions.
00125   bool isTypeLegal(MVT::ValueType VT) const {
00126     return RegClassForVT[VT] != 0;
00127   }
00128 
00129   class ValueTypeActionImpl {
00130     /// ValueTypeActions - This is a bitvector that contains two bits for each
00131     /// value type, where the two bits correspond to the LegalizeAction enum.
00132     /// This can be queried with "getTypeAction(VT)".
00133     uint32_t ValueTypeActions[2];
00134   public:
00135     ValueTypeActionImpl() {
00136       ValueTypeActions[0] = ValueTypeActions[1] = 0;
00137     }
00138     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
00139       ValueTypeActions[0] = RHS.ValueTypeActions[0];
00140       ValueTypeActions[1] = RHS.ValueTypeActions[1];
00141     }
00142     
00143     LegalizeAction getTypeAction(MVT::ValueType VT) const {
00144       return (LegalizeAction)((ValueTypeActions[VT>>4] >> ((2*VT) & 31)) & 3);
00145     }
00146     void setTypeAction(MVT::ValueType VT, LegalizeAction Action) {
00147       assert(unsigned(VT >> 4) < 
00148              sizeof(ValueTypeActions)/sizeof(ValueTypeActions[0]));
00149       ValueTypeActions[VT>>4] |= Action << ((VT*2) & 31);
00150     }
00151   };
00152   
00153   const ValueTypeActionImpl &getValueTypeActions() const {
00154     return ValueTypeActions;
00155   }
00156   
00157   /// getTypeAction - Return how we should legalize values of this type, either
00158   /// it is already legal (return 'Legal') or we need to promote it to a larger
00159   /// type (return 'Promote'), or we need to expand it into multiple registers
00160   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
00161   LegalizeAction getTypeAction(MVT::ValueType VT) const {
00162     return ValueTypeActions.getTypeAction(VT);
00163   }
00164 
00165   /// getTypeToTransformTo - For types supported by the target, this is an
00166   /// identity function.  For types that must be promoted to larger types, this
00167   /// returns the larger type to promote to.  For types that are larger than the
00168   /// largest integer register, this contains one step in the expansion to get
00169   /// to the smaller register.
00170   MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
00171     return TransformToType[VT];
00172   }
00173   
00174   /// getPackedTypeBreakdown - Packed types are broken down into some number of
00175   /// legal first class types.  For example, <8 x float> maps to 2 MVT::v4f32
00176   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
00177   /// Similarly, <2 x long> turns into 4 MVT::i32 values with both PPC and X86.
00178   ///
00179   /// This method returns the number of registers needed, and the VT for each
00180   /// register.  It also returns the VT of the PackedType elements before they
00181   /// are promoted/expanded.
00182   ///
00183   unsigned getPackedTypeBreakdown(const PackedType *PTy, 
00184                                   MVT::ValueType &PTyElementVT,
00185                                   MVT::ValueType &PTyLegalElementVT) const;
00186   
00187   typedef std::vector<double>::const_iterator legal_fpimm_iterator;
00188   legal_fpimm_iterator legal_fpimm_begin() const {
00189     return LegalFPImmediates.begin();
00190   }
00191   legal_fpimm_iterator legal_fpimm_end() const {
00192     return LegalFPImmediates.end();
00193   }
00194   
00195   /// isShuffleMaskLegal - Targets can use this to indicate that they only
00196   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
00197   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
00198   /// are assumed to be legal.
00199   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
00200     return true;
00201   }
00202 
00203   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
00204   /// used by Targets can use this to indicate if there is a suitable
00205   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
00206   /// pool entry.
00207   virtual bool isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
00208                                       MVT::ValueType EVT,
00209                                       SelectionDAG &DAG) const {
00210     return false;
00211   }
00212 
00213   /// getOperationAction - Return how this operation should be treated: either
00214   /// it is legal, needs to be promoted to a larger size, needs to be
00215   /// expanded to some other code sequence, or the target has a custom expander
00216   /// for it.
00217   LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
00218     return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
00219   }
00220   
00221   /// isOperationLegal - Return true if the specified operation is legal on this
00222   /// target.
00223   bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
00224     return getOperationAction(Op, VT) == Legal ||
00225            getOperationAction(Op, VT) == Custom;
00226   }
00227   
00228   /// getTypeToPromoteTo - If the action for this operation is to promote, this
00229   /// method returns the ValueType to promote to.
00230   MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
00231     assert(getOperationAction(Op, VT) == Promote &&
00232            "This operation isn't promoted!");
00233 
00234     // See if this has an explicit type specified.
00235     std::map<std::pair<unsigned, MVT::ValueType>, 
00236              MVT::ValueType>::const_iterator PTTI =
00237       PromoteToType.find(std::make_pair(Op, VT));
00238     if (PTTI != PromoteToType.end()) return PTTI->second;
00239     
00240     assert((MVT::isInteger(VT) || MVT::isFloatingPoint(VT)) &&
00241            "Cannot autopromote this type, add it with AddPromotedToType.");
00242     
00243     MVT::ValueType NVT = VT;
00244     do {
00245       NVT = (MVT::ValueType)(NVT+1);
00246       assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
00247              "Didn't find type to promote to!");
00248     } while (!isTypeLegal(NVT) ||
00249               getOperationAction(Op, NVT) == Promote);
00250     return NVT;
00251   }
00252 
00253   /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
00254   /// This is fixed by the LLVM operations except for the pointer size.
00255   MVT::ValueType getValueType(const Type *Ty) const {
00256     switch (Ty->getTypeID()) {
00257     default: assert(0 && "Unknown type!");
00258     case Type::VoidTyID:    return MVT::isVoid;
00259     case Type::BoolTyID:    return MVT::i1;
00260     case Type::UByteTyID:
00261     case Type::SByteTyID:   return MVT::i8;
00262     case Type::ShortTyID:
00263     case Type::UShortTyID:  return MVT::i16;
00264     case Type::IntTyID:
00265     case Type::UIntTyID:    return MVT::i32;
00266     case Type::LongTyID:
00267     case Type::ULongTyID:   return MVT::i64;
00268     case Type::FloatTyID:   return MVT::f32;
00269     case Type::DoubleTyID:  return MVT::f64;
00270     case Type::PointerTyID: return PointerTy;
00271     case Type::PackedTyID:  return MVT::Vector;
00272     }
00273   }
00274 
00275   /// getNumElements - Return the number of registers that this ValueType will
00276   /// eventually require.  This is always one for all non-integer types, is
00277   /// one for any types promoted to live in larger registers, but may be more
00278   /// than one for types (like i64) that are split into pieces.
00279   unsigned getNumElements(MVT::ValueType VT) const {
00280     return NumElementsForVT[VT];
00281   }
00282   
00283   /// hasTargetDAGCombine - If true, the target has custom DAG combine
00284   /// transformations that it can perform for the specified node.
00285   bool hasTargetDAGCombine(ISD::NodeType NT) const {
00286     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
00287   }
00288 
00289   /// This function returns the maximum number of store operations permitted
00290   /// to replace a call to llvm.memset. The value is set by the target at the
00291   /// performance threshold for such a replacement.
00292   /// @brief Get maximum # of store operations permitted for llvm.memset
00293   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
00294 
00295   /// This function returns the maximum number of store operations permitted
00296   /// to replace a call to llvm.memcpy. The value is set by the target at the
00297   /// performance threshold for such a replacement.
00298   /// @brief Get maximum # of store operations permitted for llvm.memcpy
00299   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
00300 
00301   /// This function returns the maximum number of store operations permitted
00302   /// to replace a call to llvm.memmove. The value is set by the target at the
00303   /// performance threshold for such a replacement.
00304   /// @brief Get maximum # of store operations permitted for llvm.memmove
00305   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
00306 
00307   /// This function returns true if the target allows unaligned memory accesses.
00308   /// This is used, for example, in situations where an array copy/move/set is 
00309   /// converted to a sequence of store operations. It's use helps to ensure that
00310   /// such replacements don't generate code that causes an alignment error 
00311   /// (trap) on the target machine. 
00312   /// @brief Determine if the target supports unaligned memory accesses.
00313   bool allowsUnalignedMemoryAccesses() const {
00314     return allowUnalignedMemoryAccesses;
00315   }
00316   
00317   /// usesUnderscoreSetJmpLongJmp - Determine if we should use _setjmp or setjmp
00318   /// to implement llvm.setjmp.
00319   bool usesUnderscoreSetJmpLongJmp() const {
00320     return UseUnderscoreSetJmpLongJmp;
00321   }
00322   
00323   /// getStackPointerRegisterToSaveRestore - If a physical register, this
00324   /// specifies the register that llvm.savestack/llvm.restorestack should save
00325   /// and restore.
00326   unsigned getStackPointerRegisterToSaveRestore() const {
00327     return StackPointerRegisterToSaveRestore;
00328   }
00329 
00330   //===--------------------------------------------------------------------===//
00331   // TargetLowering Optimization Methods
00332   //
00333   
00334   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
00335   /// SDOperands for returning information from TargetLowering to its clients
00336   /// that want to combine 
00337   struct TargetLoweringOpt {
00338     SelectionDAG &DAG;
00339     SDOperand Old;
00340     SDOperand New;
00341 
00342     TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
00343     
00344     bool CombineTo(SDOperand O, SDOperand N) { 
00345       Old = O; 
00346       New = N; 
00347       return true;
00348     }
00349     
00350     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
00351     /// specified instruction is a constant integer.  If so, check to see if there
00352     /// are any bits set in the constant that are not demanded.  If so, shrink the
00353     /// constant and return true.
00354     bool ShrinkDemandedConstant(SDOperand Op, uint64_t Demanded);
00355   };
00356                                                 
00357   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
00358   /// use this predicate to simplify operations downstream.  Op and Mask are
00359   /// known to be the same type.
00360   bool MaskedValueIsZero(SDOperand Op, uint64_t Mask, unsigned Depth = 0)
00361     const;
00362   
00363   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
00364   /// known to be either zero or one and return them in the KnownZero/KnownOne
00365   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
00366   /// processing.  Targets can implement the computeMaskedBitsForTargetNode 
00367   /// method, to allow target nodes to be understood.
00368   void ComputeMaskedBits(SDOperand Op, uint64_t Mask, uint64_t &KnownZero,
00369                          uint64_t &KnownOne, unsigned Depth = 0) const;
00370     
00371   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
00372   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
00373   /// use this information to simplify Op, create a new simplified DAG node and
00374   /// return true, returning the original and new nodes in Old and New. 
00375   /// Otherwise, analyze the expression and return a mask of KnownOne and 
00376   /// KnownZero bits for the expression (used to simplify the caller).  
00377   /// The KnownZero/One bits may only be accurate for those bits in the 
00378   /// DemandedMask.
00379   bool SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask, 
00380                             uint64_t &KnownZero, uint64_t &KnownOne,
00381                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
00382   
00383   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
00384   /// Mask are known to be either zero or one and return them in the 
00385   /// KnownZero/KnownOne bitsets.
00386   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
00387                                               uint64_t Mask,
00388                                               uint64_t &KnownZero, 
00389                                               uint64_t &KnownOne,
00390                                               unsigned Depth = 0) const;
00391 
00392   /// ComputeNumSignBits - Return the number of times the sign bit of the
00393   /// register is replicated into the other bits.  We know that at least 1 bit
00394   /// is always equal to the sign bit (itself), but other cases can give us
00395   /// information.  For example, immediately after an "SRA X, 2", we know that
00396   /// the top 3 bits are all equal to each other, so we return 3.
00397   unsigned ComputeNumSignBits(SDOperand Op, unsigned Depth = 0) const;
00398   
00399   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
00400   /// targets that want to expose additional information about sign bits to the
00401   /// DAG Combiner.
00402   virtual unsigned ComputeNumSignBitsForTargetNode(SDOperand Op,
00403                                                    unsigned Depth = 0) const;
00404   
00405   struct DAGCombinerInfo {
00406     void *DC;  // The DAG Combiner object.
00407     bool BeforeLegalize;
00408   public:
00409     SelectionDAG &DAG;
00410     
00411     DAGCombinerInfo(SelectionDAG &dag, bool bl, void *dc)
00412       : DC(dc), BeforeLegalize(bl), DAG(dag) {}
00413     
00414     bool isBeforeLegalize() const { return BeforeLegalize; }
00415     
00416     void AddToWorklist(SDNode *N);
00417     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
00418     SDOperand CombineTo(SDNode *N, SDOperand Res);
00419     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
00420   };
00421 
00422   /// PerformDAGCombine - This method will be invoked for all target nodes and
00423   /// for any target-independent nodes that the target has registered with
00424   /// invoke it for.
00425   ///
00426   /// The semantics are as follows:
00427   /// Return Value:
00428   ///   SDOperand.Val == 0   - No change was made
00429   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
00430   ///   otherwise            - N should be replaced by the returned Operand.
00431   ///
00432   /// In addition, methods provided by DAGCombinerInfo may be used to perform
00433   /// more complex transformations.
00434   ///
00435   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
00436   
00437   //===--------------------------------------------------------------------===//
00438   // TargetLowering Configuration Methods - These methods should be invoked by
00439   // the derived class constructor to configure this object for the target.
00440   //
00441 
00442 protected:
00443 
00444   /// setShiftAmountType - Describe the type that should be used for shift
00445   /// amounts.  This type defaults to the pointer type.
00446   void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
00447 
00448   /// setSetCCResultType - Describe the type that shoudl be used as the result
00449   /// of a setcc operation.  This defaults to the pointer type.
00450   void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
00451 
00452   /// setSetCCResultContents - Specify how the target extends the result of a
00453   /// setcc operation in a register.
00454   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
00455 
00456   /// setSchedulingPreference - Specify the target scheduling preference.
00457   void setSchedulingPreference(SchedPreference Pref) {
00458     SchedPreferenceInfo = Pref;
00459   }
00460 
00461   /// setShiftAmountFlavor - Describe how the target handles out of range shift
00462   /// amounts.
00463   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
00464     ShiftAmtHandling = OORSA;
00465   }
00466 
00467   /// setUseUnderscoreSetJmpLongJmp - Indicate whether this target prefers to
00468   /// use _setjmp and _longjmp to or implement llvm.setjmp/llvm.longjmp or
00469   /// the non _ versions.  Defaults to false.
00470   void setUseUnderscoreSetJmpLongJmp(bool Val) {
00471     UseUnderscoreSetJmpLongJmp = Val;
00472   }
00473   
00474   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
00475   /// specifies the register that llvm.savestack/llvm.restorestack should save
00476   /// and restore.
00477   void setStackPointerRegisterToSaveRestore(unsigned R) {
00478     StackPointerRegisterToSaveRestore = R;
00479   }
00480   
00481   /// setSetCCIxExpensive - This is a short term hack for targets that codegen
00482   /// setcc as a conditional branch.  This encourages the code generator to fold
00483   /// setcc operations into other operations if possible.
00484   void setSetCCIsExpensive() { SetCCIsExpensive = true; }
00485 
00486   /// setIntDivIsCheap - Tells the code generator that integer divide is
00487   /// expensive, and if possible, should be replaced by an alternate sequence
00488   /// of instructions not containing an integer divide.
00489   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
00490   
00491   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
00492   /// srl/add/sra for a signed divide by power of two, and let the target handle
00493   /// it.
00494   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
00495   
00496   /// addRegisterClass - Add the specified register class as an available
00497   /// regclass for the specified value type.  This indicates the selector can
00498   /// handle values of that class natively.
00499   void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
00500     AvailableRegClasses.push_back(std::make_pair(VT, RC));
00501     RegClassForVT[VT] = RC;
00502   }
00503 
00504   /// computeRegisterProperties - Once all of the register classes are added,
00505   /// this allows us to compute derived properties we expose.
00506   void computeRegisterProperties();
00507 
00508   /// setOperationAction - Indicate that the specified operation does not work
00509   /// with the specified type and indicate what to do about it.
00510   void setOperationAction(unsigned Op, MVT::ValueType VT,
00511                           LegalizeAction Action) {
00512     assert(VT < 32 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
00513            "Table isn't big enough!");
00514     OpActions[Op] &= ~(uint64_t(3UL) << VT*2);
00515     OpActions[Op] |= (uint64_t)Action << VT*2;
00516   }
00517   
00518   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
00519   /// promotion code defaults to trying a larger integer/fp until it can find
00520   /// one that works.  If that default is insufficient, this method can be used
00521   /// by the target to override the default.
00522   void AddPromotedToType(unsigned Opc, MVT::ValueType OrigVT, 
00523                          MVT::ValueType DestVT) {
00524     PromoteToType[std::make_pair(Opc, OrigVT)] = DestVT;
00525   }
00526 
00527   /// addLegalFPImmediate - Indicate that this target can instruction select
00528   /// the specified FP immediate natively.
00529   void addLegalFPImmediate(double Imm) {
00530     LegalFPImmediates.push_back(Imm);
00531   }
00532 
00533   /// setTargetDAGCombine - Targets should invoke this method for each target
00534   /// independent node that they want to provide a custom DAG combiner for by
00535   /// implementing the PerformDAGCombine virtual method.
00536   void setTargetDAGCombine(ISD::NodeType NT) {
00537     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
00538   }
00539   
00540 public:
00541 
00542   //===--------------------------------------------------------------------===//
00543   // Lowering methods - These methods must be implemented by targets so that
00544   // the SelectionDAGLowering code knows how to lower these.
00545   //
00546 
00547   /// LowerArguments - This hook must be implemented to indicate how we should
00548   /// lower the arguments for the specified function, into the specified DAG.
00549   virtual std::vector<SDOperand>
00550   LowerArguments(Function &F, SelectionDAG &DAG);
00551 
00552   /// LowerCallTo - This hook lowers an abstract call to a function into an
00553   /// actual call.  This returns a pair of operands.  The first element is the
00554   /// return value for the function (if RetTy is not VoidTy).  The second
00555   /// element is the outgoing token chain.
00556   typedef std::vector<std::pair<SDOperand, const Type*> > ArgListTy;
00557   virtual std::pair<SDOperand, SDOperand>
00558   LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
00559               unsigned CallingConv, bool isTailCall, SDOperand Callee,
00560               ArgListTy &Args, SelectionDAG &DAG);
00561 
00562   /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
00563   /// llvm.frameaddress (depending on the value of the first argument).  The
00564   /// return values are the result pointer and the resultant token chain.  If
00565   /// not implemented, both of these intrinsics will return null.
00566   virtual std::pair<SDOperand, SDOperand>
00567   LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
00568                           SelectionDAG &DAG);
00569 
00570   /// LowerOperation - This callback is invoked for operations that are 
00571   /// unsupported by the target, which are registered to use 'custom' lowering,
00572   /// and whose defined values are all legal.
00573   /// If the target has no operations that require custom lowering, it need not
00574   /// implement this.  The default implementation of this aborts.
00575   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
00576 
00577   /// CustomPromoteOperation - This callback is invoked for operations that are
00578   /// unsupported by the target, are registered to use 'custom' lowering, and
00579   /// whose type needs to be promoted.
00580   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
00581   
00582   /// getTargetNodeName() - This method returns the name of a target specific
00583   /// DAG node.
00584   virtual const char *getTargetNodeName(unsigned Opcode) const;
00585 
00586   //===--------------------------------------------------------------------===//
00587   // Inline Asm Support hooks
00588   //
00589   
00590   enum ConstraintType {
00591     C_Register,            // Constraint represents a single register.
00592     C_RegisterClass,       // Constraint represents one or more registers.
00593     C_Memory,              // Memory constraint.
00594     C_Other,               // Something else.
00595     C_Unknown              // Unsupported constraint.
00596   };
00597   
00598   /// getConstraintType - Given a constraint letter, return the type of
00599   /// constraint it is for this target.
00600   virtual ConstraintType getConstraintType(char ConstraintLetter) const;
00601   
00602   
00603   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
00604   /// return a list of registers that can be used to satisfy the constraint.
00605   /// This should only be used for C_RegisterClass constraints.
00606   virtual std::vector<unsigned> 
00607   getRegClassForInlineAsmConstraint(const std::string &Constraint,
00608                                     MVT::ValueType VT) const;
00609 
00610   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
00611   /// {edx}), return the register number and the register class for the
00612   /// register.  This should only be used for C_Register constraints.  On error,
00613   /// this returns a register number of 0.
00614   virtual std::pair<unsigned, const TargetRegisterClass*> 
00615     getRegForInlineAsmConstraint(const std::string &Constraint,
00616                                  MVT::ValueType VT) const;
00617   
00618   
00619   /// isOperandValidForConstraint - Return true if the specified SDOperand is
00620   /// valid for the specified target constraint letter.
00621   virtual bool isOperandValidForConstraint(SDOperand Op, char ConstraintLetter);
00622   
00623   //===--------------------------------------------------------------------===//
00624   // Scheduler hooks
00625   //
00626   
00627   // InsertAtEndOfBasicBlock - This method should be implemented by targets that
00628   // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
00629   // instructions are special in various ways, which require special support to
00630   // insert.  The specified MachineInstr is created but not inserted into any
00631   // basic blocks, and the scheduler passes ownership of it to this method.
00632   virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
00633                                                      MachineBasicBlock *MBB);
00634 
00635   //===--------------------------------------------------------------------===//
00636   // Loop Strength Reduction hooks
00637   //
00638   
00639   /// isLegalAddressImmediate - Return true if the integer value or GlobalValue
00640   /// can be used as the offset of the target addressing mode.
00641   virtual bool isLegalAddressImmediate(int64_t V) const;
00642   virtual bool isLegalAddressImmediate(GlobalValue *GV) const;
00643 
00644   typedef std::vector<unsigned>::const_iterator legal_am_scale_iterator;
00645   legal_am_scale_iterator legal_am_scale_begin() const {
00646     return LegalAddressScales.begin();
00647   }
00648   legal_am_scale_iterator legal_am_scale_end() const {
00649     return LegalAddressScales.end();
00650   }
00651 
00652   //===--------------------------------------------------------------------===//
00653   // Div utility functions
00654   //
00655   SDOperand BuildSDIV(SDNode *N, SelectionDAG &DAG, 
00656           std::vector<SDNode*>* Created) const;
00657   SDOperand BuildUDIV(SDNode *N, SelectionDAG &DAG, 
00658           std::vector<SDNode*>* Created) const;
00659 
00660 
00661 protected:
00662   /// addLegalAddressScale - Add a integer (> 1) value which can be used as
00663   /// scale in the target addressing mode. Note: the ordering matters so the
00664   /// least efficient ones should be entered first.
00665   void addLegalAddressScale(unsigned Scale) {
00666     LegalAddressScales.push_back(Scale);
00667   }
00668 
00669 private:
00670   std::vector<unsigned> LegalAddressScales;
00671   
00672   TargetMachine &TM;
00673   const TargetData *TD;
00674 
00675   /// IsLittleEndian - True if this is a little endian target.
00676   ///
00677   bool IsLittleEndian;
00678 
00679   /// PointerTy - The type to use for pointers, usually i32 or i64.
00680   ///
00681   MVT::ValueType PointerTy;
00682 
00683   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
00684   /// PointerTy is.
00685   MVT::ValueType ShiftAmountTy;
00686 
00687   OutOfRangeShiftAmount ShiftAmtHandling;
00688 
00689   /// SetCCIsExpensive - This is a short term hack for targets that codegen
00690   /// setcc as a conditional branch.  This encourages the code generator to fold
00691   /// setcc operations into other operations if possible.
00692   bool SetCCIsExpensive;
00693 
00694   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
00695   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
00696   /// a real cost model is in place.  If we ever optimize for size, this will be
00697   /// set to true unconditionally.
00698   bool IntDivIsCheap;
00699   
00700   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
00701   /// srl/add/sra for a signed divide by power of two, and let the target handle
00702   /// it.
00703   bool Pow2DivIsCheap;
00704   
00705   /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
00706   /// PointerTy.
00707   MVT::ValueType SetCCResultTy;
00708 
00709   /// SetCCResultContents - Information about the contents of the high-bits in
00710   /// the result of a setcc comparison operation.
00711   SetCCResultValue SetCCResultContents;
00712 
00713   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
00714   /// total cycles or lowest register usage.
00715   SchedPreference SchedPreferenceInfo;
00716   
00717   /// UseUnderscoreSetJmpLongJmp - This target prefers to use _setjmp and
00718   /// _longjmp to implement llvm.setjmp/llvm.longjmp.  Defaults to false.
00719   bool UseUnderscoreSetJmpLongJmp;
00720   
00721   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
00722   /// specifies the register that llvm.savestack/llvm.restorestack should save
00723   /// and restore.
00724   unsigned StackPointerRegisterToSaveRestore;
00725 
00726   /// RegClassForVT - This indicates the default register class to use for
00727   /// each ValueType the target supports natively.
00728   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
00729   unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
00730 
00731   /// TransformToType - For any value types we are promoting or expanding, this
00732   /// contains the value type that we are changing to.  For Expanded types, this
00733   /// contains one step of the expand (e.g. i64 -> i32), even if there are
00734   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
00735   /// by the system, this holds the same type (e.g. i32 -> i32).
00736   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
00737 
00738   /// OpActions - For each operation and each value type, keep a LegalizeAction
00739   /// that indicates how instruction selection should deal with the operation.
00740   /// Most operations are Legal (aka, supported natively by the target), but
00741   /// operations that are not should be described.  Note that operations on
00742   /// non-legal value types are not described here.
00743   uint64_t OpActions[156];
00744   
00745   ValueTypeActionImpl ValueTypeActions;
00746 
00747   std::vector<double> LegalFPImmediates;
00748 
00749   std::vector<std::pair<MVT::ValueType,
00750                         TargetRegisterClass*> > AvailableRegClasses;
00751 
00752   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
00753   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
00754   /// which sets a bit in this array.
00755   unsigned char TargetDAGCombineArray[156/(sizeof(unsigned char)*8)];
00756   
00757   /// PromoteToType - For operations that must be promoted to a specific type,
00758   /// this holds the destination type.  This map should be sparse, so don't hold
00759   /// it as an array.
00760   ///
00761   /// Targets add entries to this map with AddPromotedToType(..), clients access
00762   /// this with getTypeToPromoteTo(..).
00763   std::map<std::pair<unsigned, MVT::ValueType>, MVT::ValueType> PromoteToType;
00764   
00765 protected:
00766   /// When lowering %llvm.memset this field specifies the maximum number of
00767   /// store operations that may be substituted for the call to memset. Targets
00768   /// must set this value based on the cost threshold for that target. Targets
00769   /// should assume that the memset will be done using as many of the largest
00770   /// store operations first, followed by smaller ones, if necessary, per
00771   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
00772   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
00773   /// store.  This only applies to setting a constant array of a constant size.
00774   /// @brief Specify maximum number of store instructions per memset call.
00775   unsigned maxStoresPerMemset;
00776 
00777   /// When lowering %llvm.memcpy this field specifies the maximum number of
00778   /// store operations that may be substituted for a call to memcpy. Targets
00779   /// must set this value based on the cost threshold for that target. Targets
00780   /// should assume that the memcpy will be done using as many of the largest
00781   /// store operations first, followed by smaller ones, if necessary, per
00782   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
00783   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
00784   /// and one 1-byte store. This only applies to copying a constant array of
00785   /// constant size.
00786   /// @brief Specify maximum bytes of store instructions per memcpy call.
00787   unsigned maxStoresPerMemcpy;
00788 
00789   /// When lowering %llvm.memmove this field specifies the maximum number of
00790   /// store instructions that may be substituted for a call to memmove. Targets
00791   /// must set this value based on the cost threshold for that target. Targets
00792   /// should assume that the memmove will be done using as many of the largest
00793   /// store operations first, followed by smaller ones, if necessary, per
00794   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
00795   /// with 8-bit alignment would result in nine 1-byte stores.  This only
00796   /// applies to copying a constant array of constant size.
00797   /// @brief Specify maximum bytes of store instructions per memmove call.
00798   unsigned maxStoresPerMemmove;
00799 
00800   /// This field specifies whether the target machine permits unaligned memory
00801   /// accesses.  This is used, for example, to determine the size of store 
00802   /// operations when copying small arrays and other similar tasks.
00803   /// @brief Indicate whether the target permits unaligned memory accesses.
00804   bool allowUnalignedMemoryAccesses;
00805 };
00806 } // end llvm namespace
00807 
00808 #endif