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