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