Eliminate ConstantBool::True and ConstantBool::False. Instead, provide
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include <algorithm>
26 #include <iostream>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 //                              Constant Class
31 //===----------------------------------------------------------------------===//
32
33 void Constant::destroyConstantImpl() {
34   // When a Constant is destroyed, there may be lingering
35   // references to the constant by other constants in the constant pool.  These
36   // constants are implicitly dependent on the module that is being deleted,
37   // but they don't know that.  Because we only find out when the CPV is
38   // deleted, we must now notify all of our users (that should only be
39   // Constants) that they are, in fact, invalid now and should be deleted.
40   //
41   while (!use_empty()) {
42     Value *V = use_back();
43 #ifndef NDEBUG      // Only in -g mode...
44     if (!isa<Constant>(V))
45       std::cerr << "While deleting: " << *this
46                 << "\n\nUse still stuck around after Def is destroyed: "
47                 << *V << "\n\n";
48 #endif
49     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50     Constant *CV = cast<Constant>(V);
51     CV->destroyConstant();
52
53     // The constant should remove itself from our use list...
54     assert((use_empty() || use_back() != V) && "Constant not removed!");
55   }
56
57   // Value has no outstanding references it is safe to delete it now...
58   delete this;
59 }
60
61 // Static constructor to create a '0' constant of arbitrary type...
62 Constant *Constant::getNullValue(const Type *Ty) {
63   switch (Ty->getTypeID()) {
64   case Type::BoolTyID: {
65     static Constant *NullBool = ConstantBool::get(false);
66     return NullBool;
67   }
68   case Type::SByteTyID: {
69     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
70     return NullSByte;
71   }
72   case Type::UByteTyID: {
73     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
74     return NullUByte;
75   }
76   case Type::ShortTyID: {
77     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
78     return NullShort;
79   }
80   case Type::UShortTyID: {
81     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
82     return NullUShort;
83   }
84   case Type::IntTyID: {
85     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
86     return NullInt;
87   }
88   case Type::UIntTyID: {
89     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
90     return NullUInt;
91   }
92   case Type::LongTyID: {
93     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
94     return NullLong;
95   }
96   case Type::ULongTyID: {
97     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
98     return NullULong;
99   }
100
101   case Type::FloatTyID: {
102     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
103     return NullFloat;
104   }
105   case Type::DoubleTyID: {
106     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
107     return NullDouble;
108   }
109
110   case Type::PointerTyID:
111     return ConstantPointerNull::get(cast<PointerType>(Ty));
112
113   case Type::StructTyID:
114   case Type::ArrayTyID:
115   case Type::PackedTyID:
116     return ConstantAggregateZero::get(Ty);
117   default:
118     // Function, Label, or Opaque type?
119     assert(!"Cannot create a null constant of that type!");
120     return 0;
121   }
122 }
123
124 // Static constructor to create the maximum constant of an integral type...
125 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
126   switch (Ty->getTypeID()) {
127   case Type::BoolTyID:   return ConstantBool::getTrue();
128   case Type::SByteTyID:
129   case Type::ShortTyID:
130   case Type::IntTyID:
131   case Type::LongTyID: {
132     // Calculate 011111111111111...
133     unsigned TypeBits = Ty->getPrimitiveSize()*8;
134     int64_t Val = INT64_MAX;             // All ones
135     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
136     return ConstantSInt::get(Ty, Val);
137   }
138
139   case Type::UByteTyID:
140   case Type::UShortTyID:
141   case Type::UIntTyID:
142   case Type::ULongTyID:  return getAllOnesValue(Ty);
143
144   default: return 0;
145   }
146 }
147
148 // Static constructor to create the minimum constant for an integral type...
149 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
150   switch (Ty->getTypeID()) {
151   case Type::BoolTyID:   return ConstantBool::getFalse();
152   case Type::SByteTyID:
153   case Type::ShortTyID:
154   case Type::IntTyID:
155   case Type::LongTyID: {
156      // Calculate 1111111111000000000000
157      unsigned TypeBits = Ty->getPrimitiveSize()*8;
158      int64_t Val = -1;                    // All ones
159      Val <<= TypeBits-1;                  // Shift over to the right spot
160      return ConstantSInt::get(Ty, Val);
161   }
162
163   case Type::UByteTyID:
164   case Type::UShortTyID:
165   case Type::UIntTyID:
166   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
167
168   default: return 0;
169   }
170 }
171
172 // Static constructor to create an integral constant with all bits set
173 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
174   switch (Ty->getTypeID()) {
175   case Type::BoolTyID:   return ConstantBool::getTrue();
176   case Type::SByteTyID:
177   case Type::ShortTyID:
178   case Type::IntTyID:
179   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
180
181   case Type::UByteTyID:
182   case Type::UShortTyID:
183   case Type::UIntTyID:
184   case Type::ULongTyID: {
185     // Calculate ~0 of the right type...
186     unsigned TypeBits = Ty->getPrimitiveSize()*8;
187     uint64_t Val = ~0ULL;                // All ones
188     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
189     return ConstantUInt::get(Ty, Val);
190   }
191   default: return 0;
192   }
193 }
194
195 bool ConstantUInt::isAllOnesValue() const {
196   unsigned TypeBits = getType()->getPrimitiveSize()*8;
197   uint64_t Val = ~0ULL;                // All ones
198   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
199   return getValue() == Val;
200 }
201
202
203 //===----------------------------------------------------------------------===//
204 //                            ConstantXXX Classes
205 //===----------------------------------------------------------------------===//
206
207 //===----------------------------------------------------------------------===//
208 //                             Normal Constructors
209
210 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
211   : Constant(Ty, VT, 0, 0) {
212     Val.Unsigned = V;
213 }
214
215 ConstantBool::ConstantBool(bool V) 
216   : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
217 }
218
219 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
220   : ConstantIntegral(Ty, VT, V) {
221 }
222
223 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
224   : ConstantInt(Ty, ConstantSIntVal, V) {
225   assert(Ty->isInteger() && Ty->isSigned() &&
226          "Illegal type for signed integer constant!");
227   assert(isValueValidForType(Ty, V) && "Value too large for type!");
228 }
229
230 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
231   : ConstantInt(Ty, ConstantUIntVal, V) {
232   assert(Ty->isInteger() && Ty->isUnsigned() &&
233          "Illegal type for unsigned integer constant!");
234   assert(isValueValidForType(Ty, V) && "Value too large for type!");
235 }
236
237 ConstantFP::ConstantFP(const Type *Ty, double V)
238   : Constant(Ty, ConstantFPVal, 0, 0) {
239   assert(isValueValidForType(Ty, V) && "Value too large for type!");
240   Val = V;
241 }
242
243 ConstantArray::ConstantArray(const ArrayType *T,
244                              const std::vector<Constant*> &V)
245   : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
246   assert(V.size() == T->getNumElements() &&
247          "Invalid initializer vector for constant array");
248   Use *OL = OperandList;
249   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
250        I != E; ++I, ++OL) {
251     Constant *C = *I;
252     assert((C->getType() == T->getElementType() ||
253             (T->isAbstract() &&
254              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
255            "Initializer for array element doesn't match array element type!");
256     OL->init(C, this);
257   }
258 }
259
260 ConstantArray::~ConstantArray() {
261   delete [] OperandList;
262 }
263
264 ConstantStruct::ConstantStruct(const StructType *T,
265                                const std::vector<Constant*> &V)
266   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
267   assert(V.size() == T->getNumElements() &&
268          "Invalid initializer vector for constant structure");
269   Use *OL = OperandList;
270   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
271        I != E; ++I, ++OL) {
272     Constant *C = *I;
273     assert((C->getType() == T->getElementType(I-V.begin()) ||
274             ((T->getElementType(I-V.begin())->isAbstract() ||
275               C->getType()->isAbstract()) &&
276              T->getElementType(I-V.begin())->getTypeID() == 
277                    C->getType()->getTypeID())) &&
278            "Initializer for struct element doesn't match struct element type!");
279     OL->init(C, this);
280   }
281 }
282
283 ConstantStruct::~ConstantStruct() {
284   delete [] OperandList;
285 }
286
287
288 ConstantPacked::ConstantPacked(const PackedType *T,
289                                const std::vector<Constant*> &V)
290   : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
291   Use *OL = OperandList;
292     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
293          I != E; ++I, ++OL) {
294       Constant *C = *I;
295       assert((C->getType() == T->getElementType() ||
296             (T->isAbstract() &&
297              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
298            "Initializer for packed element doesn't match packed element type!");
299     OL->init(C, this);
300   }
301 }
302
303 ConstantPacked::~ConstantPacked() {
304   delete [] OperandList;
305 }
306
307 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
308 /// behind the scenes to implement unary constant exprs.
309 namespace {
310 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
311   Use Op;
312 public:
313   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
314     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
315 };
316 }
317
318 static bool isSetCC(unsigned Opcode) {
319   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
320          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
321          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
322 }
323
324 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
325 /// behind the scenes to implement binary constant exprs.
326 namespace {
327 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
328   Use Ops[2];
329 public:
330   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
331     : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
332                    Opcode, Ops, 2) {
333     Ops[0].init(C1, this);
334     Ops[1].init(C2, this);
335   }
336 };
337 }
338
339 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
340 /// behind the scenes to implement select constant exprs.
341 namespace {
342 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
343   Use Ops[3];
344 public:
345   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
346     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
347     Ops[0].init(C1, this);
348     Ops[1].init(C2, this);
349     Ops[2].init(C3, this);
350   }
351 };
352 }
353
354 /// ExtractElementConstantExpr - This class is private to
355 /// Constants.cpp, and is used behind the scenes to implement
356 /// extractelement constant exprs.
357 namespace {
358 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
359   Use Ops[2];
360 public:
361   ExtractElementConstantExpr(Constant *C1, Constant *C2)
362     : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(), 
363                    Instruction::ExtractElement, Ops, 2) {
364     Ops[0].init(C1, this);
365     Ops[1].init(C2, this);
366   }
367 };
368 }
369
370 /// InsertElementConstantExpr - This class is private to
371 /// Constants.cpp, and is used behind the scenes to implement
372 /// insertelement constant exprs.
373 namespace {
374 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
375   Use Ops[3];
376 public:
377   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
378     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
379                    Ops, 3) {
380     Ops[0].init(C1, this);
381     Ops[1].init(C2, this);
382     Ops[2].init(C3, this);
383   }
384 };
385 }
386
387 /// ShuffleVectorConstantExpr - This class is private to
388 /// Constants.cpp, and is used behind the scenes to implement
389 /// shufflevector constant exprs.
390 namespace {
391 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
392   Use Ops[3];
393 public:
394   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
395   : ConstantExpr(C1->getType(), Instruction::ShuffleVector, 
396                  Ops, 3) {
397     Ops[0].init(C1, this);
398     Ops[1].init(C2, this);
399     Ops[2].init(C3, this);
400   }
401 };
402 }
403
404 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
405 /// used behind the scenes to implement getelementpr constant exprs.
406 namespace {
407 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
408   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
409                             const Type *DestTy)
410     : ConstantExpr(DestTy, Instruction::GetElementPtr,
411                    new Use[IdxList.size()+1], IdxList.size()+1) {
412     OperandList[0].init(C, this);
413     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
414       OperandList[i+1].init(IdxList[i], this);
415   }
416   ~GetElementPtrConstantExpr() {
417     delete [] OperandList;
418   }
419 };
420 }
421
422 /// ConstantExpr::get* - Return some common constants without having to
423 /// specify the full Instruction::OPCODE identifier.
424 ///
425 Constant *ConstantExpr::getNeg(Constant *C) {
426   if (!C->getType()->isFloatingPoint())
427     return get(Instruction::Sub, getNullValue(C->getType()), C);
428   else
429     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
430 }
431 Constant *ConstantExpr::getNot(Constant *C) {
432   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
433   return get(Instruction::Xor, C,
434              ConstantIntegral::getAllOnesValue(C->getType()));
435 }
436 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
437   return get(Instruction::Add, C1, C2);
438 }
439 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
440   return get(Instruction::Sub, C1, C2);
441 }
442 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
443   return get(Instruction::Mul, C1, C2);
444 }
445 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
446   return get(Instruction::Div, C1, C2);
447 }
448 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
449   return get(Instruction::Rem, C1, C2);
450 }
451 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
452   return get(Instruction::And, C1, C2);
453 }
454 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
455   return get(Instruction::Or, C1, C2);
456 }
457 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
458   return get(Instruction::Xor, C1, C2);
459 }
460 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
461   return get(Instruction::SetEQ, C1, C2);
462 }
463 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
464   return get(Instruction::SetNE, C1, C2);
465 }
466 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
467   return get(Instruction::SetLT, C1, C2);
468 }
469 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
470   return get(Instruction::SetGT, C1, C2);
471 }
472 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
473   return get(Instruction::SetLE, C1, C2);
474 }
475 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
476   return get(Instruction::SetGE, C1, C2);
477 }
478 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
479   return get(Instruction::Shl, C1, C2);
480 }
481 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
482   return get(Instruction::Shr, C1, C2);
483 }
484
485 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
486   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
487   return getCast(getShr(getCast(C1,
488                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
489 }
490
491 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
492   if (C1->getType()->isSigned()) return getShr(C1, C2);
493   return getCast(getShr(getCast(C1,
494                         C1->getType()->getSignedVersion()), C2), C1->getType());
495 }
496
497 /// getWithOperandReplaced - Return a constant expression identical to this
498 /// one, but with the specified operand set to the specified value.
499 Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
500                                                Constant *Op) const {
501   assert(OpNo < getNumOperands() && "Operand num is out of range!");
502   assert(Op->getType() == getOperand(OpNo)->getType() &&
503          "Replacing operand with value of different type!");
504   if (getOperand(OpNo) == Op)
505     return const_cast<ConstantExpr*>(this);
506   
507   Constant *Op0, *Op1, *Op2;
508   switch (getOpcode()) {
509   case Instruction::Cast:
510     return ConstantExpr::getCast(Op, getType());
511   case Instruction::Select:
512     Op0 = (OpNo == 0) ? Op : getOperand(0);
513     Op1 = (OpNo == 1) ? Op : getOperand(1);
514     Op2 = (OpNo == 2) ? Op : getOperand(2);
515     return ConstantExpr::getSelect(Op0, Op1, Op2);
516   case Instruction::InsertElement:
517     Op0 = (OpNo == 0) ? Op : getOperand(0);
518     Op1 = (OpNo == 1) ? Op : getOperand(1);
519     Op2 = (OpNo == 2) ? Op : getOperand(2);
520     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
521   case Instruction::ExtractElement:
522     Op0 = (OpNo == 0) ? Op : getOperand(0);
523     Op1 = (OpNo == 1) ? Op : getOperand(1);
524     return ConstantExpr::getExtractElement(Op0, Op1);
525   case Instruction::ShuffleVector:
526     Op0 = (OpNo == 0) ? Op : getOperand(0);
527     Op1 = (OpNo == 1) ? Op : getOperand(1);
528     Op2 = (OpNo == 2) ? Op : getOperand(2);
529     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
530   case Instruction::GetElementPtr: {
531     std::vector<Constant*> Ops;
532     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
533       Ops.push_back(getOperand(i));
534     if (OpNo == 0)
535       return ConstantExpr::getGetElementPtr(Op, Ops);
536     Ops[OpNo-1] = Op;
537     return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
538   }
539   default:
540     assert(getNumOperands() == 2 && "Must be binary operator?");
541     Op0 = (OpNo == 0) ? Op : getOperand(0);
542     Op1 = (OpNo == 1) ? Op : getOperand(1);
543     return ConstantExpr::get(getOpcode(), Op0, Op1);
544   }
545 }
546
547 /// getWithOperands - This returns the current constant expression with the
548 /// operands replaced with the specified values.  The specified operands must
549 /// match count and type with the existing ones.
550 Constant *ConstantExpr::
551 getWithOperands(const std::vector<Constant*> &Ops) const {
552   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
553   bool AnyChange = false;
554   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
555     assert(Ops[i]->getType() == getOperand(i)->getType() &&
556            "Operand type mismatch!");
557     AnyChange |= Ops[i] != getOperand(i);
558   }
559   if (!AnyChange)  // No operands changed, return self.
560     return const_cast<ConstantExpr*>(this);
561
562   switch (getOpcode()) {
563   case Instruction::Cast:
564     return ConstantExpr::getCast(Ops[0], getType());
565   case Instruction::Select:
566     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
567   case Instruction::InsertElement:
568     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
569   case Instruction::ExtractElement:
570     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
571   case Instruction::ShuffleVector:
572     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
573   case Instruction::GetElementPtr: {
574     std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
575     return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
576   }
577   default:
578     assert(getNumOperands() == 2 && "Must be binary operator?");
579     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
580   }
581 }
582
583
584 //===----------------------------------------------------------------------===//
585 //                      isValueValidForType implementations
586
587 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
588   switch (Ty->getTypeID()) {
589   default:
590     return false;         // These can't be represented as integers!!!
591     // Signed types...
592   case Type::SByteTyID:
593     return (Val <= INT8_MAX && Val >= INT8_MIN);
594   case Type::ShortTyID:
595     return (Val <= INT16_MAX && Val >= INT16_MIN);
596   case Type::IntTyID:
597     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
598   case Type::LongTyID:
599     return true;          // This is the largest type...
600   }
601 }
602
603 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
604   switch (Ty->getTypeID()) {
605   default:
606     return false;         // These can't be represented as integers!!!
607
608     // Unsigned types...
609   case Type::UByteTyID:
610     return (Val <= UINT8_MAX);
611   case Type::UShortTyID:
612     return (Val <= UINT16_MAX);
613   case Type::UIntTyID:
614     return (Val <= UINT32_MAX);
615   case Type::ULongTyID:
616     return true;          // This is the largest type...
617   }
618 }
619
620 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
621   switch (Ty->getTypeID()) {
622   default:
623     return false;         // These can't be represented as floating point!
624
625     // TODO: Figure out how to test if a double can be cast to a float!
626   case Type::FloatTyID:
627   case Type::DoubleTyID:
628     return true;          // This is the largest type...
629   }
630 }
631
632 //===----------------------------------------------------------------------===//
633 //                      Factory Function Implementation
634
635 // ConstantCreator - A class that is used to create constants by
636 // ValueMap*.  This class should be partially specialized if there is
637 // something strange that needs to be done to interface to the ctor for the
638 // constant.
639 //
640 namespace llvm {
641   template<class ConstantClass, class TypeClass, class ValType>
642   struct VISIBILITY_HIDDEN ConstantCreator {
643     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
644       return new ConstantClass(Ty, V);
645     }
646   };
647
648   template<class ConstantClass, class TypeClass>
649   struct VISIBILITY_HIDDEN ConvertConstantType {
650     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
651       assert(0 && "This type cannot be converted!\n");
652       abort();
653     }
654   };
655
656   template<class ValType, class TypeClass, class ConstantClass,
657            bool HasLargeKey = false  /*true for arrays and structs*/ >
658   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
659   public:
660     typedef std::pair<const Type*, ValType> MapKey;
661     typedef std::map<MapKey, Constant *> MapTy;
662     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
663     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
664   private:
665     /// Map - This is the main map from the element descriptor to the Constants.
666     /// This is the primary way we avoid creating two of the same shape
667     /// constant.
668     MapTy Map;
669     
670     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
671     /// from the constants to their element in Map.  This is important for
672     /// removal of constants from the array, which would otherwise have to scan
673     /// through the map with very large keys.
674     InverseMapTy InverseMap;
675
676     /// AbstractTypeMap - Map for abstract type constants.
677     ///
678     AbstractTypeMapTy AbstractTypeMap;
679
680   private:
681     void clear(std::vector<Constant *> &Constants) {
682       for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
683         Constants.push_back(I->second);
684       Map.clear();
685       AbstractTypeMap.clear();
686       InverseMap.clear();
687     }
688
689   public:
690     typename MapTy::iterator map_end() { return Map.end(); }
691     
692     /// InsertOrGetItem - Return an iterator for the specified element.
693     /// If the element exists in the map, the returned iterator points to the
694     /// entry and Exists=true.  If not, the iterator points to the newly
695     /// inserted entry and returns Exists=false.  Newly inserted entries have
696     /// I->second == 0, and should be filled in.
697     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
698                                    &InsertVal,
699                                    bool &Exists) {
700       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
701       Exists = !IP.second;
702       return IP.first;
703     }
704     
705 private:
706     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
707       if (HasLargeKey) {
708         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
709         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
710                IMI->second->second == CP &&
711                "InverseMap corrupt!");
712         return IMI->second;
713       }
714       
715       typename MapTy::iterator I =
716         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
717       if (I == Map.end() || I->second != CP) {
718         // FIXME: This should not use a linear scan.  If this gets to be a
719         // performance problem, someone should look at this.
720         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
721           /* empty */;
722       }
723       return I;
724     }
725 public:
726     
727     /// getOrCreate - Return the specified constant from the map, creating it if
728     /// necessary.
729     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
730       MapKey Lookup(Ty, V);
731       typename MapTy::iterator I = Map.lower_bound(Lookup);
732       if (I != Map.end() && I->first == Lookup)
733         return static_cast<ConstantClass *>(I->second);  // Is it in the map?
734
735       // If no preexisting value, create one now...
736       ConstantClass *Result =
737         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
738
739       /// FIXME: why does this assert fail when loading 176.gcc?
740       //assert(Result->getType() == Ty && "Type specified is not correct!");
741       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
742
743       if (HasLargeKey)  // Remember the reverse mapping if needed.
744         InverseMap.insert(std::make_pair(Result, I));
745       
746       // If the type of the constant is abstract, make sure that an entry exists
747       // for it in the AbstractTypeMap.
748       if (Ty->isAbstract()) {
749         typename AbstractTypeMapTy::iterator TI =
750           AbstractTypeMap.lower_bound(Ty);
751
752         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
753           // Add ourselves to the ATU list of the type.
754           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
755
756           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
757         }
758       }
759       return Result;
760     }
761
762     void remove(ConstantClass *CP) {
763       typename MapTy::iterator I = FindExistingElement(CP);
764       assert(I != Map.end() && "Constant not found in constant table!");
765       assert(I->second == CP && "Didn't find correct element?");
766
767       if (HasLargeKey)  // Remember the reverse mapping if needed.
768         InverseMap.erase(CP);
769       
770       // Now that we found the entry, make sure this isn't the entry that
771       // the AbstractTypeMap points to.
772       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
773       if (Ty->isAbstract()) {
774         assert(AbstractTypeMap.count(Ty) &&
775                "Abstract type not in AbstractTypeMap?");
776         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
777         if (ATMEntryIt == I) {
778           // Yes, we are removing the representative entry for this type.
779           // See if there are any other entries of the same type.
780           typename MapTy::iterator TmpIt = ATMEntryIt;
781
782           // First check the entry before this one...
783           if (TmpIt != Map.begin()) {
784             --TmpIt;
785             if (TmpIt->first.first != Ty) // Not the same type, move back...
786               ++TmpIt;
787           }
788
789           // If we didn't find the same type, try to move forward...
790           if (TmpIt == ATMEntryIt) {
791             ++TmpIt;
792             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
793               --TmpIt;   // No entry afterwards with the same type
794           }
795
796           // If there is another entry in the map of the same abstract type,
797           // update the AbstractTypeMap entry now.
798           if (TmpIt != ATMEntryIt) {
799             ATMEntryIt = TmpIt;
800           } else {
801             // Otherwise, we are removing the last instance of this type
802             // from the table.  Remove from the ATM, and from user list.
803             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
804             AbstractTypeMap.erase(Ty);
805           }
806         }
807       }
808
809       Map.erase(I);
810     }
811
812     
813     /// MoveConstantToNewSlot - If we are about to change C to be the element
814     /// specified by I, update our internal data structures to reflect this
815     /// fact.
816     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
817       // First, remove the old location of the specified constant in the map.
818       typename MapTy::iterator OldI = FindExistingElement(C);
819       assert(OldI != Map.end() && "Constant not found in constant table!");
820       assert(OldI->second == C && "Didn't find correct element?");
821       
822       // If this constant is the representative element for its abstract type,
823       // update the AbstractTypeMap so that the representative element is I.
824       if (C->getType()->isAbstract()) {
825         typename AbstractTypeMapTy::iterator ATI =
826             AbstractTypeMap.find(C->getType());
827         assert(ATI != AbstractTypeMap.end() &&
828                "Abstract type not in AbstractTypeMap?");
829         if (ATI->second == OldI)
830           ATI->second = I;
831       }
832       
833       // Remove the old entry from the map.
834       Map.erase(OldI);
835       
836       // Update the inverse map so that we know that this constant is now
837       // located at descriptor I.
838       if (HasLargeKey) {
839         assert(I->second == C && "Bad inversemap entry!");
840         InverseMap[C] = I;
841       }
842     }
843     
844     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
845       typename AbstractTypeMapTy::iterator I =
846         AbstractTypeMap.find(cast<Type>(OldTy));
847
848       assert(I != AbstractTypeMap.end() &&
849              "Abstract type not in AbstractTypeMap?");
850
851       // Convert a constant at a time until the last one is gone.  The last one
852       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
853       // eliminated eventually.
854       do {
855         ConvertConstantType<ConstantClass,
856                             TypeClass>::convert(
857                                 static_cast<ConstantClass *>(I->second->second),
858                                                 cast<TypeClass>(NewTy));
859
860         I = AbstractTypeMap.find(cast<Type>(OldTy));
861       } while (I != AbstractTypeMap.end());
862     }
863
864     // If the type became concrete without being refined to any other existing
865     // type, we just remove ourselves from the ATU list.
866     void typeBecameConcrete(const DerivedType *AbsTy) {
867       AbsTy->removeAbstractTypeUser(this);
868     }
869
870     void dump() const {
871       std::cerr << "Constant.cpp: ValueMap\n";
872     }
873   };
874 }
875
876
877 //---- ConstantBool::get*() implementation.
878
879 ConstantBool *ConstantBool::getTrue() {
880   static ConstantBool *T = 0;
881   if (T) return T;
882   return T = new ConstantBool(true);
883 }
884 ConstantBool *ConstantBool::getFalse() {
885   static ConstantBool *F = 0;
886   if (F) return F;
887   return F = new ConstantBool(false);
888 }
889
890 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
891 //
892 static ManagedStatic<ValueMap< int64_t, Type, ConstantSInt> > SIntConstants;
893 static ManagedStatic<ValueMap<uint64_t, Type, ConstantUInt> > UIntConstants;
894
895 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
896   return SIntConstants->getOrCreate(Ty, V);
897 }
898
899 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
900   return UIntConstants->getOrCreate(Ty, V);
901 }
902
903 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
904   assert(V <= 127 && "Can only be used with very small positive constants!");
905   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
906   return ConstantUInt::get(Ty, V);
907 }
908
909 //---- ConstantFP::get() implementation...
910 //
911 namespace llvm {
912   template<>
913   struct ConstantCreator<ConstantFP, Type, uint64_t> {
914     static ConstantFP *create(const Type *Ty, uint64_t V) {
915       assert(Ty == Type::DoubleTy);
916       return new ConstantFP(Ty, BitsToDouble(V));
917     }
918   };
919   template<>
920   struct ConstantCreator<ConstantFP, Type, uint32_t> {
921     static ConstantFP *create(const Type *Ty, uint32_t V) {
922       assert(Ty == Type::FloatTy);
923       return new ConstantFP(Ty, BitsToFloat(V));
924     }
925   };
926 }
927
928 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
929 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
930
931 bool ConstantFP::isNullValue() const {
932   return DoubleToBits(Val) == 0;
933 }
934
935 bool ConstantFP::isExactlyValue(double V) const {
936   return DoubleToBits(V) == DoubleToBits(Val);
937 }
938
939
940 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
941   if (Ty == Type::FloatTy) {
942     // Force the value through memory to normalize it.
943     return FloatConstants->getOrCreate(Ty, FloatToBits(V));
944   } else {
945     assert(Ty == Type::DoubleTy);
946     return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
947   }
948 }
949
950 //---- ConstantAggregateZero::get() implementation...
951 //
952 namespace llvm {
953   // ConstantAggregateZero does not take extra "value" argument...
954   template<class ValType>
955   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
956     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
957       return new ConstantAggregateZero(Ty);
958     }
959   };
960
961   template<>
962   struct ConvertConstantType<ConstantAggregateZero, Type> {
963     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
964       // Make everyone now use a constant of the new type...
965       Constant *New = ConstantAggregateZero::get(NewTy);
966       assert(New != OldC && "Didn't replace constant??");
967       OldC->uncheckedReplaceAllUsesWith(New);
968       OldC->destroyConstant();     // This constant is now dead, destroy it.
969     }
970   };
971 }
972
973 static ManagedStatic<ValueMap<char, Type, 
974                               ConstantAggregateZero> > AggZeroConstants;
975
976 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
977
978 Constant *ConstantAggregateZero::get(const Type *Ty) {
979   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
980          "Cannot create an aggregate zero of non-aggregate type!");
981   return AggZeroConstants->getOrCreate(Ty, 0);
982 }
983
984 // destroyConstant - Remove the constant from the constant table...
985 //
986 void ConstantAggregateZero::destroyConstant() {
987   AggZeroConstants->remove(this);
988   destroyConstantImpl();
989 }
990
991 //---- ConstantArray::get() implementation...
992 //
993 namespace llvm {
994   template<>
995   struct ConvertConstantType<ConstantArray, ArrayType> {
996     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
997       // Make everyone now use a constant of the new type...
998       std::vector<Constant*> C;
999       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1000         C.push_back(cast<Constant>(OldC->getOperand(i)));
1001       Constant *New = ConstantArray::get(NewTy, C);
1002       assert(New != OldC && "Didn't replace constant??");
1003       OldC->uncheckedReplaceAllUsesWith(New);
1004       OldC->destroyConstant();    // This constant is now dead, destroy it.
1005     }
1006   };
1007 }
1008
1009 static std::vector<Constant*> getValType(ConstantArray *CA) {
1010   std::vector<Constant*> Elements;
1011   Elements.reserve(CA->getNumOperands());
1012   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1013     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1014   return Elements;
1015 }
1016
1017 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1018                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1019 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1020
1021 Constant *ConstantArray::get(const ArrayType *Ty,
1022                              const std::vector<Constant*> &V) {
1023   // If this is an all-zero array, return a ConstantAggregateZero object
1024   if (!V.empty()) {
1025     Constant *C = V[0];
1026     if (!C->isNullValue())
1027       return ArrayConstants->getOrCreate(Ty, V);
1028     for (unsigned i = 1, e = V.size(); i != e; ++i)
1029       if (V[i] != C)
1030         return ArrayConstants->getOrCreate(Ty, V);
1031   }
1032   return ConstantAggregateZero::get(Ty);
1033 }
1034
1035 // destroyConstant - Remove the constant from the constant table...
1036 //
1037 void ConstantArray::destroyConstant() {
1038   ArrayConstants->remove(this);
1039   destroyConstantImpl();
1040 }
1041
1042 /// ConstantArray::get(const string&) - Return an array that is initialized to
1043 /// contain the specified string.  If length is zero then a null terminator is 
1044 /// added to the specified string so that it may be used in a natural way. 
1045 /// Otherwise, the length parameter specifies how much of the string to use 
1046 /// and it won't be null terminated.
1047 ///
1048 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1049   std::vector<Constant*> ElementVals;
1050   for (unsigned i = 0; i < Str.length(); ++i)
1051     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
1052
1053   // Add a null terminator to the string...
1054   if (AddNull) {
1055     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
1056   }
1057
1058   ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1059   return ConstantArray::get(ATy, ElementVals);
1060 }
1061
1062 /// isString - This method returns true if the array is an array of sbyte or
1063 /// ubyte, and if the elements of the array are all ConstantInt's.
1064 bool ConstantArray::isString() const {
1065   // Check the element type for sbyte or ubyte...
1066   if (getType()->getElementType() != Type::UByteTy &&
1067       getType()->getElementType() != Type::SByteTy)
1068     return false;
1069   // Check the elements to make sure they are all integers, not constant
1070   // expressions.
1071   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1072     if (!isa<ConstantInt>(getOperand(i)))
1073       return false;
1074   return true;
1075 }
1076
1077 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1078 // then this method converts the array to an std::string and returns it.
1079 // Otherwise, it asserts out.
1080 //
1081 std::string ConstantArray::getAsString() const {
1082   assert(isString() && "Not a string!");
1083   std::string Result;
1084   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1085     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
1086   return Result;
1087 }
1088
1089
1090 //---- ConstantStruct::get() implementation...
1091 //
1092
1093 namespace llvm {
1094   template<>
1095   struct ConvertConstantType<ConstantStruct, StructType> {
1096     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1097       // Make everyone now use a constant of the new type...
1098       std::vector<Constant*> C;
1099       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1100         C.push_back(cast<Constant>(OldC->getOperand(i)));
1101       Constant *New = ConstantStruct::get(NewTy, C);
1102       assert(New != OldC && "Didn't replace constant??");
1103
1104       OldC->uncheckedReplaceAllUsesWith(New);
1105       OldC->destroyConstant();    // This constant is now dead, destroy it.
1106     }
1107   };
1108 }
1109
1110 typedef ValueMap<std::vector<Constant*>, StructType,
1111                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1112 static ManagedStatic<StructConstantsTy> StructConstants;
1113
1114 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1115   std::vector<Constant*> Elements;
1116   Elements.reserve(CS->getNumOperands());
1117   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1118     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1119   return Elements;
1120 }
1121
1122 Constant *ConstantStruct::get(const StructType *Ty,
1123                               const std::vector<Constant*> &V) {
1124   // Create a ConstantAggregateZero value if all elements are zeros...
1125   for (unsigned i = 0, e = V.size(); i != e; ++i)
1126     if (!V[i]->isNullValue())
1127       return StructConstants->getOrCreate(Ty, V);
1128
1129   return ConstantAggregateZero::get(Ty);
1130 }
1131
1132 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1133   std::vector<const Type*> StructEls;
1134   StructEls.reserve(V.size());
1135   for (unsigned i = 0, e = V.size(); i != e; ++i)
1136     StructEls.push_back(V[i]->getType());
1137   return get(StructType::get(StructEls), V);
1138 }
1139
1140 // destroyConstant - Remove the constant from the constant table...
1141 //
1142 void ConstantStruct::destroyConstant() {
1143   StructConstants->remove(this);
1144   destroyConstantImpl();
1145 }
1146
1147 //---- ConstantPacked::get() implementation...
1148 //
1149 namespace llvm {
1150   template<>
1151   struct ConvertConstantType<ConstantPacked, PackedType> {
1152     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1153       // Make everyone now use a constant of the new type...
1154       std::vector<Constant*> C;
1155       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1156         C.push_back(cast<Constant>(OldC->getOperand(i)));
1157       Constant *New = ConstantPacked::get(NewTy, C);
1158       assert(New != OldC && "Didn't replace constant??");
1159       OldC->uncheckedReplaceAllUsesWith(New);
1160       OldC->destroyConstant();    // This constant is now dead, destroy it.
1161     }
1162   };
1163 }
1164
1165 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1166   std::vector<Constant*> Elements;
1167   Elements.reserve(CP->getNumOperands());
1168   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1169     Elements.push_back(CP->getOperand(i));
1170   return Elements;
1171 }
1172
1173 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1174                               ConstantPacked> > PackedConstants;
1175
1176 Constant *ConstantPacked::get(const PackedType *Ty,
1177                               const std::vector<Constant*> &V) {
1178   // If this is an all-zero packed, return a ConstantAggregateZero object
1179   if (!V.empty()) {
1180     Constant *C = V[0];
1181     if (!C->isNullValue())
1182       return PackedConstants->getOrCreate(Ty, V);
1183     for (unsigned i = 1, e = V.size(); i != e; ++i)
1184       if (V[i] != C)
1185         return PackedConstants->getOrCreate(Ty, V);
1186   }
1187   return ConstantAggregateZero::get(Ty);
1188 }
1189
1190 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1191   assert(!V.empty() && "Cannot infer type if V is empty");
1192   return get(PackedType::get(V.front()->getType(),V.size()), V);
1193 }
1194
1195 // destroyConstant - Remove the constant from the constant table...
1196 //
1197 void ConstantPacked::destroyConstant() {
1198   PackedConstants->remove(this);
1199   destroyConstantImpl();
1200 }
1201
1202 //---- ConstantPointerNull::get() implementation...
1203 //
1204
1205 namespace llvm {
1206   // ConstantPointerNull does not take extra "value" argument...
1207   template<class ValType>
1208   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1209     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1210       return new ConstantPointerNull(Ty);
1211     }
1212   };
1213
1214   template<>
1215   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1216     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1217       // Make everyone now use a constant of the new type...
1218       Constant *New = ConstantPointerNull::get(NewTy);
1219       assert(New != OldC && "Didn't replace constant??");
1220       OldC->uncheckedReplaceAllUsesWith(New);
1221       OldC->destroyConstant();     // This constant is now dead, destroy it.
1222     }
1223   };
1224 }
1225
1226 static ManagedStatic<ValueMap<char, PointerType, 
1227                               ConstantPointerNull> > NullPtrConstants;
1228
1229 static char getValType(ConstantPointerNull *) {
1230   return 0;
1231 }
1232
1233
1234 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1235   return NullPtrConstants->getOrCreate(Ty, 0);
1236 }
1237
1238 // destroyConstant - Remove the constant from the constant table...
1239 //
1240 void ConstantPointerNull::destroyConstant() {
1241   NullPtrConstants->remove(this);
1242   destroyConstantImpl();
1243 }
1244
1245
1246 //---- UndefValue::get() implementation...
1247 //
1248
1249 namespace llvm {
1250   // UndefValue does not take extra "value" argument...
1251   template<class ValType>
1252   struct ConstantCreator<UndefValue, Type, ValType> {
1253     static UndefValue *create(const Type *Ty, const ValType &V) {
1254       return new UndefValue(Ty);
1255     }
1256   };
1257
1258   template<>
1259   struct ConvertConstantType<UndefValue, Type> {
1260     static void convert(UndefValue *OldC, const Type *NewTy) {
1261       // Make everyone now use a constant of the new type.
1262       Constant *New = UndefValue::get(NewTy);
1263       assert(New != OldC && "Didn't replace constant??");
1264       OldC->uncheckedReplaceAllUsesWith(New);
1265       OldC->destroyConstant();     // This constant is now dead, destroy it.
1266     }
1267   };
1268 }
1269
1270 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1271
1272 static char getValType(UndefValue *) {
1273   return 0;
1274 }
1275
1276
1277 UndefValue *UndefValue::get(const Type *Ty) {
1278   return UndefValueConstants->getOrCreate(Ty, 0);
1279 }
1280
1281 // destroyConstant - Remove the constant from the constant table.
1282 //
1283 void UndefValue::destroyConstant() {
1284   UndefValueConstants->remove(this);
1285   destroyConstantImpl();
1286 }
1287
1288
1289
1290
1291 //---- ConstantExpr::get() implementations...
1292 //
1293 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1294
1295 namespace llvm {
1296   template<>
1297   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1298     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1299       if (V.first == Instruction::Cast)
1300         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1301       if ((V.first >= Instruction::BinaryOpsBegin &&
1302            V.first < Instruction::BinaryOpsEnd) ||
1303           V.first == Instruction::Shl || V.first == Instruction::Shr)
1304         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1305       if (V.first == Instruction::Select)
1306         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1307       if (V.first == Instruction::ExtractElement)
1308         return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1309       if (V.first == Instruction::InsertElement)
1310         return new InsertElementConstantExpr(V.second[0], V.second[1],
1311                                              V.second[2]);
1312       if (V.first == Instruction::ShuffleVector)
1313         return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1314                                              V.second[2]);
1315       
1316       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1317
1318       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1319       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1320     }
1321   };
1322
1323   template<>
1324   struct ConvertConstantType<ConstantExpr, Type> {
1325     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1326       Constant *New;
1327       switch (OldC->getOpcode()) {
1328       case Instruction::Cast:
1329         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1330         break;
1331       case Instruction::Select:
1332         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1333                                         OldC->getOperand(1),
1334                                         OldC->getOperand(2));
1335         break;
1336       case Instruction::Shl:
1337       case Instruction::Shr:
1338         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1339                                      OldC->getOperand(0), OldC->getOperand(1));
1340         break;
1341       default:
1342         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1343                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1344         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1345                                   OldC->getOperand(1));
1346         break;
1347       case Instruction::GetElementPtr:
1348         // Make everyone now use a constant of the new type...
1349         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1350         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1351         break;
1352       }
1353
1354       assert(New != OldC && "Didn't replace constant??");
1355       OldC->uncheckedReplaceAllUsesWith(New);
1356       OldC->destroyConstant();    // This constant is now dead, destroy it.
1357     }
1358   };
1359 } // end namespace llvm
1360
1361
1362 static ExprMapKeyType getValType(ConstantExpr *CE) {
1363   std::vector<Constant*> Operands;
1364   Operands.reserve(CE->getNumOperands());
1365   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1366     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1367   return ExprMapKeyType(CE->getOpcode(), Operands);
1368 }
1369
1370 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1371                               ConstantExpr> > ExprConstants;
1372
1373 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1374   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1375
1376   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1377     return FC;          // Fold a few common cases...
1378
1379   // Look up the constant in the table first to ensure uniqueness
1380   std::vector<Constant*> argVec(1, C);
1381   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1382   return ExprConstants->getOrCreate(Ty, Key);
1383 }
1384
1385 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1386   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1387          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1388          "This is an illegal sign extension!");
1389   if (C->getType() != Type::BoolTy) {
1390     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1391     return ConstantExpr::getCast(C, Ty);
1392   } else {
1393     if (C == ConstantBool::getTrue())
1394       return ConstantIntegral::getAllOnesValue(Ty);
1395     else
1396       return ConstantIntegral::getNullValue(Ty);
1397   }
1398 }
1399
1400 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1401   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1402          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1403          "This is an illegal zero extension!");
1404   if (C->getType() != Type::BoolTy)
1405     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1406   return ConstantExpr::getCast(C, Ty);
1407 }
1408
1409 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1410   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1411   return getCast(
1412     getGetElementPtr(getNullValue(PointerType::get(Ty)),
1413                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1414     Type::ULongTy);
1415 }
1416
1417 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1418   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1419   static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1420
1421   return ConstantExpr::getGetElementPtr(C, Indices);
1422 }
1423
1424 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1425                               Constant *C1, Constant *C2) {
1426   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1427     return getShiftTy(ReqTy, Opcode, C1, C2);
1428   // Check the operands for consistency first
1429   assert((Opcode >= Instruction::BinaryOpsBegin &&
1430           Opcode < Instruction::BinaryOpsEnd) &&
1431          "Invalid opcode in binary constant expression");
1432   assert(C1->getType() == C2->getType() &&
1433          "Operand types in binary constant expression should match");
1434
1435   if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1436                                  ReqTy == Type::BoolTy))
1437     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1438       return FC;          // Fold a few common cases...
1439
1440   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1441   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1442   return ExprConstants->getOrCreate(ReqTy, Key);
1443 }
1444
1445 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1446 #ifndef NDEBUG
1447   switch (Opcode) {
1448   case Instruction::Add: case Instruction::Sub:
1449   case Instruction::Mul: case Instruction::Div:
1450   case Instruction::Rem:
1451     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1452     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1453             isa<PackedType>(C1->getType())) &&
1454            "Tried to create an arithmetic operation on a non-arithmetic type!");
1455     break;
1456   case Instruction::And:
1457   case Instruction::Or:
1458   case Instruction::Xor:
1459     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1460     assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1461            "Tried to create a logical operation on a non-integral type!");
1462     break;
1463   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1464   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1465     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1466     break;
1467   case Instruction::Shl:
1468   case Instruction::Shr:
1469     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1470     assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1471            "Tried to create a shift operation on a non-integer type!");
1472     break;
1473   default:
1474     break;
1475   }
1476 #endif
1477
1478   if (Instruction::isComparison(Opcode))
1479     return getTy(Type::BoolTy, Opcode, C1, C2);
1480   else
1481     return getTy(C1->getType(), Opcode, C1, C2);
1482 }
1483
1484 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1485                                     Constant *V1, Constant *V2) {
1486   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1487   assert(V1->getType() == V2->getType() && "Select value types must match!");
1488   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1489
1490   if (ReqTy == V1->getType())
1491     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1492       return SC;        // Fold common cases
1493
1494   std::vector<Constant*> argVec(3, C);
1495   argVec[1] = V1;
1496   argVec[2] = V2;
1497   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1498   return ExprConstants->getOrCreate(ReqTy, Key);
1499 }
1500
1501 /// getShiftTy - Return a shift left or shift right constant expr
1502 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1503                                    Constant *C1, Constant *C2) {
1504   // Check the operands for consistency first
1505   assert((Opcode == Instruction::Shl ||
1506           Opcode == Instruction::Shr) &&
1507          "Invalid opcode in binary constant expression");
1508   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1509          "Invalid operand types for Shift constant expr!");
1510
1511   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1512     return FC;          // Fold a few common cases...
1513
1514   // Look up the constant in the table first to ensure uniqueness
1515   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1516   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1517   return ExprConstants->getOrCreate(ReqTy, Key);
1518 }
1519
1520
1521 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1522                                            const std::vector<Value*> &IdxList) {
1523   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1524          "GEP indices invalid!");
1525
1526   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1527     return FC;          // Fold a few common cases...
1528
1529   assert(isa<PointerType>(C->getType()) &&
1530          "Non-pointer type for constant GetElementPtr expression");
1531   // Look up the constant in the table first to ensure uniqueness
1532   std::vector<Constant*> ArgVec;
1533   ArgVec.reserve(IdxList.size()+1);
1534   ArgVec.push_back(C);
1535   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1536     ArgVec.push_back(cast<Constant>(IdxList[i]));
1537   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1538   return ExprConstants->getOrCreate(ReqTy, Key);
1539 }
1540
1541 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1542                                          const std::vector<Constant*> &IdxList){
1543   // Get the result type of the getelementptr!
1544   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1545
1546   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1547                                                      true);
1548   assert(Ty && "GEP indices invalid!");
1549   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1550 }
1551
1552 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1553                                          const std::vector<Value*> &IdxList) {
1554   // Get the result type of the getelementptr!
1555   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1556                                                      true);
1557   assert(Ty && "GEP indices invalid!");
1558   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1559 }
1560
1561 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1562                                             Constant *Idx) {
1563   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1564     return FC;          // Fold a few common cases...
1565   // Look up the constant in the table first to ensure uniqueness
1566   std::vector<Constant*> ArgVec(1, Val);
1567   ArgVec.push_back(Idx);
1568   const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1569   return ExprConstants->getOrCreate(ReqTy, Key);
1570 }
1571
1572 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1573   assert(isa<PackedType>(Val->getType()) &&
1574          "Tried to create extractelement operation on non-packed type!");
1575   assert(Idx->getType() == Type::UIntTy &&
1576          "Extractelement index must be uint type!");
1577   return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1578                              Val, Idx);
1579 }
1580
1581 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1582                                            Constant *Elt, Constant *Idx) {
1583   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1584     return FC;          // Fold a few common cases...
1585   // Look up the constant in the table first to ensure uniqueness
1586   std::vector<Constant*> ArgVec(1, Val);
1587   ArgVec.push_back(Elt);
1588   ArgVec.push_back(Idx);
1589   const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1590   return ExprConstants->getOrCreate(ReqTy, Key);
1591 }
1592
1593 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1594                                          Constant *Idx) {
1595   assert(isa<PackedType>(Val->getType()) &&
1596          "Tried to create insertelement operation on non-packed type!");
1597   assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1598          && "Insertelement types must match!");
1599   assert(Idx->getType() == Type::UIntTy &&
1600          "Insertelement index must be uint type!");
1601   return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1602                             Val, Elt, Idx);
1603 }
1604
1605 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1606                                            Constant *V2, Constant *Mask) {
1607   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1608     return FC;          // Fold a few common cases...
1609   // Look up the constant in the table first to ensure uniqueness
1610   std::vector<Constant*> ArgVec(1, V1);
1611   ArgVec.push_back(V2);
1612   ArgVec.push_back(Mask);
1613   const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
1614   return ExprConstants->getOrCreate(ReqTy, Key);
1615 }
1616
1617 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1618                                          Constant *Mask) {
1619   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1620          "Invalid shuffle vector constant expr operands!");
1621   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1622 }
1623
1624
1625 // destroyConstant - Remove the constant from the constant table...
1626 //
1627 void ConstantExpr::destroyConstant() {
1628   ExprConstants->remove(this);
1629   destroyConstantImpl();
1630 }
1631
1632 const char *ConstantExpr::getOpcodeName() const {
1633   return Instruction::getOpcodeName(getOpcode());
1634 }
1635
1636 //===----------------------------------------------------------------------===//
1637 //                replaceUsesOfWithOnConstant implementations
1638
1639 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1640                                                 Use *U) {
1641   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1642   Constant *ToC = cast<Constant>(To);
1643
1644   unsigned OperandToUpdate = U-OperandList;
1645   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1646
1647   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1648   Lookup.first.first = getType();
1649   Lookup.second = this;
1650
1651   std::vector<Constant*> &Values = Lookup.first.second;
1652   Values.reserve(getNumOperands());  // Build replacement array.
1653
1654   // Fill values with the modified operands of the constant array.  Also, 
1655   // compute whether this turns into an all-zeros array.
1656   bool isAllZeros = false;
1657   if (!ToC->isNullValue()) {
1658     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1659       Values.push_back(cast<Constant>(O->get()));
1660   } else {
1661     isAllZeros = true;
1662     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1663       Constant *Val = cast<Constant>(O->get());
1664       Values.push_back(Val);
1665       if (isAllZeros) isAllZeros = Val->isNullValue();
1666     }
1667   }
1668   Values[OperandToUpdate] = ToC;
1669   
1670   Constant *Replacement = 0;
1671   if (isAllZeros) {
1672     Replacement = ConstantAggregateZero::get(getType());
1673   } else {
1674     // Check to see if we have this array type already.
1675     bool Exists;
1676     ArrayConstantsTy::MapTy::iterator I =
1677       ArrayConstants->InsertOrGetItem(Lookup, Exists);
1678     
1679     if (Exists) {
1680       Replacement = I->second;
1681     } else {
1682       // Okay, the new shape doesn't exist in the system yet.  Instead of
1683       // creating a new constant array, inserting it, replaceallusesof'ing the
1684       // old with the new, then deleting the old... just update the current one
1685       // in place!
1686       ArrayConstants->MoveConstantToNewSlot(this, I);
1687       
1688       // Update to the new value.
1689       setOperand(OperandToUpdate, ToC);
1690       return;
1691     }
1692   }
1693  
1694   // Otherwise, I do need to replace this with an existing value.
1695   assert(Replacement != this && "I didn't contain From!");
1696   
1697   // Everyone using this now uses the replacement.
1698   uncheckedReplaceAllUsesWith(Replacement);
1699   
1700   // Delete the old constant!
1701   destroyConstant();
1702 }
1703
1704 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1705                                                  Use *U) {
1706   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1707   Constant *ToC = cast<Constant>(To);
1708
1709   unsigned OperandToUpdate = U-OperandList;
1710   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1711
1712   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1713   Lookup.first.first = getType();
1714   Lookup.second = this;
1715   std::vector<Constant*> &Values = Lookup.first.second;
1716   Values.reserve(getNumOperands());  // Build replacement struct.
1717   
1718   
1719   // Fill values with the modified operands of the constant struct.  Also, 
1720   // compute whether this turns into an all-zeros struct.
1721   bool isAllZeros = false;
1722   if (!ToC->isNullValue()) {
1723     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1724       Values.push_back(cast<Constant>(O->get()));
1725   } else {
1726     isAllZeros = true;
1727     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1728       Constant *Val = cast<Constant>(O->get());
1729       Values.push_back(Val);
1730       if (isAllZeros) isAllZeros = Val->isNullValue();
1731     }
1732   }
1733   Values[OperandToUpdate] = ToC;
1734   
1735   Constant *Replacement = 0;
1736   if (isAllZeros) {
1737     Replacement = ConstantAggregateZero::get(getType());
1738   } else {
1739     // Check to see if we have this array type already.
1740     bool Exists;
1741     StructConstantsTy::MapTy::iterator I =
1742       StructConstants->InsertOrGetItem(Lookup, Exists);
1743     
1744     if (Exists) {
1745       Replacement = I->second;
1746     } else {
1747       // Okay, the new shape doesn't exist in the system yet.  Instead of
1748       // creating a new constant struct, inserting it, replaceallusesof'ing the
1749       // old with the new, then deleting the old... just update the current one
1750       // in place!
1751       StructConstants->MoveConstantToNewSlot(this, I);
1752       
1753       // Update to the new value.
1754       setOperand(OperandToUpdate, ToC);
1755       return;
1756     }
1757   }
1758   
1759   assert(Replacement != this && "I didn't contain From!");
1760   
1761   // Everyone using this now uses the replacement.
1762   uncheckedReplaceAllUsesWith(Replacement);
1763   
1764   // Delete the old constant!
1765   destroyConstant();
1766 }
1767
1768 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1769                                                  Use *U) {
1770   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1771   
1772   std::vector<Constant*> Values;
1773   Values.reserve(getNumOperands());  // Build replacement array...
1774   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1775     Constant *Val = getOperand(i);
1776     if (Val == From) Val = cast<Constant>(To);
1777     Values.push_back(Val);
1778   }
1779   
1780   Constant *Replacement = ConstantPacked::get(getType(), Values);
1781   assert(Replacement != this && "I didn't contain From!");
1782   
1783   // Everyone using this now uses the replacement.
1784   uncheckedReplaceAllUsesWith(Replacement);
1785   
1786   // Delete the old constant!
1787   destroyConstant();
1788 }
1789
1790 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1791                                                Use *U) {
1792   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1793   Constant *To = cast<Constant>(ToV);
1794   
1795   Constant *Replacement = 0;
1796   if (getOpcode() == Instruction::GetElementPtr) {
1797     std::vector<Constant*> Indices;
1798     Constant *Pointer = getOperand(0);
1799     Indices.reserve(getNumOperands()-1);
1800     if (Pointer == From) Pointer = To;
1801     
1802     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1803       Constant *Val = getOperand(i);
1804       if (Val == From) Val = To;
1805       Indices.push_back(Val);
1806     }
1807     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1808   } else if (getOpcode() == Instruction::Cast) {
1809     assert(getOperand(0) == From && "Cast only has one use!");
1810     Replacement = ConstantExpr::getCast(To, getType());
1811   } else if (getOpcode() == Instruction::Select) {
1812     Constant *C1 = getOperand(0);
1813     Constant *C2 = getOperand(1);
1814     Constant *C3 = getOperand(2);
1815     if (C1 == From) C1 = To;
1816     if (C2 == From) C2 = To;
1817     if (C3 == From) C3 = To;
1818     Replacement = ConstantExpr::getSelect(C1, C2, C3);
1819   } else if (getOpcode() == Instruction::ExtractElement) {
1820     Constant *C1 = getOperand(0);
1821     Constant *C2 = getOperand(1);
1822     if (C1 == From) C1 = To;
1823     if (C2 == From) C2 = To;
1824     Replacement = ConstantExpr::getExtractElement(C1, C2);
1825   } else if (getOpcode() == Instruction::InsertElement) {
1826     Constant *C1 = getOperand(0);
1827     Constant *C2 = getOperand(1);
1828     Constant *C3 = getOperand(1);
1829     if (C1 == From) C1 = To;
1830     if (C2 == From) C2 = To;
1831     if (C3 == From) C3 = To;
1832     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1833   } else if (getOpcode() == Instruction::ShuffleVector) {
1834     Constant *C1 = getOperand(0);
1835     Constant *C2 = getOperand(1);
1836     Constant *C3 = getOperand(2);
1837     if (C1 == From) C1 = To;
1838     if (C2 == From) C2 = To;
1839     if (C3 == From) C3 = To;
1840     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
1841   } else if (getNumOperands() == 2) {
1842     Constant *C1 = getOperand(0);
1843     Constant *C2 = getOperand(1);
1844     if (C1 == From) C1 = To;
1845     if (C2 == From) C2 = To;
1846     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1847   } else {
1848     assert(0 && "Unknown ConstantExpr type!");
1849     return;
1850   }
1851   
1852   assert(Replacement != this && "I didn't contain From!");
1853   
1854   // Everyone using this now uses the replacement.
1855   uncheckedReplaceAllUsesWith(Replacement);
1856   
1857   // Delete the old constant!
1858   destroyConstant();
1859 }
1860
1861
1862 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
1863 /// global into a string value.  Return an empty string if we can't do it.
1864 /// Parameter Chop determines if the result is chopped at the first null
1865 /// terminator.
1866 ///
1867 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
1868   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
1869     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
1870       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1871       if (Init->isString()) {
1872         std::string Result = Init->getAsString();
1873         if (Offset < Result.size()) {
1874           // If we are pointing INTO The string, erase the beginning...
1875           Result.erase(Result.begin(), Result.begin()+Offset);
1876
1877           // Take off the null terminator, and any string fragments after it.
1878           if (Chop) {
1879             std::string::size_type NullPos = Result.find_first_of((char)0);
1880             if (NullPos != std::string::npos)
1881               Result.erase(Result.begin()+NullPos, Result.end());
1882           }
1883           return Result;
1884         }
1885       }
1886     }
1887   } else if (Constant *C = dyn_cast<Constant>(this)) {
1888     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1889       return GV->getStringValue(Chop, Offset);
1890     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1891       if (CE->getOpcode() == Instruction::GetElementPtr) {
1892         // Turn a gep into the specified offset.
1893         if (CE->getNumOperands() == 3 &&
1894             cast<Constant>(CE->getOperand(1))->isNullValue() &&
1895             isa<ConstantInt>(CE->getOperand(2))) {
1896           Offset += cast<ConstantInt>(CE->getOperand(2))->getRawValue();
1897           return CE->getOperand(0)->getStringValue(Chop, Offset);
1898         }
1899       }
1900     }
1901   }
1902   return "";
1903 }
1904