g++ 4.0 doesn't have std::vector::data.
[oota-llvm.git] / lib / VMCore / ConstantsContext.h
1 //===---------------- ConstantsContext.h - Implementation ------*- C++ -*--===//
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/Metadata.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.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     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
58     Op<0>() = C1;
59     Op<1>() = C2;
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     return
211       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
212   }
213   /// Transparently provide more efficient getOperand methods.
214   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
215 };
216
217 // CompareConstantExpr - This class is private to Constants.cpp, and is used
218 // behind the scenes to implement ICmp and FCmp constant expressions. This is
219 // needed in order to store the predicate value for these instructions.
220 struct CompareConstantExpr : public ConstantExpr {
221   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
222   // allocate space for exactly two operands
223   void *operator new(size_t s) {
224     return User::operator new(s, 2);
225   }
226   unsigned short predicate;
227   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
228                       unsigned short pred,  Constant* LHS, Constant* RHS)
229     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
230     Op<0>() = LHS;
231     Op<1>() = RHS;
232   }
233   /// Transparently provide more efficient getOperand methods.
234   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
235 };
236
237 template <>
238 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
239 };
240 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
241
242 template <>
243 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
244 };
245 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
246
247 template <>
248 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
249 };
250 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
251
252 template <>
253 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
254 };
255 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
256
257 template <>
258 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
259 };
260 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
261
262 template <>
263 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
264 };
265 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
266
267 template <>
268 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
269 };
270 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
271
272 template <>
273 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
274 };
275 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
276
277 template <>
278 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
279 };
280
281 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
282
283
284 template <>
285 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
286 };
287 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
288
289 struct ExprMapKeyType {
290   typedef SmallVector<unsigned, 4> IndexList;
291
292   ExprMapKeyType(unsigned opc,
293       const std::vector<Constant*> &ops,
294       unsigned short pred = 0,
295       const IndexList &inds = IndexList())
296         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
297   uint16_t opcode;
298   uint16_t predicate;
299   std::vector<Constant*> operands;
300   IndexList indices;
301   bool operator==(const ExprMapKeyType& that) const {
302     return this->opcode == that.opcode &&
303            this->predicate == that.predicate &&
304            this->operands == that.operands &&
305            this->indices == that.indices;
306   }
307   bool operator<(const ExprMapKeyType & that) const {
308     return this->opcode < that.opcode ||
309       (this->opcode == that.opcode && this->predicate < that.predicate) ||
310       (this->opcode == that.opcode && this->predicate == that.predicate &&
311        this->operands < that.operands) ||
312       (this->opcode == that.opcode && this->predicate == that.predicate &&
313        this->operands == that.operands && this->indices < that.indices);
314   }
315
316   bool operator!=(const ExprMapKeyType& that) const {
317     return !(*this == that);
318   }
319 };
320
321 // The number of operands for each ConstantCreator::create method is
322 // determined by the ConstantTraits template.
323 // ConstantCreator - A class that is used to create constants by
324 // ValueMap*.  This class should be partially specialized if there is
325 // something strange that needs to be done to interface to the ctor for the
326 // constant.
327 //
328 template<typename T, typename Alloc>
329 struct ConstantTraits< std::vector<T, Alloc> > {
330   static unsigned uses(const std::vector<T, Alloc>& v) {
331     return v.size();
332   }
333 };
334
335 template<class ConstantClass, class TypeClass, class ValType>
336 struct ConstantCreator {
337   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
338     return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
339   }
340 };
341
342 template<class ConstantClass, class TypeClass>
343 struct ConvertType {
344   static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
345     llvm_unreachable("This type cannot be converted!");
346   }
347 };
348
349 template<>
350 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
351   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
352       unsigned short pred = 0) {
353     if (Instruction::isCast(V.opcode))
354       return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
355     if ((V.opcode >= Instruction::BinaryOpsBegin &&
356          V.opcode < Instruction::BinaryOpsEnd))
357       return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
358     if (V.opcode == Instruction::Select)
359       return new SelectConstantExpr(V.operands[0], V.operands[1], 
360                                     V.operands[2]);
361     if (V.opcode == Instruction::ExtractElement)
362       return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
363     if (V.opcode == Instruction::InsertElement)
364       return new InsertElementConstantExpr(V.operands[0], V.operands[1],
365                                            V.operands[2]);
366     if (V.opcode == Instruction::ShuffleVector)
367       return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
368                                            V.operands[2]);
369     if (V.opcode == Instruction::InsertValue)
370       return new InsertValueConstantExpr(V.operands[0], V.operands[1],
371                                          V.indices, Ty);
372     if (V.opcode == Instruction::ExtractValue)
373       return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
374     if (V.opcode == Instruction::GetElementPtr) {
375       std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
376       return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
377     }
378
379     // The compare instructions are weird. We have to encode the predicate
380     // value and it is combined with the instruction opcode by multiplying
381     // the opcode by one hundred. We must decode this to get the predicate.
382     if (V.opcode == Instruction::ICmp)
383       return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
384                                      V.operands[0], V.operands[1]);
385     if (V.opcode == Instruction::FCmp) 
386       return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
387                                      V.operands[0], V.operands[1]);
388     llvm_unreachable("Invalid ConstantExpr!");
389     return 0;
390   }
391 };
392
393 template<>
394 struct ConvertType<ConstantExpr, Type> {
395   static void convert(ConstantExpr *OldC, const Type *NewTy) {
396     Constant *New;
397     switch (OldC->getOpcode()) {
398     case Instruction::Trunc:
399     case Instruction::ZExt:
400     case Instruction::SExt:
401     case Instruction::FPTrunc:
402     case Instruction::FPExt:
403     case Instruction::UIToFP:
404     case Instruction::SIToFP:
405     case Instruction::FPToUI:
406     case Instruction::FPToSI:
407     case Instruction::PtrToInt:
408     case Instruction::IntToPtr:
409     case Instruction::BitCast:
410       New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
411                                   NewTy);
412       break;
413     case Instruction::Select:
414       New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
415                                       OldC->getOperand(1),
416                                       OldC->getOperand(2));
417       break;
418     default:
419       assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
420              OldC->getOpcode() <  Instruction::BinaryOpsEnd);
421       New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
422                                 OldC->getOperand(1));
423       break;
424     case Instruction::GetElementPtr:
425       // Make everyone now use a constant of the new type...
426       std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
427       New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
428                                              &Idx[0], Idx.size());
429       break;
430     }
431
432     assert(New != OldC && "Didn't replace constant??");
433     OldC->uncheckedReplaceAllUsesWith(New);
434     OldC->destroyConstant();    // This constant is now dead, destroy it.
435   }
436 };
437
438 // ConstantAggregateZero does not take extra "value" argument...
439 template<class ValType>
440 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
441   static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
442     return new ConstantAggregateZero(Ty);
443   }
444 };
445
446 template<>
447 struct ConstantCreator<MDNode, Type, std::vector<Value*> > {
448   static MDNode *create(const Type* Ty, const std::vector<Value*> &V) {
449     return new MDNode(&V[0], V.size());
450   }
451 };
452
453 template<>
454 struct ConvertType<ConstantVector, VectorType> {
455   static void convert(ConstantVector *OldC, const VectorType *NewTy) {
456     // Make everyone now use a constant of the new type...
457     std::vector<Constant*> C;
458     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
459       C.push_back(cast<Constant>(OldC->getOperand(i)));
460     Constant *New = ConstantVector::get(NewTy, C);
461     assert(New != OldC && "Didn't replace constant??");
462     OldC->uncheckedReplaceAllUsesWith(New);
463     OldC->destroyConstant();    // This constant is now dead, destroy it.
464   }
465 };
466
467 template<>
468 struct ConvertType<ConstantAggregateZero, Type> {
469   static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
470     // Make everyone now use a constant of the new type...
471     Constant *New = ConstantAggregateZero::get(NewTy);
472     assert(New != OldC && "Didn't replace constant??");
473     OldC->uncheckedReplaceAllUsesWith(New);
474     OldC->destroyConstant();     // This constant is now dead, destroy it.
475   }
476 };
477
478 template<>
479 struct ConvertType<ConstantArray, ArrayType> {
480   static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
481     // Make everyone now use a constant of the new type...
482     std::vector<Constant*> C;
483     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
484       C.push_back(cast<Constant>(OldC->getOperand(i)));
485     Constant *New = ConstantArray::get(NewTy, C);
486     assert(New != OldC && "Didn't replace constant??");
487     OldC->uncheckedReplaceAllUsesWith(New);
488     OldC->destroyConstant();    // This constant is now dead, destroy it.
489   }
490 };
491
492 template<>
493 struct ConvertType<ConstantStruct, StructType> {
494   static void convert(ConstantStruct *OldC, const StructType *NewTy) {
495     // Make everyone now use a constant of the new type...
496     std::vector<Constant*> C;
497     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
498       C.push_back(cast<Constant>(OldC->getOperand(i)));
499     Constant *New = ConstantStruct::get(NewTy, C);
500     assert(New != OldC && "Didn't replace constant??");
501
502     OldC->uncheckedReplaceAllUsesWith(New);
503     OldC->destroyConstant();    // This constant is now dead, destroy it.
504   }
505 };
506
507 // ConstantPointerNull does not take extra "value" argument...
508 template<class ValType>
509 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
510   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
511     return new ConstantPointerNull(Ty);
512   }
513 };
514
515 template<>
516 struct ConvertType<ConstantPointerNull, PointerType> {
517   static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
518     // Make everyone now use a constant of the new type...
519     Constant *New = ConstantPointerNull::get(NewTy);
520     assert(New != OldC && "Didn't replace constant??");
521     OldC->uncheckedReplaceAllUsesWith(New);
522     OldC->destroyConstant();     // This constant is now dead, destroy it.
523   }
524 };
525
526 // UndefValue does not take extra "value" argument...
527 template<class ValType>
528 struct ConstantCreator<UndefValue, Type, ValType> {
529   static UndefValue *create(const Type *Ty, const ValType &V) {
530     return new UndefValue(Ty);
531   }
532 };
533
534 template<>
535 struct ConvertType<UndefValue, Type> {
536   static void convert(UndefValue *OldC, const Type *NewTy) {
537     // Make everyone now use a constant of the new type.
538     Constant *New = UndefValue::get(NewTy);
539     assert(New != OldC && "Didn't replace constant??");
540     OldC->uncheckedReplaceAllUsesWith(New);
541     OldC->destroyConstant();     // This constant is now dead, destroy it.
542   }
543 };
544
545 template<class ValType, class TypeClass, class ConstantClass,
546          bool HasLargeKey = false /*true for arrays and structs*/ >
547 class ValueMap : public AbstractTypeUser {
548 public:
549   typedef std::pair<const Type*, ValType> MapKey;
550   typedef std::map<MapKey, Value *> MapTy;
551   typedef std::map<Value*, typename MapTy::iterator> InverseMapTy;
552   typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
553 private:
554   /// Map - This is the main map from the element descriptor to the Constants.
555   /// This is the primary way we avoid creating two of the same shape
556   /// constant.
557   MapTy Map;
558     
559   /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
560   /// from the constants to their element in Map.  This is important for
561   /// removal of constants from the array, which would otherwise have to scan
562   /// through the map with very large keys.
563   InverseMapTy InverseMap;
564
565   /// AbstractTypeMap - Map for abstract type constants.
566   ///
567   AbstractTypeMapTy AbstractTypeMap;
568     
569   /// ValueMapLock - Mutex for this map.
570   sys::SmartMutex<true> ValueMapLock;
571
572 public:
573   // NOTE: This function is not locked.  It is the caller's responsibility
574   // to enforce proper synchronization.
575   typename MapTy::iterator map_end() { return Map.end(); }
576     
577   /// InsertOrGetItem - Return an iterator for the specified element.
578   /// If the element exists in the map, the returned iterator points to the
579   /// entry and Exists=true.  If not, the iterator points to the newly
580   /// inserted entry and returns Exists=false.  Newly inserted entries have
581   /// I->second == 0, and should be filled in.
582   /// NOTE: This function is not locked.  It is the caller's responsibility
583   // to enforce proper synchronization.
584   typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
585                                  &InsertVal,
586                                  bool &Exists) {
587     std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
588     Exists = !IP.second;
589     return IP.first;
590   }
591     
592 private:
593   typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
594     if (HasLargeKey) {
595       typename InverseMapTy::iterator IMI = InverseMap.find(CP);
596       assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
597              IMI->second->second == CP &&
598              "InverseMap corrupt!");
599       return IMI->second;
600     }
601       
602     typename MapTy::iterator I =
603       Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
604                       getValType(CP)));
605     if (I == Map.end() || I->second != CP) {
606       // FIXME: This should not use a linear scan.  If this gets to be a
607       // performance problem, someone should look at this.
608       for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
609         /* empty */;
610     }
611     return I;
612   }
613     
614   ConstantClass* Create(const TypeClass *Ty, const ValType &V,
615                         typename MapTy::iterator I) {
616     ConstantClass* Result =
617       ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
618
619     assert(Result->getType() == Ty && "Type specified is not correct!");
620     I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
621
622     if (HasLargeKey)  // Remember the reverse mapping if needed.
623       InverseMap.insert(std::make_pair(Result, I));
624
625     // If the type of the constant is abstract, make sure that an entry
626     // exists for it in the AbstractTypeMap.
627     if (Ty->isAbstract()) {
628       typename AbstractTypeMapTy::iterator TI = 
629                                                AbstractTypeMap.find(Ty);
630
631       if (TI == AbstractTypeMap.end()) {
632         // Add ourselves to the ATU list of the type.
633         cast<DerivedType>(Ty)->addAbstractTypeUser(this);
634
635         AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
636       }
637     }
638       
639     return Result;
640   }
641 public:
642     
643   /// getOrCreate - Return the specified constant from the map, creating it if
644   /// necessary.
645   ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
646     sys::SmartScopedLock<true> Lock(ValueMapLock);
647     MapKey Lookup(Ty, V);
648     ConstantClass* Result = 0;
649     
650     typename MapTy::iterator I = Map.find(Lookup);
651     // Is it in the map?  
652     if (I != Map.end())
653       Result = static_cast<ConstantClass *>(I->second);
654         
655     if (!Result) {
656       // If no preexisting value, create one now...
657       Result = Create(Ty, V, I);
658     }
659         
660     return Result;
661   }
662
663   void remove(ConstantClass *CP) {
664     sys::SmartScopedLock<true> Lock(ValueMapLock);
665     typename MapTy::iterator I = FindExistingElement(CP);
666     assert(I != Map.end() && "Constant not found in constant table!");
667     assert(I->second == CP && "Didn't find correct element?");
668
669     if (HasLargeKey)  // Remember the reverse mapping if needed.
670       InverseMap.erase(CP);
671       
672     // Now that we found the entry, make sure this isn't the entry that
673     // the AbstractTypeMap points to.
674     const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
675     if (Ty->isAbstract()) {
676       assert(AbstractTypeMap.count(Ty) &&
677              "Abstract type not in AbstractTypeMap?");
678       typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
679       if (ATMEntryIt == I) {
680         // Yes, we are removing the representative entry for this type.
681         // See if there are any other entries of the same type.
682         typename MapTy::iterator TmpIt = ATMEntryIt;
683
684         // First check the entry before this one...
685         if (TmpIt != Map.begin()) {
686           --TmpIt;
687           if (TmpIt->first.first != Ty) // Not the same type, move back...
688             ++TmpIt;
689         }
690
691         // If we didn't find the same type, try to move forward...
692         if (TmpIt == ATMEntryIt) {
693           ++TmpIt;
694           if (TmpIt == Map.end() || TmpIt->first.first != Ty)
695             --TmpIt;   // No entry afterwards with the same type
696         }
697
698         // If there is another entry in the map of the same abstract type,
699         // update the AbstractTypeMap entry now.
700         if (TmpIt != ATMEntryIt) {
701           ATMEntryIt = TmpIt;
702         } else {
703           // Otherwise, we are removing the last instance of this type
704           // from the table.  Remove from the ATM, and from user list.
705           cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
706           AbstractTypeMap.erase(Ty);
707         }
708       }
709     }
710
711     Map.erase(I);
712   }
713
714     
715   /// MoveConstantToNewSlot - If we are about to change C to be the element
716   /// specified by I, update our internal data structures to reflect this
717   /// fact.
718   /// NOTE: This function is not locked. It is the responsibility of the
719   /// caller to enforce proper synchronization if using this method.
720   void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
721     // First, remove the old location of the specified constant in the map.
722     typename MapTy::iterator OldI = FindExistingElement(C);
723     assert(OldI != Map.end() && "Constant not found in constant table!");
724     assert(OldI->second == C && "Didn't find correct element?");
725       
726     // If this constant is the representative element for its abstract type,
727     // update the AbstractTypeMap so that the representative element is I.
728     if (C->getType()->isAbstract()) {
729       typename AbstractTypeMapTy::iterator ATI =
730           AbstractTypeMap.find(C->getType());
731       assert(ATI != AbstractTypeMap.end() &&
732              "Abstract type not in AbstractTypeMap?");
733       if (ATI->second == OldI)
734         ATI->second = I;
735     }
736       
737     // Remove the old entry from the map.
738     Map.erase(OldI);
739     
740     // Update the inverse map so that we know that this constant is now
741     // located at descriptor I.
742     if (HasLargeKey) {
743       assert(I->second == C && "Bad inversemap entry!");
744       InverseMap[C] = I;
745     }
746   }
747     
748   void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
749     sys::SmartScopedLock<true> Lock(ValueMapLock);
750     typename AbstractTypeMapTy::iterator I =
751       AbstractTypeMap.find(cast<Type>(OldTy));
752
753     assert(I != AbstractTypeMap.end() &&
754            "Abstract type not in AbstractTypeMap?");
755
756     // Convert a constant at a time until the last one is gone.  The last one
757     // leaving will remove() itself, causing the AbstractTypeMapEntry to be
758     // eliminated eventually.
759     do {
760       ConvertType<ConstantClass, TypeClass>::convert(
761                               static_cast<ConstantClass *>(I->second->second),
762                                               cast<TypeClass>(NewTy));
763
764       I = AbstractTypeMap.find(cast<Type>(OldTy));
765     } while (I != AbstractTypeMap.end());
766   }
767
768   // If the type became concrete without being refined to any other existing
769   // type, we just remove ourselves from the ATU list.
770   void typeBecameConcrete(const DerivedType *AbsTy) {
771     AbsTy->removeAbstractTypeUser(this);
772   }
773
774   void dump() const {
775     DOUT << "Constant.cpp: ValueMap\n";
776   }
777 };
778
779 }
780
781 #endif