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