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