Reverting r215966, r215965, r215964, r215963, r215960, r215959, r215958, and r215957...
[oota-llvm.git] / lib / IR / ConstantsContext.h
1 //===-- ConstantsContext.h - Constants-related Context Interals -----------===//
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 helper methods and classes used by
11 // LLVMContextImpl for creating and managing constants.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_LIB_IR_CONSTANTSCONTEXT_H
16 #define LLVM_LIB_IR_CONSTANTSCONTEXT_H
17
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <map>
27 #include <tuple>
28
29 #define DEBUG_TYPE "ir"
30
31 namespace llvm {
32 template<class ValType>
33 struct ConstantTraits;
34
35 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
36 /// behind the scenes to implement unary constant exprs.
37 class UnaryConstantExpr : public ConstantExpr {
38   void anchor() override;
39   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
40 public:
41   // allocate space for exactly one operand
42   void *operator new(size_t s) {
43     return User::operator new(s, 1);
44   }
45   UnaryConstantExpr(unsigned Opcode, Constant *C, Type *Ty)
46     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
47     Op<0>() = C;
48   }
49   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
50 };
51
52 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
53 /// behind the scenes to implement binary constant exprs.
54 class BinaryConstantExpr : public ConstantExpr {
55   void anchor() override;
56   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
57 public:
58   // allocate space for exactly two operands
59   void *operator new(size_t s) {
60     return User::operator new(s, 2);
61   }
62   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2,
63                      unsigned Flags)
64     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
65     Op<0>() = C1;
66     Op<1>() = C2;
67     SubclassOptionalData = Flags;
68   }
69   /// Transparently provide more efficient getOperand methods.
70   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
71 };
72
73 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
74 /// behind the scenes to implement select constant exprs.
75 class SelectConstantExpr : public ConstantExpr {
76   void anchor() override;
77   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
78 public:
79   // allocate space for exactly three operands
80   void *operator new(size_t s) {
81     return User::operator new(s, 3);
82   }
83   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
84     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
85     Op<0>() = C1;
86     Op<1>() = C2;
87     Op<2>() = C3;
88   }
89   /// Transparently provide more efficient getOperand methods.
90   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
91 };
92
93 /// ExtractElementConstantExpr - This class is private to
94 /// Constants.cpp, and is used behind the scenes to implement
95 /// extractelement constant exprs.
96 class ExtractElementConstantExpr : public ConstantExpr {
97   void anchor() override;
98   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
99 public:
100   // allocate space for exactly two operands
101   void *operator new(size_t s) {
102     return User::operator new(s, 2);
103   }
104   ExtractElementConstantExpr(Constant *C1, Constant *C2)
105     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
106                    Instruction::ExtractElement, &Op<0>(), 2) {
107     Op<0>() = C1;
108     Op<1>() = C2;
109   }
110   /// Transparently provide more efficient getOperand methods.
111   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
112 };
113
114 /// InsertElementConstantExpr - This class is private to
115 /// Constants.cpp, and is used behind the scenes to implement
116 /// insertelement constant exprs.
117 class InsertElementConstantExpr : public ConstantExpr {
118   void anchor() override;
119   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
120 public:
121   // allocate space for exactly three operands
122   void *operator new(size_t s) {
123     return User::operator new(s, 3);
124   }
125   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
126     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
127                    &Op<0>(), 3) {
128     Op<0>() = C1;
129     Op<1>() = C2;
130     Op<2>() = C3;
131   }
132   /// Transparently provide more efficient getOperand methods.
133   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
134 };
135
136 /// ShuffleVectorConstantExpr - This class is private to
137 /// Constants.cpp, and is used behind the scenes to implement
138 /// shufflevector constant exprs.
139 class ShuffleVectorConstantExpr : public ConstantExpr {
140   void anchor() override;
141   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
142 public:
143   // allocate space for exactly three operands
144   void *operator new(size_t s) {
145     return User::operator new(s, 3);
146   }
147   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
148   : ConstantExpr(VectorType::get(
149                    cast<VectorType>(C1->getType())->getElementType(),
150                    cast<VectorType>(C3->getType())->getNumElements()),
151                  Instruction::ShuffleVector, 
152                  &Op<0>(), 3) {
153     Op<0>() = C1;
154     Op<1>() = C2;
155     Op<2>() = C3;
156   }
157   /// Transparently provide more efficient getOperand methods.
158   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
159 };
160
161 /// ExtractValueConstantExpr - This class is private to
162 /// Constants.cpp, and is used behind the scenes to implement
163 /// extractvalue constant exprs.
164 class ExtractValueConstantExpr : public ConstantExpr {
165   void anchor() override;
166   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
167 public:
168   // allocate space for exactly one operand
169   void *operator new(size_t s) {
170     return User::operator new(s, 1);
171   }
172   ExtractValueConstantExpr(Constant *Agg, ArrayRef<unsigned> IdxList,
173                            Type *DestTy)
174       : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
175         Indices(IdxList.begin(), IdxList.end()) {
176     Op<0>() = Agg;
177   }
178
179   /// Indices - These identify which value to extract.
180   const SmallVector<unsigned, 4> Indices;
181
182   /// Transparently provide more efficient getOperand methods.
183   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
184 };
185
186 /// InsertValueConstantExpr - This class is private to
187 /// Constants.cpp, and is used behind the scenes to implement
188 /// insertvalue constant exprs.
189 class InsertValueConstantExpr : public ConstantExpr {
190   void anchor() override;
191   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
192 public:
193   // allocate space for exactly one operand
194   void *operator new(size_t s) {
195     return User::operator new(s, 2);
196   }
197   InsertValueConstantExpr(Constant *Agg, Constant *Val,
198                           ArrayRef<unsigned> IdxList, Type *DestTy)
199       : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
200         Indices(IdxList.begin(), IdxList.end()) {
201     Op<0>() = Agg;
202     Op<1>() = Val;
203   }
204
205   /// Indices - These identify the position for the insertion.
206   const SmallVector<unsigned, 4> Indices;
207
208   /// Transparently provide more efficient getOperand methods.
209   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
210 };
211
212
213 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
214 /// used behind the scenes to implement getelementpr constant exprs.
215 class GetElementPtrConstantExpr : public ConstantExpr {
216   void anchor() override;
217   GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
218                             Type *DestTy);
219 public:
220   static GetElementPtrConstantExpr *Create(Constant *C,
221                                            ArrayRef<Constant*> IdxList,
222                                            Type *DestTy,
223                                            unsigned Flags) {
224     GetElementPtrConstantExpr *Result =
225       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
226     Result->SubclassOptionalData = Flags;
227     return Result;
228   }
229   /// Transparently provide more efficient getOperand methods.
230   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
231 };
232
233 // CompareConstantExpr - This class is private to Constants.cpp, and is used
234 // behind the scenes to implement ICmp and FCmp constant expressions. This is
235 // needed in order to store the predicate value for these instructions.
236 class CompareConstantExpr : public ConstantExpr {
237   void anchor() override;
238   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
239 public:
240   // allocate space for exactly two operands
241   void *operator new(size_t s) {
242     return User::operator new(s, 2);
243   }
244   unsigned short predicate;
245   CompareConstantExpr(Type *ty, Instruction::OtherOps opc,
246                       unsigned short pred,  Constant* LHS, Constant* RHS)
247     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
248     Op<0>() = LHS;
249     Op<1>() = RHS;
250   }
251   /// Transparently provide more efficient getOperand methods.
252   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
253 };
254
255 template <>
256 struct OperandTraits<UnaryConstantExpr> :
257   public FixedNumOperandTraits<UnaryConstantExpr, 1> {
258 };
259 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
260
261 template <>
262 struct OperandTraits<BinaryConstantExpr> :
263   public FixedNumOperandTraits<BinaryConstantExpr, 2> {
264 };
265 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
266
267 template <>
268 struct OperandTraits<SelectConstantExpr> :
269   public FixedNumOperandTraits<SelectConstantExpr, 3> {
270 };
271 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
272
273 template <>
274 struct OperandTraits<ExtractElementConstantExpr> :
275   public FixedNumOperandTraits<ExtractElementConstantExpr, 2> {
276 };
277 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
278
279 template <>
280 struct OperandTraits<InsertElementConstantExpr> :
281   public FixedNumOperandTraits<InsertElementConstantExpr, 3> {
282 };
283 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
284
285 template <>
286 struct OperandTraits<ShuffleVectorConstantExpr> :
287     public FixedNumOperandTraits<ShuffleVectorConstantExpr, 3> {
288 };
289 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
290
291 template <>
292 struct OperandTraits<ExtractValueConstantExpr> :
293   public FixedNumOperandTraits<ExtractValueConstantExpr, 1> {
294 };
295 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
296
297 template <>
298 struct OperandTraits<InsertValueConstantExpr> :
299   public FixedNumOperandTraits<InsertValueConstantExpr, 2> {
300 };
301 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
302
303 template <>
304 struct OperandTraits<GetElementPtrConstantExpr> :
305   public VariadicOperandTraits<GetElementPtrConstantExpr, 1> {
306 };
307
308 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
309
310
311 template <>
312 struct OperandTraits<CompareConstantExpr> :
313   public FixedNumOperandTraits<CompareConstantExpr, 2> {
314 };
315 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
316
317 struct ExprMapKeyType {
318   ExprMapKeyType(unsigned opc,
319       ArrayRef<Constant*> ops,
320       unsigned short flags = 0,
321       unsigned short optionalflags = 0,
322       ArrayRef<unsigned> inds = None)
323         : opcode(opc), subclassoptionaldata(optionalflags), subclassdata(flags),
324         operands(ops.begin(), ops.end()), indices(inds.begin(), inds.end()) {}
325   uint8_t opcode;
326   uint8_t subclassoptionaldata;
327   uint16_t subclassdata;
328   std::vector<Constant*> operands;
329   SmallVector<unsigned, 4> indices;
330   bool operator==(const ExprMapKeyType& that) const {
331     return this->opcode == that.opcode &&
332            this->subclassdata == that.subclassdata &&
333            this->subclassoptionaldata == that.subclassoptionaldata &&
334            this->operands == that.operands &&
335            this->indices == that.indices;
336   }
337   bool operator<(const ExprMapKeyType & that) const {
338     return std::tie(opcode, operands, subclassdata, subclassoptionaldata,
339                     indices) <
340            std::tie(that.opcode, that.operands, that.subclassdata,
341                     that.subclassoptionaldata, that.indices);
342   }
343
344   bool operator!=(const ExprMapKeyType& that) const {
345     return !(*this == that);
346   }
347 };
348
349 struct InlineAsmKeyType {
350   InlineAsmKeyType(StringRef AsmString,
351                    StringRef Constraints, bool hasSideEffects,
352                    bool isAlignStack, InlineAsm::AsmDialect asmDialect)
353     : asm_string(AsmString), constraints(Constraints),
354       has_side_effects(hasSideEffects), is_align_stack(isAlignStack),
355       asm_dialect(asmDialect) {}
356   std::string asm_string;
357   std::string constraints;
358   bool has_side_effects;
359   bool is_align_stack;
360   InlineAsm::AsmDialect asm_dialect;
361   bool operator==(const InlineAsmKeyType& that) const {
362     return this->asm_string == that.asm_string &&
363            this->constraints == that.constraints &&
364            this->has_side_effects == that.has_side_effects &&
365            this->is_align_stack == that.is_align_stack &&
366            this->asm_dialect == that.asm_dialect;
367   }
368   bool operator<(const InlineAsmKeyType& that) const {
369     return std::tie(asm_string, constraints, has_side_effects, is_align_stack,
370                     asm_dialect) <
371            std::tie(that.asm_string, that.constraints, that.has_side_effects,
372                     that.is_align_stack, that.asm_dialect);
373   }
374
375   bool operator!=(const InlineAsmKeyType& that) const {
376     return !(*this == that);
377   }
378 };
379
380 // The number of operands for each ConstantCreator::create method is
381 // determined by the ConstantTraits template.
382 // ConstantCreator - A class that is used to create constants by
383 // ConstantUniqueMap*.  This class should be partially specialized if there is
384 // something strange that needs to be done to interface to the ctor for the
385 // constant.
386 //
387 template<typename T, typename Alloc>
388 struct ConstantTraits< std::vector<T, Alloc> > {
389   static unsigned uses(const std::vector<T, Alloc>& v) {
390     return v.size();
391   }
392 };
393
394 template<>
395 struct ConstantTraits<Constant *> {
396   static unsigned uses(Constant * const & v) {
397     return 1;
398   }
399 };
400
401 template<class ConstantClass, class TypeClass, class ValType>
402 struct ConstantCreator {
403   static ConstantClass *create(TypeClass *Ty, const ValType &V) {
404     return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
405   }
406 };
407
408 template<class ConstantClass, class TypeClass>
409 struct ConstantArrayCreator {
410   static ConstantClass *create(TypeClass *Ty, ArrayRef<Constant*> V) {
411     return new(V.size()) ConstantClass(Ty, V);
412   }
413 };
414
415 template<class ConstantClass>
416 struct ConstantKeyData {
417   typedef void ValType;
418   static ValType getValType(ConstantClass *C) {
419     llvm_unreachable("Unknown Constant type!");
420   }
421 };
422
423 template<>
424 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
425   static ConstantExpr *create(Type *Ty, const ExprMapKeyType &V,
426       unsigned short pred = 0) {
427     if (Instruction::isCast(V.opcode))
428       return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
429     if ((V.opcode >= Instruction::BinaryOpsBegin &&
430          V.opcode < Instruction::BinaryOpsEnd))
431       return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1],
432                                     V.subclassoptionaldata);
433     if (V.opcode == Instruction::Select)
434       return new SelectConstantExpr(V.operands[0], V.operands[1], 
435                                     V.operands[2]);
436     if (V.opcode == Instruction::ExtractElement)
437       return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
438     if (V.opcode == Instruction::InsertElement)
439       return new InsertElementConstantExpr(V.operands[0], V.operands[1],
440                                            V.operands[2]);
441     if (V.opcode == Instruction::ShuffleVector)
442       return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
443                                            V.operands[2]);
444     if (V.opcode == Instruction::InsertValue)
445       return new InsertValueConstantExpr(V.operands[0], V.operands[1],
446                                          V.indices, Ty);
447     if (V.opcode == Instruction::ExtractValue)
448       return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
449     if (V.opcode == Instruction::GetElementPtr) {
450       std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
451       return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty,
452                                                V.subclassoptionaldata);
453     }
454
455     // The compare instructions are weird. We have to encode the predicate
456     // value and it is combined with the instruction opcode by multiplying
457     // the opcode by one hundred. We must decode this to get the predicate.
458     if (V.opcode == Instruction::ICmp)
459       return new CompareConstantExpr(Ty, Instruction::ICmp, V.subclassdata,
460                                      V.operands[0], V.operands[1]);
461     if (V.opcode == Instruction::FCmp) 
462       return new CompareConstantExpr(Ty, Instruction::FCmp, V.subclassdata,
463                                      V.operands[0], V.operands[1]);
464     llvm_unreachable("Invalid ConstantExpr!");
465   }
466 };
467
468 template<>
469 struct ConstantKeyData<ConstantExpr> {
470   typedef ExprMapKeyType ValType;
471   static ValType getValType(ConstantExpr *CE) {
472     std::vector<Constant*> Operands;
473     Operands.reserve(CE->getNumOperands());
474     for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
475       Operands.push_back(cast<Constant>(CE->getOperand(i)));
476     return ExprMapKeyType(CE->getOpcode(), Operands,
477         CE->isCompare() ? CE->getPredicate() : 0,
478         CE->getRawSubclassOptionalData(),
479         CE->hasIndices() ?
480           CE->getIndices() : ArrayRef<unsigned>());
481   }
482 };
483
484 template<>
485 struct ConstantCreator<InlineAsm, PointerType, InlineAsmKeyType> {
486   static InlineAsm *create(PointerType *Ty, const InlineAsmKeyType &Key) {
487     return new InlineAsm(Ty, Key.asm_string, Key.constraints,
488                          Key.has_side_effects, Key.is_align_stack,
489                          Key.asm_dialect);
490   }
491 };
492
493 template<>
494 struct ConstantKeyData<InlineAsm> {
495   typedef InlineAsmKeyType ValType;
496   static ValType getValType(InlineAsm *Asm) {
497     return InlineAsmKeyType(Asm->getAsmString(), Asm->getConstraintString(),
498                             Asm->hasSideEffects(), Asm->isAlignStack(),
499                             Asm->getDialect());
500   }
501 };
502
503 template<class ValType, class ValRefType, class TypeClass, class ConstantClass,
504          bool HasLargeKey = false /*true for arrays and structs*/ >
505 class ConstantUniqueMap {
506 public:
507   typedef std::pair<TypeClass*, ValType> MapKey;
508   typedef std::map<MapKey, ConstantClass *> MapTy;
509   typedef std::map<ConstantClass *, typename MapTy::iterator> InverseMapTy;
510 private:
511   /// Map - This is the main map from the element descriptor to the Constants.
512   /// This is the primary way we avoid creating two of the same shape
513   /// constant.
514   MapTy Map;
515     
516   /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
517   /// from the constants to their element in Map.  This is important for
518   /// removal of constants from the array, which would otherwise have to scan
519   /// through the map with very large keys.
520   InverseMapTy InverseMap;
521
522 public:
523   typename MapTy::iterator map_begin() { return Map.begin(); }
524   typename MapTy::iterator map_end() { return Map.end(); }
525
526   void freeConstants() {
527     for (typename MapTy::iterator I=Map.begin(), E=Map.end();
528          I != E; ++I) {
529       // Asserts that use_empty().
530       delete I->second;
531     }
532   }
533     
534   /// InsertOrGetItem - Return an iterator for the specified element.
535   /// If the element exists in the map, the returned iterator points to the
536   /// entry and Exists=true.  If not, the iterator points to the newly
537   /// inserted entry and returns Exists=false.  Newly inserted entries have
538   /// I->second == 0, and should be filled in.
539   typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, ConstantClass *>
540                                  &InsertVal,
541                                  bool &Exists) {
542     std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
543     Exists = !IP.second;
544     return IP.first;
545   }
546     
547 private:
548   typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
549     if (HasLargeKey) {
550       typename InverseMapTy::iterator IMI = InverseMap.find(CP);
551       assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
552              IMI->second->second == CP &&
553              "InverseMap corrupt!");
554       return IMI->second;
555     }
556       
557     typename MapTy::iterator I =
558       Map.find(MapKey(static_cast<TypeClass*>(CP->getType()),
559                       ConstantKeyData<ConstantClass>::getValType(CP)));
560     if (I == Map.end() || I->second != CP) {
561       // FIXME: This should not use a linear scan.  If this gets to be a
562       // performance problem, someone should look at this.
563       for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
564         /* empty */;
565     }
566     return I;
567   }
568
569   ConstantClass *Create(TypeClass *Ty, ValRefType V,
570                         typename MapTy::iterator I) {
571     ConstantClass* Result =
572       ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
573
574     assert(Result->getType() == Ty && "Type specified is not correct!");
575     I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
576
577     if (HasLargeKey)  // Remember the reverse mapping if needed.
578       InverseMap.insert(std::make_pair(Result, I));
579
580     return Result;
581   }
582 public:
583     
584   /// getOrCreate - Return the specified constant from the map, creating it if
585   /// necessary.
586   ConstantClass *getOrCreate(TypeClass *Ty, ValRefType V) {
587     MapKey Lookup(Ty, V);
588     ConstantClass* Result = nullptr;
589     
590     typename MapTy::iterator I = Map.find(Lookup);
591     // Is it in the map?  
592     if (I != Map.end())
593       Result = I->second;
594         
595     if (!Result) {
596       // If no preexisting value, create one now...
597       Result = Create(Ty, V, I);
598     }
599         
600     return Result;
601   }
602
603   void remove(ConstantClass *CP) {
604     typename MapTy::iterator I = FindExistingElement(CP);
605     assert(I != Map.end() && "Constant not found in constant table!");
606     assert(I->second == CP && "Didn't find correct element?");
607
608     if (HasLargeKey)  // Remember the reverse mapping if needed.
609       InverseMap.erase(CP);
610
611     Map.erase(I);
612   }
613
614   /// MoveConstantToNewSlot - If we are about to change C to be the element
615   /// specified by I, update our internal data structures to reflect this
616   /// fact.
617   void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
618     // First, remove the old location of the specified constant in the map.
619     typename MapTy::iterator OldI = FindExistingElement(C);
620     assert(OldI != Map.end() && "Constant not found in constant table!");
621     assert(OldI->second == C && "Didn't find correct element?");
622       
623      // Remove the old entry from the map.
624     Map.erase(OldI);
625     
626     // Update the inverse map so that we know that this constant is now
627     // located at descriptor I.
628     if (HasLargeKey) {
629       assert(I->second == C && "Bad inversemap entry!");
630       InverseMap[C] = I;
631     }
632   }
633
634   void dump() const {
635     DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");
636   }
637 };
638
639 // Unique map for aggregate constants
640 template<class TypeClass, class ConstantClass>
641 class ConstantAggrUniqueMap {
642 public:
643   typedef ArrayRef<Constant*> Operands;
644   typedef std::pair<TypeClass*, Operands> LookupKey;
645 private:
646   struct MapInfo {
647     typedef DenseMapInfo<ConstantClass*> ConstantClassInfo;
648     typedef DenseMapInfo<Constant*> ConstantInfo;
649     typedef DenseMapInfo<TypeClass*> TypeClassInfo;
650     static inline ConstantClass* getEmptyKey() {
651       return ConstantClassInfo::getEmptyKey();
652     }
653     static inline ConstantClass* getTombstoneKey() {
654       return ConstantClassInfo::getTombstoneKey();
655     }
656     static unsigned getHashValue(const ConstantClass *CP) {
657       SmallVector<Constant*, 8> CPOperands;
658       CPOperands.reserve(CP->getNumOperands());
659       for (unsigned I = 0, E = CP->getNumOperands(); I < E; ++I)
660         CPOperands.push_back(CP->getOperand(I));
661       return getHashValue(LookupKey(CP->getType(), CPOperands));
662     }
663     static bool isEqual(const ConstantClass *LHS, const ConstantClass *RHS) {
664       return LHS == RHS;
665     }
666     static unsigned getHashValue(const LookupKey &Val) {
667       return hash_combine(Val.first, hash_combine_range(Val.second.begin(),
668                                                         Val.second.end()));
669     }
670     static bool isEqual(const LookupKey &LHS, const ConstantClass *RHS) {
671       if (RHS == getEmptyKey() || RHS == getTombstoneKey())
672         return false;
673       if (LHS.first != RHS->getType()
674           || LHS.second.size() != RHS->getNumOperands())
675         return false;
676       for (unsigned I = 0, E = RHS->getNumOperands(); I < E; ++I) {
677         if (LHS.second[I] != RHS->getOperand(I))
678           return false;
679       }
680       return true;
681     }
682   };
683 public:
684   typedef DenseMap<ConstantClass *, char, MapInfo> MapTy;
685
686 private:
687   /// Map - This is the main map from the element descriptor to the Constants.
688   /// This is the primary way we avoid creating two of the same shape
689   /// constant.
690   MapTy Map;
691
692 public:
693   typename MapTy::iterator map_begin() { return Map.begin(); }
694   typename MapTy::iterator map_end() { return Map.end(); }
695
696   void freeConstants() {
697     for (typename MapTy::iterator I=Map.begin(), E=Map.end();
698          I != E; ++I) {
699       // Asserts that use_empty().
700       delete I->first;
701     }
702   }
703
704 private:
705   typename MapTy::iterator findExistingElement(ConstantClass *CP) {
706     return Map.find(CP);
707   }
708
709   ConstantClass *Create(TypeClass *Ty, Operands V, typename MapTy::iterator I) {
710     ConstantClass* Result =
711       ConstantArrayCreator<ConstantClass,TypeClass>::create(Ty, V);
712
713     assert(Result->getType() == Ty && "Type specified is not correct!");
714     Map[Result] = '\0';
715
716     return Result;
717   }
718 public:
719
720   /// getOrCreate - Return the specified constant from the map, creating it if
721   /// necessary.
722   ConstantClass *getOrCreate(TypeClass *Ty, Operands V) {
723     LookupKey Lookup(Ty, V);
724     ConstantClass* Result = nullptr;
725
726     typename MapTy::iterator I = Map.find_as(Lookup);
727     // Is it in the map?
728     if (I != Map.end())
729       Result = I->first;
730
731     if (!Result) {
732       // If no preexisting value, create one now...
733       Result = Create(Ty, V, I);
734     }
735
736     return Result;
737   }
738
739   /// Find the constant by lookup key.
740   typename MapTy::iterator find(LookupKey Lookup) {
741     return Map.find_as(Lookup);
742   }
743
744   /// Insert the constant into its proper slot.
745   void insert(ConstantClass *CP) {
746     Map[CP] = '\0';
747   }
748
749   /// Remove this constant from the map
750   void remove(ConstantClass *CP) {
751     typename MapTy::iterator I = findExistingElement(CP);
752     assert(I != Map.end() && "Constant not found in constant table!");
753     assert(I->first == CP && "Didn't find correct element?");
754     Map.erase(I);
755   }
756
757   void dump() const {
758     DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");
759   }
760 };
761
762 } // end namespace llvm
763
764 #endif