LLVM API Documentation

ConstantsContext.h
Go to the documentation of this file.
00001 //===-- ConstantsContext.h - Constants-related Context Interals -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines various helper methods and classes used by
00011 // LLVMContextImpl for creating and managing constants.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CONSTANTSCONTEXT_H
00016 #define LLVM_CONSTANTSCONTEXT_H
00017 
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/Hashing.h"
00020 #include "llvm/IR/InlineAsm.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/Operator.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include <map>
00027 
00028 #define DEBUG_TYPE "ir"
00029 
00030 namespace llvm {
00031 template<class ValType>
00032 struct ConstantTraits;
00033 
00034 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
00035 /// behind the scenes to implement unary constant exprs.
00036 class UnaryConstantExpr : public ConstantExpr {
00037   void anchor() override;
00038   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00039 public:
00040   // allocate space for exactly one operand
00041   void *operator new(size_t s) {
00042     return User::operator new(s, 1);
00043   }
00044   UnaryConstantExpr(unsigned Opcode, Constant *C, Type *Ty)
00045     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
00046     Op<0>() = C;
00047   }
00048   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00049 };
00050 
00051 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
00052 /// behind the scenes to implement binary constant exprs.
00053 class BinaryConstantExpr : public ConstantExpr {
00054   void anchor() override;
00055   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00056 public:
00057   // allocate space for exactly two operands
00058   void *operator new(size_t s) {
00059     return User::operator new(s, 2);
00060   }
00061   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2,
00062                      unsigned Flags)
00063     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
00064     Op<0>() = C1;
00065     Op<1>() = C2;
00066     SubclassOptionalData = Flags;
00067   }
00068   /// Transparently provide more efficient getOperand methods.
00069   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00070 };
00071 
00072 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
00073 /// behind the scenes to implement select constant exprs.
00074 class SelectConstantExpr : public ConstantExpr {
00075   void anchor() override;
00076   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00077 public:
00078   // allocate space for exactly three operands
00079   void *operator new(size_t s) {
00080     return User::operator new(s, 3);
00081   }
00082   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00083     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
00084     Op<0>() = C1;
00085     Op<1>() = C2;
00086     Op<2>() = C3;
00087   }
00088   /// Transparently provide more efficient getOperand methods.
00089   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00090 };
00091 
00092 /// ExtractElementConstantExpr - This class is private to
00093 /// Constants.cpp, and is used behind the scenes to implement
00094 /// extractelement constant exprs.
00095 class ExtractElementConstantExpr : public ConstantExpr {
00096   void anchor() override;
00097   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00098 public:
00099   // allocate space for exactly two operands
00100   void *operator new(size_t s) {
00101     return User::operator new(s, 2);
00102   }
00103   ExtractElementConstantExpr(Constant *C1, Constant *C2)
00104     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
00105                    Instruction::ExtractElement, &Op<0>(), 2) {
00106     Op<0>() = C1;
00107     Op<1>() = C2;
00108   }
00109   /// Transparently provide more efficient getOperand methods.
00110   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00111 };
00112 
00113 /// InsertElementConstantExpr - This class is private to
00114 /// Constants.cpp, and is used behind the scenes to implement
00115 /// insertelement constant exprs.
00116 class InsertElementConstantExpr : public ConstantExpr {
00117   void anchor() override;
00118   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00119 public:
00120   // allocate space for exactly three operands
00121   void *operator new(size_t s) {
00122     return User::operator new(s, 3);
00123   }
00124   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00125     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
00126                    &Op<0>(), 3) {
00127     Op<0>() = C1;
00128     Op<1>() = C2;
00129     Op<2>() = C3;
00130   }
00131   /// Transparently provide more efficient getOperand methods.
00132   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00133 };
00134 
00135 /// ShuffleVectorConstantExpr - This class is private to
00136 /// Constants.cpp, and is used behind the scenes to implement
00137 /// shufflevector constant exprs.
00138 class ShuffleVectorConstantExpr : public ConstantExpr {
00139   void anchor() override;
00140   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00141 public:
00142   // allocate space for exactly three operands
00143   void *operator new(size_t s) {
00144     return User::operator new(s, 3);
00145   }
00146   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00147   : ConstantExpr(VectorType::get(
00148                    cast<VectorType>(C1->getType())->getElementType(),
00149                    cast<VectorType>(C3->getType())->getNumElements()),
00150                  Instruction::ShuffleVector, 
00151                  &Op<0>(), 3) {
00152     Op<0>() = C1;
00153     Op<1>() = C2;
00154     Op<2>() = C3;
00155   }
00156   /// Transparently provide more efficient getOperand methods.
00157   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00158 };
00159 
00160 /// ExtractValueConstantExpr - This class is private to
00161 /// Constants.cpp, and is used behind the scenes to implement
00162 /// extractvalue constant exprs.
00163 class ExtractValueConstantExpr : public ConstantExpr {
00164   void anchor() override;
00165   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00166 public:
00167   // allocate space for exactly one operand
00168   void *operator new(size_t s) {
00169     return User::operator new(s, 1);
00170   }
00171   ExtractValueConstantExpr(Constant *Agg,
00172                            const SmallVector<unsigned, 4> &IdxList,
00173                            Type *DestTy)
00174     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
00175       Indices(IdxList) {
00176     Op<0>() = Agg;
00177   }
00178 
00179   /// Indices - These identify which value to extract.
00180   const SmallVector<unsigned, 4> Indices;
00181 
00182   /// Transparently provide more efficient getOperand methods.
00183   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00184 };
00185 
00186 /// InsertValueConstantExpr - This class is private to
00187 /// Constants.cpp, and is used behind the scenes to implement
00188 /// insertvalue constant exprs.
00189 class InsertValueConstantExpr : public ConstantExpr {
00190   void anchor() override;
00191   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00192 public:
00193   // allocate space for exactly one operand
00194   void *operator new(size_t s) {
00195     return User::operator new(s, 2);
00196   }
00197   InsertValueConstantExpr(Constant *Agg, Constant *Val,
00198                           const SmallVector<unsigned, 4> &IdxList,
00199                           Type *DestTy)
00200     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
00201       Indices(IdxList) {
00202     Op<0>() = Agg;
00203     Op<1>() = Val;
00204   }
00205 
00206   /// Indices - These identify the position for the insertion.
00207   const SmallVector<unsigned, 4> Indices;
00208 
00209   /// Transparently provide more efficient getOperand methods.
00210   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00211 };
00212 
00213 
00214 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
00215 /// used behind the scenes to implement getelementpr constant exprs.
00216 class GetElementPtrConstantExpr : public ConstantExpr {
00217   void anchor() override;
00218   GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
00219                             Type *DestTy);
00220 public:
00221   static GetElementPtrConstantExpr *Create(Constant *C,
00222                                            ArrayRef<Constant*> IdxList,
00223                                            Type *DestTy,
00224                                            unsigned Flags) {
00225     GetElementPtrConstantExpr *Result =
00226       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
00227     Result->SubclassOptionalData = Flags;
00228     return Result;
00229   }
00230   /// Transparently provide more efficient getOperand methods.
00231   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00232 };
00233 
00234 // CompareConstantExpr - This class is private to Constants.cpp, and is used
00235 // behind the scenes to implement ICmp and FCmp constant expressions. This is
00236 // needed in order to store the predicate value for these instructions.
00237 class CompareConstantExpr : public ConstantExpr {
00238   void anchor() override;
00239   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
00240 public:
00241   // allocate space for exactly two operands
00242   void *operator new(size_t s) {
00243     return User::operator new(s, 2);
00244   }
00245   unsigned short predicate;
00246   CompareConstantExpr(Type *ty, Instruction::OtherOps opc,
00247                       unsigned short pred,  Constant* LHS, Constant* RHS)
00248     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
00249     Op<0>() = LHS;
00250     Op<1>() = RHS;
00251   }
00252   /// Transparently provide more efficient getOperand methods.
00253   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00254 };
00255 
00256 template <>
00257 struct OperandTraits<UnaryConstantExpr> :
00258   public FixedNumOperandTraits<UnaryConstantExpr, 1> {
00259 };
00260 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
00261 
00262 template <>
00263 struct OperandTraits<BinaryConstantExpr> :
00264   public FixedNumOperandTraits<BinaryConstantExpr, 2> {
00265 };
00266 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
00267 
00268 template <>
00269 struct OperandTraits<SelectConstantExpr> :
00270   public FixedNumOperandTraits<SelectConstantExpr, 3> {
00271 };
00272 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
00273 
00274 template <>
00275 struct OperandTraits<ExtractElementConstantExpr> :
00276   public FixedNumOperandTraits<ExtractElementConstantExpr, 2> {
00277 };
00278 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
00279 
00280 template <>
00281 struct OperandTraits<InsertElementConstantExpr> :
00282   public FixedNumOperandTraits<InsertElementConstantExpr, 3> {
00283 };
00284 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
00285 
00286 template <>
00287 struct OperandTraits<ShuffleVectorConstantExpr> :
00288     public FixedNumOperandTraits<ShuffleVectorConstantExpr, 3> {
00289 };
00290 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
00291 
00292 template <>
00293 struct OperandTraits<ExtractValueConstantExpr> :
00294   public FixedNumOperandTraits<ExtractValueConstantExpr, 1> {
00295 };
00296 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
00297 
00298 template <>
00299 struct OperandTraits<InsertValueConstantExpr> :
00300   public FixedNumOperandTraits<InsertValueConstantExpr, 2> {
00301 };
00302 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
00303 
00304 template <>
00305 struct OperandTraits<GetElementPtrConstantExpr> :
00306   public VariadicOperandTraits<GetElementPtrConstantExpr, 1> {
00307 };
00308 
00309 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
00310 
00311 
00312 template <>
00313 struct OperandTraits<CompareConstantExpr> :
00314   public FixedNumOperandTraits<CompareConstantExpr, 2> {
00315 };
00316 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
00317 
00318 struct ExprMapKeyType {
00319   ExprMapKeyType(unsigned opc,
00320       ArrayRef<Constant*> ops,
00321       unsigned short flags = 0,
00322       unsigned short optionalflags = 0,
00323       ArrayRef<unsigned> inds = None)
00324         : opcode(opc), subclassoptionaldata(optionalflags), subclassdata(flags),
00325         operands(ops.begin(), ops.end()), indices(inds.begin(), inds.end()) {}
00326   uint8_t opcode;
00327   uint8_t subclassoptionaldata;
00328   uint16_t subclassdata;
00329   std::vector<Constant*> operands;
00330   SmallVector<unsigned, 4> indices;
00331   bool operator==(const ExprMapKeyType& that) const {
00332     return this->opcode == that.opcode &&
00333            this->subclassdata == that.subclassdata &&
00334            this->subclassoptionaldata == that.subclassoptionaldata &&
00335            this->operands == that.operands &&
00336            this->indices == that.indices;
00337   }
00338   bool operator<(const ExprMapKeyType & that) const {
00339     return std::tie(opcode, operands, subclassdata, subclassoptionaldata,
00340                     indices) <
00341            std::tie(that.opcode, that.operands, that.subclassdata,
00342                     that.subclassoptionaldata, that.indices);
00343   }
00344 
00345   bool operator!=(const ExprMapKeyType& that) const {
00346     return !(*this == that);
00347   }
00348 };
00349 
00350 struct InlineAsmKeyType {
00351   InlineAsmKeyType(StringRef AsmString,
00352                    StringRef Constraints, bool hasSideEffects,
00353                    bool isAlignStack, InlineAsm::AsmDialect asmDialect)
00354     : asm_string(AsmString), constraints(Constraints),
00355       has_side_effects(hasSideEffects), is_align_stack(isAlignStack),
00356       asm_dialect(asmDialect) {}
00357   std::string asm_string;
00358   std::string constraints;
00359   bool has_side_effects;
00360   bool is_align_stack;
00361   InlineAsm::AsmDialect asm_dialect;
00362   bool operator==(const InlineAsmKeyType& that) const {
00363     return this->asm_string == that.asm_string &&
00364            this->constraints == that.constraints &&
00365            this->has_side_effects == that.has_side_effects &&
00366            this->is_align_stack == that.is_align_stack &&
00367            this->asm_dialect == that.asm_dialect;
00368   }
00369   bool operator<(const InlineAsmKeyType& that) const {
00370     return std::tie(asm_string, constraints, has_side_effects, is_align_stack,
00371                     asm_dialect) <
00372            std::tie(that.asm_string, that.constraints, that.has_side_effects,
00373                     that.is_align_stack, that.asm_dialect);
00374   }
00375 
00376   bool operator!=(const InlineAsmKeyType& that) const {
00377     return !(*this == that);
00378   }
00379 };
00380 
00381 // The number of operands for each ConstantCreator::create method is
00382 // determined by the ConstantTraits template.
00383 // ConstantCreator - A class that is used to create constants by
00384 // ConstantUniqueMap*.  This class should be partially specialized if there is
00385 // something strange that needs to be done to interface to the ctor for the
00386 // constant.
00387 //
00388 template<typename T, typename Alloc>
00389 struct ConstantTraits< std::vector<T, Alloc> > {
00390   static unsigned uses(const std::vector<T, Alloc>& v) {
00391     return v.size();
00392   }
00393 };
00394 
00395 template<>
00396 struct ConstantTraits<Constant *> {
00397   static unsigned uses(Constant * const & v) {
00398     return 1;
00399   }
00400 };
00401 
00402 template<class ConstantClass, class TypeClass, class ValType>
00403 struct ConstantCreator {
00404   static ConstantClass *create(TypeClass *Ty, const ValType &V) {
00405     return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
00406   }
00407 };
00408 
00409 template<class ConstantClass, class TypeClass>
00410 struct ConstantArrayCreator {
00411   static ConstantClass *create(TypeClass *Ty, ArrayRef<Constant*> V) {
00412     return new(V.size()) ConstantClass(Ty, V);
00413   }
00414 };
00415 
00416 template<class ConstantClass>
00417 struct ConstantKeyData {
00418   typedef void ValType;
00419   static ValType getValType(ConstantClass *C) {
00420     llvm_unreachable("Unknown Constant type!");
00421   }
00422 };
00423 
00424 template<>
00425 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
00426   static ConstantExpr *create(Type *Ty, const ExprMapKeyType &V,
00427       unsigned short pred = 0) {
00428     if (Instruction::isCast(V.opcode))
00429       return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
00430     if ((V.opcode >= Instruction::BinaryOpsBegin &&
00431          V.opcode < Instruction::BinaryOpsEnd))
00432       return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1],
00433                                     V.subclassoptionaldata);
00434     if (V.opcode == Instruction::Select)
00435       return new SelectConstantExpr(V.operands[0], V.operands[1], 
00436                                     V.operands[2]);
00437     if (V.opcode == Instruction::ExtractElement)
00438       return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
00439     if (V.opcode == Instruction::InsertElement)
00440       return new InsertElementConstantExpr(V.operands[0], V.operands[1],
00441                                            V.operands[2]);
00442     if (V.opcode == Instruction::ShuffleVector)
00443       return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
00444                                            V.operands[2]);
00445     if (V.opcode == Instruction::InsertValue)
00446       return new InsertValueConstantExpr(V.operands[0], V.operands[1],
00447                                          V.indices, Ty);
00448     if (V.opcode == Instruction::ExtractValue)
00449       return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
00450     if (V.opcode == Instruction::GetElementPtr) {
00451       std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
00452       return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty,
00453                                                V.subclassoptionaldata);
00454     }
00455 
00456     // The compare instructions are weird. We have to encode the predicate
00457     // value and it is combined with the instruction opcode by multiplying
00458     // the opcode by one hundred. We must decode this to get the predicate.
00459     if (V.opcode == Instruction::ICmp)
00460       return new CompareConstantExpr(Ty, Instruction::ICmp, V.subclassdata,
00461                                      V.operands[0], V.operands[1]);
00462     if (V.opcode == Instruction::FCmp) 
00463       return new CompareConstantExpr(Ty, Instruction::FCmp, V.subclassdata,
00464                                      V.operands[0], V.operands[1]);
00465     llvm_unreachable("Invalid ConstantExpr!");
00466   }
00467 };
00468 
00469 template<>
00470 struct ConstantKeyData<ConstantExpr> {
00471   typedef ExprMapKeyType ValType;
00472   static ValType getValType(ConstantExpr *CE) {
00473     std::vector<Constant*> Operands;
00474     Operands.reserve(CE->getNumOperands());
00475     for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
00476       Operands.push_back(cast<Constant>(CE->getOperand(i)));
00477     return ExprMapKeyType(CE->getOpcode(), Operands,
00478         CE->isCompare() ? CE->getPredicate() : 0,
00479         CE->getRawSubclassOptionalData(),
00480         CE->hasIndices() ?
00481           CE->getIndices() : ArrayRef<unsigned>());
00482   }
00483 };
00484 
00485 template<>
00486 struct ConstantCreator<InlineAsm, PointerType, InlineAsmKeyType> {
00487   static InlineAsm *create(PointerType *Ty, const InlineAsmKeyType &Key) {
00488     return new InlineAsm(Ty, Key.asm_string, Key.constraints,
00489                          Key.has_side_effects, Key.is_align_stack,
00490                          Key.asm_dialect);
00491   }
00492 };
00493 
00494 template<>
00495 struct ConstantKeyData<InlineAsm> {
00496   typedef InlineAsmKeyType ValType;
00497   static ValType getValType(InlineAsm *Asm) {
00498     return InlineAsmKeyType(Asm->getAsmString(), Asm->getConstraintString(),
00499                             Asm->hasSideEffects(), Asm->isAlignStack(),
00500                             Asm->getDialect());
00501   }
00502 };
00503 
00504 template<class ValType, class ValRefType, class TypeClass, class ConstantClass,
00505          bool HasLargeKey = false /*true for arrays and structs*/ >
00506 class ConstantUniqueMap {
00507 public:
00508   typedef std::pair<TypeClass*, ValType> MapKey;
00509   typedef std::map<MapKey, ConstantClass *> MapTy;
00510   typedef std::map<ConstantClass *, typename MapTy::iterator> InverseMapTy;
00511 private:
00512   /// Map - This is the main map from the element descriptor to the Constants.
00513   /// This is the primary way we avoid creating two of the same shape
00514   /// constant.
00515   MapTy Map;
00516     
00517   /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
00518   /// from the constants to their element in Map.  This is important for
00519   /// removal of constants from the array, which would otherwise have to scan
00520   /// through the map with very large keys.
00521   InverseMapTy InverseMap;
00522 
00523 public:
00524   typename MapTy::iterator map_begin() { return Map.begin(); }
00525   typename MapTy::iterator map_end() { return Map.end(); }
00526 
00527   void freeConstants() {
00528     for (typename MapTy::iterator I=Map.begin(), E=Map.end();
00529          I != E; ++I) {
00530       // Asserts that use_empty().
00531       delete I->second;
00532     }
00533   }
00534     
00535   /// InsertOrGetItem - Return an iterator for the specified element.
00536   /// If the element exists in the map, the returned iterator points to the
00537   /// entry and Exists=true.  If not, the iterator points to the newly
00538   /// inserted entry and returns Exists=false.  Newly inserted entries have
00539   /// I->second == 0, and should be filled in.
00540   typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, ConstantClass *>
00541                                  &InsertVal,
00542                                  bool &Exists) {
00543     std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
00544     Exists = !IP.second;
00545     return IP.first;
00546   }
00547     
00548 private:
00549   typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
00550     if (HasLargeKey) {
00551       typename InverseMapTy::iterator IMI = InverseMap.find(CP);
00552       assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
00553              IMI->second->second == CP &&
00554              "InverseMap corrupt!");
00555       return IMI->second;
00556     }
00557       
00558     typename MapTy::iterator I =
00559       Map.find(MapKey(static_cast<TypeClass*>(CP->getType()),
00560                       ConstantKeyData<ConstantClass>::getValType(CP)));
00561     if (I == Map.end() || I->second != CP) {
00562       // FIXME: This should not use a linear scan.  If this gets to be a
00563       // performance problem, someone should look at this.
00564       for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
00565         /* empty */;
00566     }
00567     return I;
00568   }
00569 
00570   ConstantClass *Create(TypeClass *Ty, ValRefType V,
00571                         typename MapTy::iterator I) {
00572     ConstantClass* Result =
00573       ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
00574 
00575     assert(Result->getType() == Ty && "Type specified is not correct!");
00576     I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
00577 
00578     if (HasLargeKey)  // Remember the reverse mapping if needed.
00579       InverseMap.insert(std::make_pair(Result, I));
00580 
00581     return Result;
00582   }
00583 public:
00584     
00585   /// getOrCreate - Return the specified constant from the map, creating it if
00586   /// necessary.
00587   ConstantClass *getOrCreate(TypeClass *Ty, ValRefType V) {
00588     MapKey Lookup(Ty, V);
00589     ConstantClass* Result = 0;
00590     
00591     typename MapTy::iterator I = Map.find(Lookup);
00592     // Is it in the map?  
00593     if (I != Map.end())
00594       Result = I->second;
00595         
00596     if (!Result) {
00597       // If no preexisting value, create one now...
00598       Result = Create(Ty, V, I);
00599     }
00600         
00601     return Result;
00602   }
00603 
00604   void remove(ConstantClass *CP) {
00605     typename MapTy::iterator I = FindExistingElement(CP);
00606     assert(I != Map.end() && "Constant not found in constant table!");
00607     assert(I->second == CP && "Didn't find correct element?");
00608 
00609     if (HasLargeKey)  // Remember the reverse mapping if needed.
00610       InverseMap.erase(CP);
00611 
00612     Map.erase(I);
00613   }
00614 
00615   /// MoveConstantToNewSlot - If we are about to change C to be the element
00616   /// specified by I, update our internal data structures to reflect this
00617   /// fact.
00618   void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
00619     // First, remove the old location of the specified constant in the map.
00620     typename MapTy::iterator OldI = FindExistingElement(C);
00621     assert(OldI != Map.end() && "Constant not found in constant table!");
00622     assert(OldI->second == C && "Didn't find correct element?");
00623       
00624      // Remove the old entry from the map.
00625     Map.erase(OldI);
00626     
00627     // Update the inverse map so that we know that this constant is now
00628     // located at descriptor I.
00629     if (HasLargeKey) {
00630       assert(I->second == C && "Bad inversemap entry!");
00631       InverseMap[C] = I;
00632     }
00633   }
00634 
00635   void dump() const {
00636     DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");
00637   }
00638 };
00639 
00640 // Unique map for aggregate constants
00641 template<class TypeClass, class ConstantClass>
00642 class ConstantAggrUniqueMap {
00643 public:
00644   typedef ArrayRef<Constant*> Operands;
00645   typedef std::pair<TypeClass*, Operands> LookupKey;
00646 private:
00647   struct MapInfo {
00648     typedef DenseMapInfo<ConstantClass*> ConstantClassInfo;
00649     typedef DenseMapInfo<Constant*> ConstantInfo;
00650     typedef DenseMapInfo<TypeClass*> TypeClassInfo;
00651     static inline ConstantClass* getEmptyKey() {
00652       return ConstantClassInfo::getEmptyKey();
00653     }
00654     static inline ConstantClass* getTombstoneKey() {
00655       return ConstantClassInfo::getTombstoneKey();
00656     }
00657     static unsigned getHashValue(const ConstantClass *CP) {
00658       SmallVector<Constant*, 8> CPOperands;
00659       CPOperands.reserve(CP->getNumOperands());
00660       for (unsigned I = 0, E = CP->getNumOperands(); I < E; ++I)
00661         CPOperands.push_back(CP->getOperand(I));
00662       return getHashValue(LookupKey(CP->getType(), CPOperands));
00663     }
00664     static bool isEqual(const ConstantClass *LHS, const ConstantClass *RHS) {
00665       return LHS == RHS;
00666     }
00667     static unsigned getHashValue(const LookupKey &Val) {
00668       return hash_combine(Val.first, hash_combine_range(Val.second.begin(),
00669                                                         Val.second.end()));
00670     }
00671     static bool isEqual(const LookupKey &LHS, const ConstantClass *RHS) {
00672       if (RHS == getEmptyKey() || RHS == getTombstoneKey())
00673         return false;
00674       if (LHS.first != RHS->getType()
00675           || LHS.second.size() != RHS->getNumOperands())
00676         return false;
00677       for (unsigned I = 0, E = RHS->getNumOperands(); I < E; ++I) {
00678         if (LHS.second[I] != RHS->getOperand(I))
00679           return false;
00680       }
00681       return true;
00682     }
00683   };
00684 public:
00685   typedef DenseMap<ConstantClass *, char, MapInfo> MapTy;
00686 
00687 private:
00688   /// Map - This is the main map from the element descriptor to the Constants.
00689   /// This is the primary way we avoid creating two of the same shape
00690   /// constant.
00691   MapTy Map;
00692 
00693 public:
00694   typename MapTy::iterator map_begin() { return Map.begin(); }
00695   typename MapTy::iterator map_end() { return Map.end(); }
00696 
00697   void freeConstants() {
00698     for (typename MapTy::iterator I=Map.begin(), E=Map.end();
00699          I != E; ++I) {
00700       // Asserts that use_empty().
00701       delete I->first;
00702     }
00703   }
00704 
00705 private:
00706   typename MapTy::iterator findExistingElement(ConstantClass *CP) {
00707     return Map.find(CP);
00708   }
00709 
00710   ConstantClass *Create(TypeClass *Ty, Operands V, typename MapTy::iterator I) {
00711     ConstantClass* Result =
00712       ConstantArrayCreator<ConstantClass,TypeClass>::create(Ty, V);
00713 
00714     assert(Result->getType() == Ty && "Type specified is not correct!");
00715     Map[Result] = '\0';
00716 
00717     return Result;
00718   }
00719 public:
00720 
00721   /// getOrCreate - Return the specified constant from the map, creating it if
00722   /// necessary.
00723   ConstantClass *getOrCreate(TypeClass *Ty, Operands V) {
00724     LookupKey Lookup(Ty, V);
00725     ConstantClass* Result = 0;
00726 
00727     typename MapTy::iterator I = Map.find_as(Lookup);
00728     // Is it in the map?
00729     if (I != Map.end())
00730       Result = I->first;
00731 
00732     if (!Result) {
00733       // If no preexisting value, create one now...
00734       Result = Create(Ty, V, I);
00735     }
00736 
00737     return Result;
00738   }
00739 
00740   /// Find the constant by lookup key.
00741   typename MapTy::iterator find(LookupKey Lookup) {
00742     return Map.find_as(Lookup);
00743   }
00744 
00745   /// Insert the constant into its proper slot.
00746   void insert(ConstantClass *CP) {
00747     Map[CP] = '\0';
00748   }
00749 
00750   /// Remove this constant from the map
00751   void remove(ConstantClass *CP) {
00752     typename MapTy::iterator I = findExistingElement(CP);
00753     assert(I != Map.end() && "Constant not found in constant table!");
00754     assert(I->first == CP && "Didn't find correct element?");
00755     Map.erase(I);
00756   }
00757 
00758   void dump() const {
00759     DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");
00760   }
00761 };
00762 
00763 }
00764 
00765 #endif