reimplement Constant::ContainsRelocations as
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include <algorithm>
36 #include <map>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 //                              Constant Class
41 //===----------------------------------------------------------------------===//
42
43 // Becomes a no-op when multithreading is disabled.
44 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45
46 void Constant::destroyConstantImpl() {
47   // When a Constant is destroyed, there may be lingering
48   // references to the constant by other constants in the constant pool.  These
49   // constants are implicitly dependent on the module that is being deleted,
50   // but they don't know that.  Because we only find out when the CPV is
51   // deleted, we must now notify all of our users (that should only be
52   // Constants) that they are, in fact, invalid now and should be deleted.
53   //
54   while (!use_empty()) {
55     Value *V = use_back();
56 #ifndef NDEBUG      // Only in -g mode...
57     if (!isa<Constant>(V))
58       DOUT << "While deleting: " << *this
59            << "\n\nUse still stuck around after Def is destroyed: "
60            << *V << "\n\n";
61 #endif
62     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
63     Constant *CV = cast<Constant>(V);
64     CV->destroyConstant();
65
66     // The constant should remove itself from our use list...
67     assert((use_empty() || use_back() != V) && "Constant not removed!");
68   }
69
70   // Value has no outstanding references it is safe to delete it now...
71   delete this;
72 }
73
74 /// canTrap - Return true if evaluation of this constant could trap.  This is
75 /// true for things like constant expressions that could divide by zero.
76 bool Constant::canTrap() const {
77   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
78   // The only thing that could possibly trap are constant exprs.
79   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
80   if (!CE) return false;
81   
82   // ConstantExpr traps if any operands can trap. 
83   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
84     if (getOperand(i)->canTrap()) 
85       return true;
86
87   // Otherwise, only specific operations can trap.
88   switch (CE->getOpcode()) {
89   default:
90     return false;
91   case Instruction::UDiv:
92   case Instruction::SDiv:
93   case Instruction::FDiv:
94   case Instruction::URem:
95   case Instruction::SRem:
96   case Instruction::FRem:
97     // Div and rem can trap if the RHS is not known to be non-zero.
98     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
99       return true;
100     return false;
101   }
102 }
103
104
105 /// getRelocationInfo - This method classifies the entry according to
106 /// whether or not it may generate a relocation entry.  This must be
107 /// conservative, so if it might codegen to a relocatable entry, it should say
108 /// so.  The return values are:
109 /// 
110 ///  0: This constant pool entry is guaranteed to never have a relocation
111 ///     applied to it (because it holds a simple constant like '4').
112 ///  1: This entry has relocations, but the entries are guaranteed to be
113 ///     resolvable by the static linker, so the dynamic linker will never see
114 ///     them.
115 ///  2: This entry may have arbitrary relocations.
116 ///
117 /// FIXME: This really should not be in VMCore.
118 unsigned Constant::getRelocationInfo() const {
119   if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
120     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
121       return 1;  // Local to this file/library.
122     return 2;    // Global reference.
123   }
124   
125   unsigned Result = 0;
126   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
127     Result = std::max(Result, getOperand(i)->getRelocationInfo());
128   
129   return Result;
130 }
131
132
133 /// getVectorElements - This method, which is only valid on constant of vector
134 /// type, returns the elements of the vector in the specified smallvector.
135 /// This handles breaking down a vector undef into undef elements, etc.  For
136 /// constant exprs and other cases we can't handle, we return an empty vector.
137 void Constant::getVectorElements(LLVMContext &Context,
138                                  SmallVectorImpl<Constant*> &Elts) const {
139   assert(isa<VectorType>(getType()) && "Not a vector constant!");
140   
141   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
142     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
143       Elts.push_back(CV->getOperand(i));
144     return;
145   }
146   
147   const VectorType *VT = cast<VectorType>(getType());
148   if (isa<ConstantAggregateZero>(this)) {
149     Elts.assign(VT->getNumElements(), 
150                 Context.getNullValue(VT->getElementType()));
151     return;
152   }
153   
154   if (isa<UndefValue>(this)) {
155     Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
156     return;
157   }
158   
159   // Unknown type, must be constant expr etc.
160 }
161
162
163
164 //===----------------------------------------------------------------------===//
165 //                                ConstantInt
166 //===----------------------------------------------------------------------===//
167
168 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
169   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
170   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 }
172
173 //===----------------------------------------------------------------------===//
174 //                                ConstantFP
175 //===----------------------------------------------------------------------===//
176
177 #ifndef NDEBUG 
178 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
179   if (Ty == Type::FloatTy)
180     return &APFloat::IEEEsingle;
181   if (Ty == Type::DoubleTy)
182     return &APFloat::IEEEdouble;
183   if (Ty == Type::X86_FP80Ty)
184     return &APFloat::x87DoubleExtended;
185   else if (Ty == Type::FP128Ty)
186     return &APFloat::IEEEquad;
187   
188   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
189   return &APFloat::PPCDoubleDouble;
190 }
191 #endif
192
193 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
194   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
195   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
196          "FP type Mismatch");
197 }
198
199 bool ConstantFP::isNullValue() const {
200   return Val.isZero() && !Val.isNegative();
201 }
202
203 bool ConstantFP::isExactlyValue(const APFloat& V) const {
204   return Val.bitwiseIsEqual(V);
205 }
206
207 //===----------------------------------------------------------------------===//
208 //                            ConstantXXX Classes
209 //===----------------------------------------------------------------------===//
210
211
212 ConstantArray::ConstantArray(const ArrayType *T,
213                              const std::vector<Constant*> &V)
214   : Constant(T, ConstantArrayVal,
215              OperandTraits<ConstantArray>::op_end(this) - V.size(),
216              V.size()) {
217   assert(V.size() == T->getNumElements() &&
218          "Invalid initializer vector for constant array");
219   Use *OL = OperandList;
220   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
221        I != E; ++I, ++OL) {
222     Constant *C = *I;
223     assert((C->getType() == T->getElementType() ||
224             (T->isAbstract() &&
225              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
226            "Initializer for array element doesn't match array element type!");
227     *OL = C;
228   }
229 }
230
231
232 ConstantStruct::ConstantStruct(const StructType *T,
233                                const std::vector<Constant*> &V)
234   : Constant(T, ConstantStructVal,
235              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
236              V.size()) {
237   assert(V.size() == T->getNumElements() &&
238          "Invalid initializer vector for constant structure");
239   Use *OL = OperandList;
240   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
241        I != E; ++I, ++OL) {
242     Constant *C = *I;
243     assert((C->getType() == T->getElementType(I-V.begin()) ||
244             ((T->getElementType(I-V.begin())->isAbstract() ||
245               C->getType()->isAbstract()) &&
246              T->getElementType(I-V.begin())->getTypeID() == 
247                    C->getType()->getTypeID())) &&
248            "Initializer for struct element doesn't match struct element type!");
249     *OL = C;
250   }
251 }
252
253
254 ConstantVector::ConstantVector(const VectorType *T,
255                                const std::vector<Constant*> &V)
256   : Constant(T, ConstantVectorVal,
257              OperandTraits<ConstantVector>::op_end(this) - V.size(),
258              V.size()) {
259   Use *OL = OperandList;
260     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
261          I != E; ++I, ++OL) {
262       Constant *C = *I;
263       assert((C->getType() == T->getElementType() ||
264             (T->isAbstract() &&
265              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
266            "Initializer for vector element doesn't match vector element type!");
267     *OL = C;
268   }
269 }
270
271
272 namespace llvm {
273 // We declare several classes private to this file, so use an anonymous
274 // namespace
275 namespace {
276
277 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
278 /// behind the scenes to implement unary constant exprs.
279 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
280   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
281 public:
282   // allocate space for exactly one operand
283   void *operator new(size_t s) {
284     return User::operator new(s, 1);
285   }
286   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
287     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
288     Op<0>() = C;
289   }
290   /// Transparently provide more efficient getOperand methods.
291   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
292 };
293
294 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
295 /// behind the scenes to implement binary constant exprs.
296 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
297   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
298 public:
299   // allocate space for exactly two operands
300   void *operator new(size_t s) {
301     return User::operator new(s, 2);
302   }
303   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
304     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
305     Op<0>() = C1;
306     Op<1>() = C2;
307   }
308   /// Transparently provide more efficient getOperand methods.
309   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
310 };
311
312 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
313 /// behind the scenes to implement select constant exprs.
314 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
315   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
316 public:
317   // allocate space for exactly three operands
318   void *operator new(size_t s) {
319     return User::operator new(s, 3);
320   }
321   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
322     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
323     Op<0>() = C1;
324     Op<1>() = C2;
325     Op<2>() = C3;
326   }
327   /// Transparently provide more efficient getOperand methods.
328   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
329 };
330
331 /// ExtractElementConstantExpr - This class is private to
332 /// Constants.cpp, and is used behind the scenes to implement
333 /// extractelement constant exprs.
334 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
335   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
336 public:
337   // allocate space for exactly two operands
338   void *operator new(size_t s) {
339     return User::operator new(s, 2);
340   }
341   ExtractElementConstantExpr(Constant *C1, Constant *C2)
342     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
343                    Instruction::ExtractElement, &Op<0>(), 2) {
344     Op<0>() = C1;
345     Op<1>() = C2;
346   }
347   /// Transparently provide more efficient getOperand methods.
348   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
349 };
350
351 /// InsertElementConstantExpr - This class is private to
352 /// Constants.cpp, and is used behind the scenes to implement
353 /// insertelement constant exprs.
354 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
355   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
356 public:
357   // allocate space for exactly three operands
358   void *operator new(size_t s) {
359     return User::operator new(s, 3);
360   }
361   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
362     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
363                    &Op<0>(), 3) {
364     Op<0>() = C1;
365     Op<1>() = C2;
366     Op<2>() = C3;
367   }
368   /// Transparently provide more efficient getOperand methods.
369   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
370 };
371
372 /// ShuffleVectorConstantExpr - This class is private to
373 /// Constants.cpp, and is used behind the scenes to implement
374 /// shufflevector constant exprs.
375 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
376   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
377 public:
378   // allocate space for exactly three operands
379   void *operator new(size_t s) {
380     return User::operator new(s, 3);
381   }
382   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
383   : ConstantExpr(VectorType::get(
384                    cast<VectorType>(C1->getType())->getElementType(),
385                    cast<VectorType>(C3->getType())->getNumElements()),
386                  Instruction::ShuffleVector, 
387                  &Op<0>(), 3) {
388     Op<0>() = C1;
389     Op<1>() = C2;
390     Op<2>() = C3;
391   }
392   /// Transparently provide more efficient getOperand methods.
393   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
394 };
395
396 /// ExtractValueConstantExpr - This class is private to
397 /// Constants.cpp, and is used behind the scenes to implement
398 /// extractvalue constant exprs.
399 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
400   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
401 public:
402   // allocate space for exactly one operand
403   void *operator new(size_t s) {
404     return User::operator new(s, 1);
405   }
406   ExtractValueConstantExpr(Constant *Agg,
407                            const SmallVector<unsigned, 4> &IdxList,
408                            const Type *DestTy)
409     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
410       Indices(IdxList) {
411     Op<0>() = Agg;
412   }
413
414   /// Indices - These identify which value to extract.
415   const SmallVector<unsigned, 4> Indices;
416
417   /// Transparently provide more efficient getOperand methods.
418   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
419 };
420
421 /// InsertValueConstantExpr - This class is private to
422 /// Constants.cpp, and is used behind the scenes to implement
423 /// insertvalue constant exprs.
424 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
425   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
426 public:
427   // allocate space for exactly one operand
428   void *operator new(size_t s) {
429     return User::operator new(s, 2);
430   }
431   InsertValueConstantExpr(Constant *Agg, Constant *Val,
432                           const SmallVector<unsigned, 4> &IdxList,
433                           const Type *DestTy)
434     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
435       Indices(IdxList) {
436     Op<0>() = Agg;
437     Op<1>() = Val;
438   }
439
440   /// Indices - These identify the position for the insertion.
441   const SmallVector<unsigned, 4> Indices;
442
443   /// Transparently provide more efficient getOperand methods.
444   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
445 };
446
447
448 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
449 /// used behind the scenes to implement getelementpr constant exprs.
450 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
451   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
452                             const Type *DestTy);
453 public:
454   static GetElementPtrConstantExpr *Create(Constant *C,
455                                            const std::vector<Constant*>&IdxList,
456                                            const Type *DestTy) {
457     return
458       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
459   }
460   /// Transparently provide more efficient getOperand methods.
461   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
462 };
463
464 // CompareConstantExpr - This class is private to Constants.cpp, and is used
465 // behind the scenes to implement ICmp and FCmp constant expressions. This is
466 // needed in order to store the predicate value for these instructions.
467 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
468   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
469   // allocate space for exactly two operands
470   void *operator new(size_t s) {
471     return User::operator new(s, 2);
472   }
473   unsigned short predicate;
474   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
475                       unsigned short pred,  Constant* LHS, Constant* RHS)
476     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
477     Op<0>() = LHS;
478     Op<1>() = RHS;
479   }
480   /// Transparently provide more efficient getOperand methods.
481   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
482 };
483
484 } // end anonymous namespace
485
486 template <>
487 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
488 };
489 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
490
491 template <>
492 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
493 };
494 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
495
496 template <>
497 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
498 };
499 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
500
501 template <>
502 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
503 };
504 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
505
506 template <>
507 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
508 };
509 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
510
511 template <>
512 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
513 };
514 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
515
516 template <>
517 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
518 };
519 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
520
521 template <>
522 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
523 };
524 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
525
526 template <>
527 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
528 };
529
530 GetElementPtrConstantExpr::GetElementPtrConstantExpr
531   (Constant *C,
532    const std::vector<Constant*> &IdxList,
533    const Type *DestTy)
534     : ConstantExpr(DestTy, Instruction::GetElementPtr,
535                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
536                    - (IdxList.size()+1),
537                    IdxList.size()+1) {
538   OperandList[0] = C;
539   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
540     OperandList[i+1] = IdxList[i];
541 }
542
543 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
544
545
546 template <>
547 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
548 };
549 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
550
551
552 } // End llvm namespace
553
554
555 // Utility function for determining if a ConstantExpr is a CastOp or not. This
556 // can't be inline because we don't want to #include Instruction.h into
557 // Constant.h
558 bool ConstantExpr::isCast() const {
559   return Instruction::isCast(getOpcode());
560 }
561
562 bool ConstantExpr::isCompare() const {
563   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
564 }
565
566 bool ConstantExpr::hasIndices() const {
567   return getOpcode() == Instruction::ExtractValue ||
568          getOpcode() == Instruction::InsertValue;
569 }
570
571 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
572   if (const ExtractValueConstantExpr *EVCE =
573         dyn_cast<ExtractValueConstantExpr>(this))
574     return EVCE->Indices;
575
576   return cast<InsertValueConstantExpr>(this)->Indices;
577 }
578
579 unsigned ConstantExpr::getPredicate() const {
580   assert(getOpcode() == Instruction::FCmp || 
581          getOpcode() == Instruction::ICmp);
582   return ((const CompareConstantExpr*)this)->predicate;
583 }
584
585 /// getWithOperandReplaced - Return a constant expression identical to this
586 /// one, but with the specified operand set to the specified value.
587 Constant *
588 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
589   assert(OpNo < getNumOperands() && "Operand num is out of range!");
590   assert(Op->getType() == getOperand(OpNo)->getType() &&
591          "Replacing operand with value of different type!");
592   if (getOperand(OpNo) == Op)
593     return const_cast<ConstantExpr*>(this);
594   
595   Constant *Op0, *Op1, *Op2;
596   switch (getOpcode()) {
597   case Instruction::Trunc:
598   case Instruction::ZExt:
599   case Instruction::SExt:
600   case Instruction::FPTrunc:
601   case Instruction::FPExt:
602   case Instruction::UIToFP:
603   case Instruction::SIToFP:
604   case Instruction::FPToUI:
605   case Instruction::FPToSI:
606   case Instruction::PtrToInt:
607   case Instruction::IntToPtr:
608   case Instruction::BitCast:
609     return ConstantExpr::getCast(getOpcode(), Op, getType());
610   case Instruction::Select:
611     Op0 = (OpNo == 0) ? Op : getOperand(0);
612     Op1 = (OpNo == 1) ? Op : getOperand(1);
613     Op2 = (OpNo == 2) ? Op : getOperand(2);
614     return ConstantExpr::getSelect(Op0, Op1, Op2);
615   case Instruction::InsertElement:
616     Op0 = (OpNo == 0) ? Op : getOperand(0);
617     Op1 = (OpNo == 1) ? Op : getOperand(1);
618     Op2 = (OpNo == 2) ? Op : getOperand(2);
619     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
620   case Instruction::ExtractElement:
621     Op0 = (OpNo == 0) ? Op : getOperand(0);
622     Op1 = (OpNo == 1) ? Op : getOperand(1);
623     return ConstantExpr::getExtractElement(Op0, Op1);
624   case Instruction::ShuffleVector:
625     Op0 = (OpNo == 0) ? Op : getOperand(0);
626     Op1 = (OpNo == 1) ? Op : getOperand(1);
627     Op2 = (OpNo == 2) ? Op : getOperand(2);
628     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
629   case Instruction::GetElementPtr: {
630     SmallVector<Constant*, 8> Ops;
631     Ops.resize(getNumOperands()-1);
632     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
633       Ops[i-1] = getOperand(i);
634     if (OpNo == 0)
635       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
636     Ops[OpNo-1] = Op;
637     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
638   }
639   default:
640     assert(getNumOperands() == 2 && "Must be binary operator?");
641     Op0 = (OpNo == 0) ? Op : getOperand(0);
642     Op1 = (OpNo == 1) ? Op : getOperand(1);
643     return ConstantExpr::get(getOpcode(), Op0, Op1);
644   }
645 }
646
647 /// getWithOperands - This returns the current constant expression with the
648 /// operands replaced with the specified values.  The specified operands must
649 /// match count and type with the existing ones.
650 Constant *ConstantExpr::
651 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
652   assert(NumOps == getNumOperands() && "Operand count mismatch!");
653   bool AnyChange = false;
654   for (unsigned i = 0; i != NumOps; ++i) {
655     assert(Ops[i]->getType() == getOperand(i)->getType() &&
656            "Operand type mismatch!");
657     AnyChange |= Ops[i] != getOperand(i);
658   }
659   if (!AnyChange)  // No operands changed, return self.
660     return const_cast<ConstantExpr*>(this);
661
662   switch (getOpcode()) {
663   case Instruction::Trunc:
664   case Instruction::ZExt:
665   case Instruction::SExt:
666   case Instruction::FPTrunc:
667   case Instruction::FPExt:
668   case Instruction::UIToFP:
669   case Instruction::SIToFP:
670   case Instruction::FPToUI:
671   case Instruction::FPToSI:
672   case Instruction::PtrToInt:
673   case Instruction::IntToPtr:
674   case Instruction::BitCast:
675     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
676   case Instruction::Select:
677     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
678   case Instruction::InsertElement:
679     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
680   case Instruction::ExtractElement:
681     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
682   case Instruction::ShuffleVector:
683     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
684   case Instruction::GetElementPtr:
685     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
686   case Instruction::ICmp:
687   case Instruction::FCmp:
688     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
689   default:
690     assert(getNumOperands() == 2 && "Must be binary operator?");
691     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
692   }
693 }
694
695
696 //===----------------------------------------------------------------------===//
697 //                      isValueValidForType implementations
698
699 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
700   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
701   if (Ty == Type::Int1Ty)
702     return Val == 0 || Val == 1;
703   if (NumBits >= 64)
704     return true; // always true, has to fit in largest type
705   uint64_t Max = (1ll << NumBits) - 1;
706   return Val <= Max;
707 }
708
709 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
710   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
711   if (Ty == Type::Int1Ty)
712     return Val == 0 || Val == 1 || Val == -1;
713   if (NumBits >= 64)
714     return true; // always true, has to fit in largest type
715   int64_t Min = -(1ll << (NumBits-1));
716   int64_t Max = (1ll << (NumBits-1)) - 1;
717   return (Val >= Min && Val <= Max);
718 }
719
720 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
721   // convert modifies in place, so make a copy.
722   APFloat Val2 = APFloat(Val);
723   bool losesInfo;
724   switch (Ty->getTypeID()) {
725   default:
726     return false;         // These can't be represented as floating point!
727
728   // FIXME rounding mode needs to be more flexible
729   case Type::FloatTyID: {
730     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
731       return true;
732     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
733     return !losesInfo;
734   }
735   case Type::DoubleTyID: {
736     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
737         &Val2.getSemantics() == &APFloat::IEEEdouble)
738       return true;
739     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
740     return !losesInfo;
741   }
742   case Type::X86_FP80TyID:
743     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
744            &Val2.getSemantics() == &APFloat::IEEEdouble ||
745            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
746   case Type::FP128TyID:
747     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
748            &Val2.getSemantics() == &APFloat::IEEEdouble ||
749            &Val2.getSemantics() == &APFloat::IEEEquad;
750   case Type::PPC_FP128TyID:
751     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
752            &Val2.getSemantics() == &APFloat::IEEEdouble ||
753            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
754   }
755 }
756
757 //===----------------------------------------------------------------------===//
758 //                      Factory Function Implementation
759
760
761 // The number of operands for each ConstantCreator::create method is
762 // determined by the ConstantTraits template.
763 // ConstantCreator - A class that is used to create constants by
764 // ValueMap*.  This class should be partially specialized if there is
765 // something strange that needs to be done to interface to the ctor for the
766 // constant.
767 //
768 namespace llvm {
769   template<class ValType>
770   struct ConstantTraits;
771
772   template<typename T, typename Alloc>
773   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
774     static unsigned uses(const std::vector<T, Alloc>& v) {
775       return v.size();
776     }
777   };
778
779   template<class ConstantClass, class TypeClass, class ValType>
780   struct VISIBILITY_HIDDEN ConstantCreator {
781     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
782       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
783     }
784   };
785
786   template<class ConstantClass, class TypeClass>
787   struct VISIBILITY_HIDDEN ConvertConstantType {
788     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
789       llvm_unreachable("This type cannot be converted!");
790     }
791   };
792
793   template<class ValType, class TypeClass, class ConstantClass,
794            bool HasLargeKey = false  /*true for arrays and structs*/ >
795   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
796   public:
797     typedef std::pair<const Type*, ValType> MapKey;
798     typedef std::map<MapKey, Constant *> MapTy;
799     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
800     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
801   private:
802     /// Map - This is the main map from the element descriptor to the Constants.
803     /// This is the primary way we avoid creating two of the same shape
804     /// constant.
805     MapTy Map;
806     
807     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
808     /// from the constants to their element in Map.  This is important for
809     /// removal of constants from the array, which would otherwise have to scan
810     /// through the map with very large keys.
811     InverseMapTy InverseMap;
812
813     /// AbstractTypeMap - Map for abstract type constants.
814     ///
815     AbstractTypeMapTy AbstractTypeMap;
816     
817     /// ValueMapLock - Mutex for this map.
818     sys::SmartMutex<true> ValueMapLock;
819
820   public:
821     // NOTE: This function is not locked.  It is the caller's responsibility
822     // to enforce proper synchronization.
823     typename MapTy::iterator map_end() { return Map.end(); }
824     
825     /// InsertOrGetItem - Return an iterator for the specified element.
826     /// If the element exists in the map, the returned iterator points to the
827     /// entry and Exists=true.  If not, the iterator points to the newly
828     /// inserted entry and returns Exists=false.  Newly inserted entries have
829     /// I->second == 0, and should be filled in.
830     /// NOTE: This function is not locked.  It is the caller's responsibility
831     // to enforce proper synchronization.
832     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
833                                    &InsertVal,
834                                    bool &Exists) {
835       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
836       Exists = !IP.second;
837       return IP.first;
838     }
839     
840 private:
841     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
842       if (HasLargeKey) {
843         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
844         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
845                IMI->second->second == CP &&
846                "InverseMap corrupt!");
847         return IMI->second;
848       }
849       
850       typename MapTy::iterator I =
851         Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
852                         getValType(CP)));
853       if (I == Map.end() || I->second != CP) {
854         // FIXME: This should not use a linear scan.  If this gets to be a
855         // performance problem, someone should look at this.
856         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
857           /* empty */;
858       }
859       return I;
860     }
861     
862     ConstantClass* Create(const TypeClass *Ty, const ValType &V,
863                           typename MapTy::iterator I) {
864       ConstantClass* Result =
865         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
866
867       assert(Result->getType() == Ty && "Type specified is not correct!");
868       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
869
870       if (HasLargeKey)  // Remember the reverse mapping if needed.
871         InverseMap.insert(std::make_pair(Result, I));
872
873       // If the type of the constant is abstract, make sure that an entry
874       // exists for it in the AbstractTypeMap.
875       if (Ty->isAbstract()) {
876         typename AbstractTypeMapTy::iterator TI = 
877                                                  AbstractTypeMap.find(Ty);
878
879         if (TI == AbstractTypeMap.end()) {
880           // Add ourselves to the ATU list of the type.
881           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
882
883           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
884         }
885       }
886       
887       return Result;
888     }
889 public:
890     
891     /// getOrCreate - Return the specified constant from the map, creating it if
892     /// necessary.
893     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
894       sys::SmartScopedLock<true> Lock(ValueMapLock);
895       MapKey Lookup(Ty, V);
896       ConstantClass* Result = 0;
897       
898       typename MapTy::iterator I = Map.find(Lookup);
899       // Is it in the map?  
900       if (I != Map.end())
901         Result = static_cast<ConstantClass *>(I->second);
902         
903       if (!Result) {
904         // If no preexisting value, create one now...
905         Result = Create(Ty, V, I);
906       }
907         
908       return Result;
909     }
910
911     void remove(ConstantClass *CP) {
912       sys::SmartScopedLock<true> Lock(ValueMapLock);
913       typename MapTy::iterator I = FindExistingElement(CP);
914       assert(I != Map.end() && "Constant not found in constant table!");
915       assert(I->second == CP && "Didn't find correct element?");
916
917       if (HasLargeKey)  // Remember the reverse mapping if needed.
918         InverseMap.erase(CP);
919       
920       // Now that we found the entry, make sure this isn't the entry that
921       // the AbstractTypeMap points to.
922       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
923       if (Ty->isAbstract()) {
924         assert(AbstractTypeMap.count(Ty) &&
925                "Abstract type not in AbstractTypeMap?");
926         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
927         if (ATMEntryIt == I) {
928           // Yes, we are removing the representative entry for this type.
929           // See if there are any other entries of the same type.
930           typename MapTy::iterator TmpIt = ATMEntryIt;
931
932           // First check the entry before this one...
933           if (TmpIt != Map.begin()) {
934             --TmpIt;
935             if (TmpIt->first.first != Ty) // Not the same type, move back...
936               ++TmpIt;
937           }
938
939           // If we didn't find the same type, try to move forward...
940           if (TmpIt == ATMEntryIt) {
941             ++TmpIt;
942             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
943               --TmpIt;   // No entry afterwards with the same type
944           }
945
946           // If there is another entry in the map of the same abstract type,
947           // update the AbstractTypeMap entry now.
948           if (TmpIt != ATMEntryIt) {
949             ATMEntryIt = TmpIt;
950           } else {
951             // Otherwise, we are removing the last instance of this type
952             // from the table.  Remove from the ATM, and from user list.
953             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
954             AbstractTypeMap.erase(Ty);
955           }
956         }
957       }
958
959       Map.erase(I);
960     }
961
962     
963     /// MoveConstantToNewSlot - If we are about to change C to be the element
964     /// specified by I, update our internal data structures to reflect this
965     /// fact.
966     /// NOTE: This function is not locked. It is the responsibility of the
967     /// caller to enforce proper synchronization if using this method.
968     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
969       // First, remove the old location of the specified constant in the map.
970       typename MapTy::iterator OldI = FindExistingElement(C);
971       assert(OldI != Map.end() && "Constant not found in constant table!");
972       assert(OldI->second == C && "Didn't find correct element?");
973       
974       // If this constant is the representative element for its abstract type,
975       // update the AbstractTypeMap so that the representative element is I.
976       if (C->getType()->isAbstract()) {
977         typename AbstractTypeMapTy::iterator ATI =
978             AbstractTypeMap.find(C->getType());
979         assert(ATI != AbstractTypeMap.end() &&
980                "Abstract type not in AbstractTypeMap?");
981         if (ATI->second == OldI)
982           ATI->second = I;
983       }
984       
985       // Remove the old entry from the map.
986       Map.erase(OldI);
987       
988       // Update the inverse map so that we know that this constant is now
989       // located at descriptor I.
990       if (HasLargeKey) {
991         assert(I->second == C && "Bad inversemap entry!");
992         InverseMap[C] = I;
993       }
994     }
995     
996     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
997       sys::SmartScopedLock<true> Lock(ValueMapLock);
998       typename AbstractTypeMapTy::iterator I =
999         AbstractTypeMap.find(cast<Type>(OldTy));
1000
1001       assert(I != AbstractTypeMap.end() &&
1002              "Abstract type not in AbstractTypeMap?");
1003
1004       // Convert a constant at a time until the last one is gone.  The last one
1005       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1006       // eliminated eventually.
1007       do {
1008         ConvertConstantType<ConstantClass,
1009                             TypeClass>::convert(
1010                                 static_cast<ConstantClass *>(I->second->second),
1011                                                 cast<TypeClass>(NewTy));
1012
1013         I = AbstractTypeMap.find(cast<Type>(OldTy));
1014       } while (I != AbstractTypeMap.end());
1015     }
1016
1017     // If the type became concrete without being refined to any other existing
1018     // type, we just remove ourselves from the ATU list.
1019     void typeBecameConcrete(const DerivedType *AbsTy) {
1020       AbsTy->removeAbstractTypeUser(this);
1021     }
1022
1023     void dump() const {
1024       DOUT << "Constant.cpp: ValueMap\n";
1025     }
1026   };
1027 }
1028
1029 /// destroyConstant - Remove the constant from the constant table...
1030 ///
1031 void ConstantAggregateZero::destroyConstant() {
1032   // Implicitly locked.
1033   getType()->getContext().erase(this);
1034   destroyConstantImpl();
1035 }
1036
1037 /// destroyConstant - Remove the constant from the constant table...
1038 ///
1039 void ConstantArray::destroyConstant() {
1040   // Implicitly locked.
1041   getType()->getContext().erase(this);
1042   destroyConstantImpl();
1043 }
1044
1045 /// isString - This method returns true if the array is an array of i8, and 
1046 /// if the elements of the array are all ConstantInt's.
1047 bool ConstantArray::isString() const {
1048   // Check the element type for i8...
1049   if (getType()->getElementType() != Type::Int8Ty)
1050     return false;
1051   // Check the elements to make sure they are all integers, not constant
1052   // expressions.
1053   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1054     if (!isa<ConstantInt>(getOperand(i)))
1055       return false;
1056   return true;
1057 }
1058
1059 /// isCString - This method returns true if the array is a string (see
1060 /// isString) and it ends in a null byte \\0 and does not contains any other
1061 /// null bytes except its terminator.
1062 bool ConstantArray::isCString() const {
1063   // Check the element type for i8...
1064   if (getType()->getElementType() != Type::Int8Ty)
1065     return false;
1066
1067   // Last element must be a null.
1068   if (!getOperand(getNumOperands()-1)->isNullValue())
1069     return false;
1070   // Other elements must be non-null integers.
1071   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1072     if (!isa<ConstantInt>(getOperand(i)))
1073       return false;
1074     if (getOperand(i)->isNullValue())
1075       return false;
1076   }
1077   return true;
1078 }
1079
1080
1081 /// getAsString - If the sub-element type of this array is i8
1082 /// then this method converts the array to an std::string and returns it.
1083 /// Otherwise, it asserts out.
1084 ///
1085 std::string ConstantArray::getAsString() const {
1086   assert(isString() && "Not a string!");
1087   std::string Result;
1088   Result.reserve(getNumOperands());
1089   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1090     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1091   return Result;
1092 }
1093
1094
1095 //---- ConstantStruct::get() implementation...
1096 //
1097
1098 namespace llvm {
1099   template<>
1100   struct ConvertConstantType<ConstantStruct, StructType> {
1101     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1102       // Make everyone now use a constant of the new type...
1103       std::vector<Constant*> C;
1104       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1105         C.push_back(cast<Constant>(OldC->getOperand(i)));
1106       Constant *New = ConstantStruct::get(NewTy, C);
1107       assert(New != OldC && "Didn't replace constant??");
1108
1109       OldC->uncheckedReplaceAllUsesWith(New);
1110       OldC->destroyConstant();    // This constant is now dead, destroy it.
1111     }
1112   };
1113 }
1114
1115 typedef ValueMap<std::vector<Constant*>, StructType,
1116                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1117 static ManagedStatic<StructConstantsTy> StructConstants;
1118
1119 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1120   std::vector<Constant*> Elements;
1121   Elements.reserve(CS->getNumOperands());
1122   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1123     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1124   return Elements;
1125 }
1126
1127 Constant *ConstantStruct::get(const StructType *Ty,
1128                               const std::vector<Constant*> &V) {
1129   // Create a ConstantAggregateZero value if all elements are zeros...
1130   for (unsigned i = 0, e = V.size(); i != e; ++i)
1131     if (!V[i]->isNullValue())
1132       // Implicitly locked.
1133       return StructConstants->getOrCreate(Ty, V);
1134
1135   return Ty->getContext().getConstantAggregateZero(Ty);
1136 }
1137
1138 // destroyConstant - Remove the constant from the constant table...
1139 //
1140 void ConstantStruct::destroyConstant() {
1141   // Implicitly locked.
1142   StructConstants->remove(this);
1143   destroyConstantImpl();
1144 }
1145
1146 //---- ConstantVector::get() implementation...
1147 //
1148 namespace llvm {
1149   template<>
1150   struct ConvertConstantType<ConstantVector, VectorType> {
1151     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1152       // Make everyone now use a constant of the new type...
1153       std::vector<Constant*> C;
1154       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1155         C.push_back(cast<Constant>(OldC->getOperand(i)));
1156       Constant *New = ConstantVector::get(NewTy, C);
1157       assert(New != OldC && "Didn't replace constant??");
1158       OldC->uncheckedReplaceAllUsesWith(New);
1159       OldC->destroyConstant();    // This constant is now dead, destroy it.
1160     }
1161   };
1162 }
1163
1164 static std::vector<Constant*> getValType(ConstantVector *CP) {
1165   std::vector<Constant*> Elements;
1166   Elements.reserve(CP->getNumOperands());
1167   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1168     Elements.push_back(CP->getOperand(i));
1169   return Elements;
1170 }
1171
1172 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1173                               ConstantVector> > VectorConstants;
1174
1175 Constant *ConstantVector::get(const VectorType *Ty,
1176                               const std::vector<Constant*> &V) {
1177   assert(!V.empty() && "Vectors can't be empty");
1178   // If this is an all-undef or alll-zero vector, return a
1179   // ConstantAggregateZero or UndefValue.
1180   Constant *C = V[0];
1181   bool isZero = C->isNullValue();
1182   bool isUndef = isa<UndefValue>(C);
1183
1184   if (isZero || isUndef) {
1185     for (unsigned i = 1, e = V.size(); i != e; ++i)
1186       if (V[i] != C) {
1187         isZero = isUndef = false;
1188         break;
1189       }
1190   }
1191   
1192   if (isZero)
1193     return Ty->getContext().getConstantAggregateZero(Ty);
1194   if (isUndef)
1195     return UndefValue::get(Ty);
1196     
1197   // Implicitly locked.
1198   return VectorConstants->getOrCreate(Ty, V);
1199 }
1200
1201 // destroyConstant - Remove the constant from the constant table...
1202 //
1203 void ConstantVector::destroyConstant() {
1204   // Implicitly locked.
1205   VectorConstants->remove(this);
1206   destroyConstantImpl();
1207 }
1208
1209 /// This function will return true iff every element in this vector constant
1210 /// is set to all ones.
1211 /// @returns true iff this constant's emements are all set to all ones.
1212 /// @brief Determine if the value is all ones.
1213 bool ConstantVector::isAllOnesValue() const {
1214   // Check out first element.
1215   const Constant *Elt = getOperand(0);
1216   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1217   if (!CI || !CI->isAllOnesValue()) return false;
1218   // Then make sure all remaining elements point to the same value.
1219   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1220     if (getOperand(I) != Elt) return false;
1221   }
1222   return true;
1223 }
1224
1225 /// getSplatValue - If this is a splat constant, where all of the
1226 /// elements have the same value, return that value. Otherwise return null.
1227 Constant *ConstantVector::getSplatValue() {
1228   // Check out first element.
1229   Constant *Elt = getOperand(0);
1230   // Then make sure all remaining elements point to the same value.
1231   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1232     if (getOperand(I) != Elt) return 0;
1233   return Elt;
1234 }
1235
1236 //---- ConstantPointerNull::get() implementation...
1237 //
1238
1239 namespace llvm {
1240   // ConstantPointerNull does not take extra "value" argument...
1241   template<class ValType>
1242   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1243     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1244       return new ConstantPointerNull(Ty);
1245     }
1246   };
1247
1248   template<>
1249   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1250     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1251       // Make everyone now use a constant of the new type...
1252       Constant *New = ConstantPointerNull::get(NewTy);
1253       assert(New != OldC && "Didn't replace constant??");
1254       OldC->uncheckedReplaceAllUsesWith(New);
1255       OldC->destroyConstant();     // This constant is now dead, destroy it.
1256     }
1257   };
1258 }
1259
1260 static ManagedStatic<ValueMap<char, PointerType, 
1261                               ConstantPointerNull> > NullPtrConstants;
1262
1263 static char getValType(ConstantPointerNull *) {
1264   return 0;
1265 }
1266
1267
1268 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1269   // Implicitly locked.
1270   return NullPtrConstants->getOrCreate(Ty, 0);
1271 }
1272
1273 // destroyConstant - Remove the constant from the constant table...
1274 //
1275 void ConstantPointerNull::destroyConstant() {
1276   // Implicitly locked.
1277   NullPtrConstants->remove(this);
1278   destroyConstantImpl();
1279 }
1280
1281
1282 //---- UndefValue::get() implementation...
1283 //
1284
1285 namespace llvm {
1286   // UndefValue does not take extra "value" argument...
1287   template<class ValType>
1288   struct ConstantCreator<UndefValue, Type, ValType> {
1289     static UndefValue *create(const Type *Ty, const ValType &V) {
1290       return new UndefValue(Ty);
1291     }
1292   };
1293
1294   template<>
1295   struct ConvertConstantType<UndefValue, Type> {
1296     static void convert(UndefValue *OldC, const Type *NewTy) {
1297       // Make everyone now use a constant of the new type.
1298       Constant *New = UndefValue::get(NewTy);
1299       assert(New != OldC && "Didn't replace constant??");
1300       OldC->uncheckedReplaceAllUsesWith(New);
1301       OldC->destroyConstant();     // This constant is now dead, destroy it.
1302     }
1303   };
1304 }
1305
1306 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1307
1308 static char getValType(UndefValue *) {
1309   return 0;
1310 }
1311
1312
1313 UndefValue *UndefValue::get(const Type *Ty) {
1314   // Implicitly locked.
1315   return UndefValueConstants->getOrCreate(Ty, 0);
1316 }
1317
1318 // destroyConstant - Remove the constant from the constant table.
1319 //
1320 void UndefValue::destroyConstant() {
1321   // Implicitly locked.
1322   UndefValueConstants->remove(this);
1323   destroyConstantImpl();
1324 }
1325
1326 //---- MDString::get() implementation
1327 //
1328
1329 MDString::MDString(const char *begin, const char *end)
1330   : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1331     StrBegin(begin), StrEnd(end) {}
1332
1333 void MDString::destroyConstant() {
1334   getType()->getContext().erase(this);
1335   destroyConstantImpl();
1336 }
1337
1338 //---- MDNode::get() implementation
1339 //
1340
1341 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1342   : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1343   for (unsigned i = 0; i != NumVals; ++i)
1344     Node.push_back(ElementVH(Vals[i], this));
1345 }
1346
1347 void MDNode::Profile(FoldingSetNodeID &ID) const {
1348   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1349     ID.AddPointer(*I);
1350 }
1351
1352 void MDNode::destroyConstant() {
1353   getType()->getContext().erase(this);
1354   destroyConstantImpl();
1355 }
1356
1357 //---- ConstantExpr::get() implementations...
1358 //
1359
1360 namespace {
1361
1362 struct ExprMapKeyType {
1363   typedef SmallVector<unsigned, 4> IndexList;
1364
1365   ExprMapKeyType(unsigned opc,
1366       const std::vector<Constant*> &ops,
1367       unsigned short pred = 0,
1368       const IndexList &inds = IndexList())
1369         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1370   uint16_t opcode;
1371   uint16_t predicate;
1372   std::vector<Constant*> operands;
1373   IndexList indices;
1374   bool operator==(const ExprMapKeyType& that) const {
1375     return this->opcode == that.opcode &&
1376            this->predicate == that.predicate &&
1377            this->operands == that.operands &&
1378            this->indices == that.indices;
1379   }
1380   bool operator<(const ExprMapKeyType & that) const {
1381     return this->opcode < that.opcode ||
1382       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1383       (this->opcode == that.opcode && this->predicate == that.predicate &&
1384        this->operands < that.operands) ||
1385       (this->opcode == that.opcode && this->predicate == that.predicate &&
1386        this->operands == that.operands && this->indices < that.indices);
1387   }
1388
1389   bool operator!=(const ExprMapKeyType& that) const {
1390     return !(*this == that);
1391   }
1392 };
1393
1394 }
1395
1396 namespace llvm {
1397   template<>
1398   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1399     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1400         unsigned short pred = 0) {
1401       if (Instruction::isCast(V.opcode))
1402         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1403       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1404            V.opcode < Instruction::BinaryOpsEnd))
1405         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1406       if (V.opcode == Instruction::Select)
1407         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1408                                       V.operands[2]);
1409       if (V.opcode == Instruction::ExtractElement)
1410         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1411       if (V.opcode == Instruction::InsertElement)
1412         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1413                                              V.operands[2]);
1414       if (V.opcode == Instruction::ShuffleVector)
1415         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1416                                              V.operands[2]);
1417       if (V.opcode == Instruction::InsertValue)
1418         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1419                                            V.indices, Ty);
1420       if (V.opcode == Instruction::ExtractValue)
1421         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1422       if (V.opcode == Instruction::GetElementPtr) {
1423         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1424         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1425       }
1426
1427       // The compare instructions are weird. We have to encode the predicate
1428       // value and it is combined with the instruction opcode by multiplying
1429       // the opcode by one hundred. We must decode this to get the predicate.
1430       if (V.opcode == Instruction::ICmp)
1431         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1432                                        V.operands[0], V.operands[1]);
1433       if (V.opcode == Instruction::FCmp) 
1434         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1435                                        V.operands[0], V.operands[1]);
1436       llvm_unreachable("Invalid ConstantExpr!");
1437       return 0;
1438     }
1439   };
1440
1441   template<>
1442   struct ConvertConstantType<ConstantExpr, Type> {
1443     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1444       Constant *New;
1445       switch (OldC->getOpcode()) {
1446       case Instruction::Trunc:
1447       case Instruction::ZExt:
1448       case Instruction::SExt:
1449       case Instruction::FPTrunc:
1450       case Instruction::FPExt:
1451       case Instruction::UIToFP:
1452       case Instruction::SIToFP:
1453       case Instruction::FPToUI:
1454       case Instruction::FPToSI:
1455       case Instruction::PtrToInt:
1456       case Instruction::IntToPtr:
1457       case Instruction::BitCast:
1458         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1459                                     NewTy);
1460         break;
1461       case Instruction::Select:
1462         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1463                                         OldC->getOperand(1),
1464                                         OldC->getOperand(2));
1465         break;
1466       default:
1467         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1468                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1469         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1470                                   OldC->getOperand(1));
1471         break;
1472       case Instruction::GetElementPtr:
1473         // Make everyone now use a constant of the new type...
1474         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1475         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1476                                                &Idx[0], Idx.size());
1477         break;
1478       }
1479
1480       assert(New != OldC && "Didn't replace constant??");
1481       OldC->uncheckedReplaceAllUsesWith(New);
1482       OldC->destroyConstant();    // This constant is now dead, destroy it.
1483     }
1484   };
1485 } // end namespace llvm
1486
1487
1488 static ExprMapKeyType getValType(ConstantExpr *CE) {
1489   std::vector<Constant*> Operands;
1490   Operands.reserve(CE->getNumOperands());
1491   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1492     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1493   return ExprMapKeyType(CE->getOpcode(), Operands, 
1494       CE->isCompare() ? CE->getPredicate() : 0,
1495       CE->hasIndices() ?
1496         CE->getIndices() : SmallVector<unsigned, 4>());
1497 }
1498
1499 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1500                               ConstantExpr> > ExprConstants;
1501
1502 /// This is a utility function to handle folding of casts and lookup of the
1503 /// cast in the ExprConstants map. It is used by the various get* methods below.
1504 static inline Constant *getFoldedCast(
1505   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1506   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1507   // Fold a few common cases
1508   if (Constant *FC = 
1509                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1510     return FC;
1511
1512   // Look up the constant in the table first to ensure uniqueness
1513   std::vector<Constant*> argVec(1, C);
1514   ExprMapKeyType Key(opc, argVec);
1515   
1516   // Implicitly locked.
1517   return ExprConstants->getOrCreate(Ty, Key);
1518 }
1519  
1520 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1521   Instruction::CastOps opc = Instruction::CastOps(oc);
1522   assert(Instruction::isCast(opc) && "opcode out of range");
1523   assert(C && Ty && "Null arguments to getCast");
1524   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1525
1526   switch (opc) {
1527     default:
1528       llvm_unreachable("Invalid cast opcode");
1529       break;
1530     case Instruction::Trunc:    return getTrunc(C, Ty);
1531     case Instruction::ZExt:     return getZExt(C, Ty);
1532     case Instruction::SExt:     return getSExt(C, Ty);
1533     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1534     case Instruction::FPExt:    return getFPExtend(C, Ty);
1535     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1536     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1537     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1538     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1539     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1540     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1541     case Instruction::BitCast:  return getBitCast(C, Ty);
1542   }
1543   return 0;
1544
1545
1546 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1547   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1548     return getCast(Instruction::BitCast, C, Ty);
1549   return getCast(Instruction::ZExt, C, Ty);
1550 }
1551
1552 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1553   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1554     return getCast(Instruction::BitCast, C, Ty);
1555   return getCast(Instruction::SExt, C, Ty);
1556 }
1557
1558 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1559   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1560     return getCast(Instruction::BitCast, C, Ty);
1561   return getCast(Instruction::Trunc, C, Ty);
1562 }
1563
1564 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1565   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1566   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1567
1568   if (Ty->isInteger())
1569     return getCast(Instruction::PtrToInt, S, Ty);
1570   return getCast(Instruction::BitCast, S, Ty);
1571 }
1572
1573 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1574                                        bool isSigned) {
1575   assert(C->getType()->isIntOrIntVector() &&
1576          Ty->isIntOrIntVector() && "Invalid cast");
1577   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1578   unsigned DstBits = Ty->getScalarSizeInBits();
1579   Instruction::CastOps opcode =
1580     (SrcBits == DstBits ? Instruction::BitCast :
1581      (SrcBits > DstBits ? Instruction::Trunc :
1582       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1583   return getCast(opcode, C, Ty);
1584 }
1585
1586 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1587   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1588          "Invalid cast");
1589   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1590   unsigned DstBits = Ty->getScalarSizeInBits();
1591   if (SrcBits == DstBits)
1592     return C; // Avoid a useless cast
1593   Instruction::CastOps opcode =
1594      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1595   return getCast(opcode, C, Ty);
1596 }
1597
1598 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1599 #ifndef NDEBUG
1600   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1601   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1602 #endif
1603   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1604   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1605   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1606   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1607          "SrcTy must be larger than DestTy for Trunc!");
1608
1609   return getFoldedCast(Instruction::Trunc, C, Ty);
1610 }
1611
1612 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1613 #ifndef NDEBUG
1614   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1615   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1616 #endif
1617   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1618   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1619   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1620   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1621          "SrcTy must be smaller than DestTy for SExt!");
1622
1623   return getFoldedCast(Instruction::SExt, C, Ty);
1624 }
1625
1626 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1627 #ifndef NDEBUG
1628   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1629   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1630 #endif
1631   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1632   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1633   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1634   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1635          "SrcTy must be smaller than DestTy for ZExt!");
1636
1637   return getFoldedCast(Instruction::ZExt, C, Ty);
1638 }
1639
1640 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1641 #ifndef NDEBUG
1642   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1643   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1644 #endif
1645   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1646   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1647          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1648          "This is an illegal floating point truncation!");
1649   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1650 }
1651
1652 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1653 #ifndef NDEBUG
1654   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1655   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1656 #endif
1657   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1658   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1659          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1660          "This is an illegal floating point extension!");
1661   return getFoldedCast(Instruction::FPExt, C, Ty);
1662 }
1663
1664 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1665 #ifndef NDEBUG
1666   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1667   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1668 #endif
1669   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1670   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1671          "This is an illegal uint to floating point cast!");
1672   return getFoldedCast(Instruction::UIToFP, C, Ty);
1673 }
1674
1675 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1676 #ifndef NDEBUG
1677   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1678   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1679 #endif
1680   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1681   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1682          "This is an illegal sint to floating point cast!");
1683   return getFoldedCast(Instruction::SIToFP, C, Ty);
1684 }
1685
1686 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1687 #ifndef NDEBUG
1688   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1690 #endif
1691   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1692   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1693          "This is an illegal floating point to uint cast!");
1694   return getFoldedCast(Instruction::FPToUI, C, Ty);
1695 }
1696
1697 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1698 #ifndef NDEBUG
1699   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1700   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1701 #endif
1702   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1703   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1704          "This is an illegal floating point to sint cast!");
1705   return getFoldedCast(Instruction::FPToSI, C, Ty);
1706 }
1707
1708 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1709   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1710   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1711   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1712 }
1713
1714 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1715   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1716   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1717   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1718 }
1719
1720 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1721   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1722   // can't cast pointers to anything but pointers.
1723 #ifndef NDEBUG
1724   const Type *SrcTy = C->getType();
1725   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1726          "BitCast cannot cast pointer to non-pointer and vice versa");
1727
1728   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1729   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1730   // destination bit widths are identical.
1731   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1732   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1733 #endif
1734   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1735   
1736   // It is common to ask for a bitcast of a value to its own type, handle this
1737   // speedily.
1738   if (C->getType() == DstTy) return C;
1739   
1740   return getFoldedCast(Instruction::BitCast, C, DstTy);
1741 }
1742
1743 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1744                               Constant *C1, Constant *C2) {
1745   // Check the operands for consistency first
1746   assert(Opcode >= Instruction::BinaryOpsBegin &&
1747          Opcode <  Instruction::BinaryOpsEnd   &&
1748          "Invalid opcode in binary constant expression");
1749   assert(C1->getType() == C2->getType() &&
1750          "Operand types in binary constant expression should match");
1751
1752   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1753     if (Constant *FC = ConstantFoldBinaryInstruction(
1754                                             getGlobalContext(), Opcode, C1, C2))
1755       return FC;          // Fold a few common cases...
1756
1757   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1758   ExprMapKeyType Key(Opcode, argVec);
1759   
1760   // Implicitly locked.
1761   return ExprConstants->getOrCreate(ReqTy, Key);
1762 }
1763
1764 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1765                                      Constant *C1, Constant *C2) {
1766   switch (predicate) {
1767     default: llvm_unreachable("Invalid CmpInst predicate");
1768     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1769     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1770     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1771     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1772     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1773     case CmpInst::FCMP_TRUE:
1774       return getFCmp(predicate, C1, C2);
1775
1776     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1777     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1778     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1779     case CmpInst::ICMP_SLE:
1780       return getICmp(predicate, C1, C2);
1781   }
1782 }
1783
1784 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1785   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1786   if (C1->getType()->isFPOrFPVector()) {
1787     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1788     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1789     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1790   }
1791 #ifndef NDEBUG
1792   switch (Opcode) {
1793   case Instruction::Add:
1794   case Instruction::Sub:
1795   case Instruction::Mul:
1796     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1797     assert(C1->getType()->isIntOrIntVector() &&
1798            "Tried to create an integer operation on a non-integer type!");
1799     break;
1800   case Instruction::FAdd:
1801   case Instruction::FSub:
1802   case Instruction::FMul:
1803     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1804     assert(C1->getType()->isFPOrFPVector() &&
1805            "Tried to create a floating-point operation on a "
1806            "non-floating-point type!");
1807     break;
1808   case Instruction::UDiv: 
1809   case Instruction::SDiv: 
1810     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1811     assert(C1->getType()->isIntOrIntVector() &&
1812            "Tried to create an arithmetic operation on a non-arithmetic type!");
1813     break;
1814   case Instruction::FDiv:
1815     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1816     assert(C1->getType()->isFPOrFPVector() &&
1817            "Tried to create an arithmetic operation on a non-arithmetic type!");
1818     break;
1819   case Instruction::URem: 
1820   case Instruction::SRem: 
1821     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1822     assert(C1->getType()->isIntOrIntVector() &&
1823            "Tried to create an arithmetic operation on a non-arithmetic type!");
1824     break;
1825   case Instruction::FRem:
1826     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1827     assert(C1->getType()->isFPOrFPVector() &&
1828            "Tried to create an arithmetic operation on a non-arithmetic type!");
1829     break;
1830   case Instruction::And:
1831   case Instruction::Or:
1832   case Instruction::Xor:
1833     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1834     assert(C1->getType()->isIntOrIntVector() &&
1835            "Tried to create a logical operation on a non-integral type!");
1836     break;
1837   case Instruction::Shl:
1838   case Instruction::LShr:
1839   case Instruction::AShr:
1840     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1841     assert(C1->getType()->isIntOrIntVector() &&
1842            "Tried to create a shift operation on a non-integer type!");
1843     break;
1844   default:
1845     break;
1846   }
1847 #endif
1848
1849   return getTy(C1->getType(), Opcode, C1, C2);
1850 }
1851
1852 Constant *ConstantExpr::getCompare(unsigned short pred, 
1853                             Constant *C1, Constant *C2) {
1854   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1855   return getCompareTy(pred, C1, C2);
1856 }
1857
1858 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1859                                     Constant *V1, Constant *V2) {
1860   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1861
1862   if (ReqTy == V1->getType())
1863     if (Constant *SC = ConstantFoldSelectInstruction(
1864                                                 getGlobalContext(), C, V1, V2))
1865       return SC;        // Fold common cases
1866
1867   std::vector<Constant*> argVec(3, C);
1868   argVec[1] = V1;
1869   argVec[2] = V2;
1870   ExprMapKeyType Key(Instruction::Select, argVec);
1871   
1872   // Implicitly locked.
1873   return ExprConstants->getOrCreate(ReqTy, Key);
1874 }
1875
1876 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1877                                            Value* const *Idxs,
1878                                            unsigned NumIdx) {
1879   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1880                                            Idxs+NumIdx) ==
1881          cast<PointerType>(ReqTy)->getElementType() &&
1882          "GEP indices invalid!");
1883
1884   if (Constant *FC = ConstantFoldGetElementPtr(
1885                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1886     return FC;          // Fold a few common cases...
1887
1888   assert(isa<PointerType>(C->getType()) &&
1889          "Non-pointer type for constant GetElementPtr expression");
1890   // Look up the constant in the table first to ensure uniqueness
1891   std::vector<Constant*> ArgVec;
1892   ArgVec.reserve(NumIdx+1);
1893   ArgVec.push_back(C);
1894   for (unsigned i = 0; i != NumIdx; ++i)
1895     ArgVec.push_back(cast<Constant>(Idxs[i]));
1896   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1897
1898   // Implicitly locked.
1899   return ExprConstants->getOrCreate(ReqTy, Key);
1900 }
1901
1902 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1903                                          unsigned NumIdx) {
1904   // Get the result type of the getelementptr!
1905   const Type *Ty = 
1906     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1907   assert(Ty && "GEP indices invalid!");
1908   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1909   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1910 }
1911
1912 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1913                                          unsigned NumIdx) {
1914   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1915 }
1916
1917
1918 Constant *
1919 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1920   assert(LHS->getType() == RHS->getType());
1921   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1922          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1923
1924   if (Constant *FC = ConstantFoldCompareInstruction(
1925                                              getGlobalContext(),pred, LHS, RHS))
1926     return FC;          // Fold a few common cases...
1927
1928   // Look up the constant in the table first to ensure uniqueness
1929   std::vector<Constant*> ArgVec;
1930   ArgVec.push_back(LHS);
1931   ArgVec.push_back(RHS);
1932   // Get the key type with both the opcode and predicate
1933   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1934
1935   // Implicitly locked.
1936   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1937 }
1938
1939 Constant *
1940 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1941   assert(LHS->getType() == RHS->getType());
1942   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1943
1944   if (Constant *FC = ConstantFoldCompareInstruction(
1945                                             getGlobalContext(), pred, LHS, RHS))
1946     return FC;          // Fold a few common cases...
1947
1948   // Look up the constant in the table first to ensure uniqueness
1949   std::vector<Constant*> ArgVec;
1950   ArgVec.push_back(LHS);
1951   ArgVec.push_back(RHS);
1952   // Get the key type with both the opcode and predicate
1953   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1954   
1955   // Implicitly locked.
1956   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1957 }
1958
1959 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1960                                             Constant *Idx) {
1961   if (Constant *FC = ConstantFoldExtractElementInstruction(
1962                                                   getGlobalContext(), Val, Idx))
1963     return FC;          // Fold a few common cases...
1964   // Look up the constant in the table first to ensure uniqueness
1965   std::vector<Constant*> ArgVec(1, Val);
1966   ArgVec.push_back(Idx);
1967   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1968   
1969   // Implicitly locked.
1970   return ExprConstants->getOrCreate(ReqTy, Key);
1971 }
1972
1973 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1974   assert(isa<VectorType>(Val->getType()) &&
1975          "Tried to create extractelement operation on non-vector type!");
1976   assert(Idx->getType() == Type::Int32Ty &&
1977          "Extractelement index must be i32 type!");
1978   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1979                              Val, Idx);
1980 }
1981
1982 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1983                                            Constant *Elt, Constant *Idx) {
1984   if (Constant *FC = ConstantFoldInsertElementInstruction(
1985                                             getGlobalContext(), Val, Elt, Idx))
1986     return FC;          // Fold a few common cases...
1987   // Look up the constant in the table first to ensure uniqueness
1988   std::vector<Constant*> ArgVec(1, Val);
1989   ArgVec.push_back(Elt);
1990   ArgVec.push_back(Idx);
1991   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1992   
1993   // Implicitly locked.
1994   return ExprConstants->getOrCreate(ReqTy, Key);
1995 }
1996
1997 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1998                                          Constant *Idx) {
1999   assert(isa<VectorType>(Val->getType()) &&
2000          "Tried to create insertelement operation on non-vector type!");
2001   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2002          && "Insertelement types must match!");
2003   assert(Idx->getType() == Type::Int32Ty &&
2004          "Insertelement index must be i32 type!");
2005   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2006 }
2007
2008 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2009                                            Constant *V2, Constant *Mask) {
2010   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2011                                               getGlobalContext(), V1, V2, Mask))
2012     return FC;          // Fold a few common cases...
2013   // Look up the constant in the table first to ensure uniqueness
2014   std::vector<Constant*> ArgVec(1, V1);
2015   ArgVec.push_back(V2);
2016   ArgVec.push_back(Mask);
2017   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2018   
2019   // Implicitly locked.
2020   return ExprConstants->getOrCreate(ReqTy, Key);
2021 }
2022
2023 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2024                                          Constant *Mask) {
2025   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2026          "Invalid shuffle vector constant expr operands!");
2027
2028   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2029   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2030   const Type *ShufTy = VectorType::get(EltTy, NElts);
2031   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2032 }
2033
2034 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2035                                          Constant *Val,
2036                                         const unsigned *Idxs, unsigned NumIdx) {
2037   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2038                                           Idxs+NumIdx) == Val->getType() &&
2039          "insertvalue indices invalid!");
2040   assert(Agg->getType() == ReqTy &&
2041          "insertvalue type invalid!");
2042   assert(Agg->getType()->isFirstClassType() &&
2043          "Non-first-class type for constant InsertValue expression");
2044   Constant *FC = ConstantFoldInsertValueInstruction(
2045                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
2046   assert(FC && "InsertValue constant expr couldn't be folded!");
2047   return FC;
2048 }
2049
2050 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2051                                      const unsigned *IdxList, unsigned NumIdx) {
2052   assert(Agg->getType()->isFirstClassType() &&
2053          "Tried to create insertelement operation on non-first-class type!");
2054
2055   const Type *ReqTy = Agg->getType();
2056 #ifndef NDEBUG
2057   const Type *ValTy =
2058     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2059 #endif
2060   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2061   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2062 }
2063
2064 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2065                                         const unsigned *Idxs, unsigned NumIdx) {
2066   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2067                                           Idxs+NumIdx) == ReqTy &&
2068          "extractvalue indices invalid!");
2069   assert(Agg->getType()->isFirstClassType() &&
2070          "Non-first-class type for constant extractvalue expression");
2071   Constant *FC = ConstantFoldExtractValueInstruction(
2072                                          getGlobalContext(), Agg, Idxs, NumIdx);
2073   assert(FC && "ExtractValue constant expr couldn't be folded!");
2074   return FC;
2075 }
2076
2077 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2078                                      const unsigned *IdxList, unsigned NumIdx) {
2079   assert(Agg->getType()->isFirstClassType() &&
2080          "Tried to create extractelement operation on non-first-class type!");
2081
2082   const Type *ReqTy =
2083     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2084   assert(ReqTy && "extractvalue indices invalid!");
2085   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2086 }
2087
2088 // destroyConstant - Remove the constant from the constant table...
2089 //
2090 void ConstantExpr::destroyConstant() {
2091   // Implicitly locked.
2092   ExprConstants->remove(this);
2093   destroyConstantImpl();
2094 }
2095
2096 const char *ConstantExpr::getOpcodeName() const {
2097   return Instruction::getOpcodeName(getOpcode());
2098 }
2099
2100 //===----------------------------------------------------------------------===//
2101 //                replaceUsesOfWithOnConstant implementations
2102
2103 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2104 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2105 /// etc.
2106 ///
2107 /// Note that we intentionally replace all uses of From with To here.  Consider
2108 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2109 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2110 /// single invocation handles all 1000 uses.  Handling them one at a time would
2111 /// work, but would be really slow because it would have to unique each updated
2112 /// array instance.
2113 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2114                                                 Use *U) {
2115   Constant *Replacement =
2116     getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2117  
2118   if (!Replacement) return;
2119  
2120   // Otherwise, I do need to replace this with an existing value.
2121   assert(Replacement != this && "I didn't contain From!");
2122   
2123   // Everyone using this now uses the replacement.
2124   uncheckedReplaceAllUsesWith(Replacement);
2125   
2126   // Delete the old constant!
2127   destroyConstant();
2128 }
2129
2130 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2131                                                  Use *U) {
2132   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2133   Constant *ToC = cast<Constant>(To);
2134
2135   unsigned OperandToUpdate = U-OperandList;
2136   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2137
2138   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2139   Lookup.first.first = getType();
2140   Lookup.second = this;
2141   std::vector<Constant*> &Values = Lookup.first.second;
2142   Values.reserve(getNumOperands());  // Build replacement struct.
2143   
2144   
2145   // Fill values with the modified operands of the constant struct.  Also, 
2146   // compute whether this turns into an all-zeros struct.
2147   bool isAllZeros = false;
2148   if (!ToC->isNullValue()) {
2149     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2150       Values.push_back(cast<Constant>(O->get()));
2151   } else {
2152     isAllZeros = true;
2153     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2154       Constant *Val = cast<Constant>(O->get());
2155       Values.push_back(Val);
2156       if (isAllZeros) isAllZeros = Val->isNullValue();
2157     }
2158   }
2159   Values[OperandToUpdate] = ToC;
2160   
2161   Constant *Replacement = 0;
2162   if (isAllZeros) {
2163     Replacement = getType()->getContext().getConstantAggregateZero(getType());
2164   } else {
2165     // Check to see if we have this array type already.
2166     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2167     bool Exists;
2168     StructConstantsTy::MapTy::iterator I =
2169       StructConstants->InsertOrGetItem(Lookup, Exists);
2170     
2171     if (Exists) {
2172       Replacement = I->second;
2173     } else {
2174       // Okay, the new shape doesn't exist in the system yet.  Instead of
2175       // creating a new constant struct, inserting it, replaceallusesof'ing the
2176       // old with the new, then deleting the old... just update the current one
2177       // in place!
2178       StructConstants->MoveConstantToNewSlot(this, I);
2179       
2180       // Update to the new value.
2181       setOperand(OperandToUpdate, ToC);
2182       return;
2183     }
2184   }
2185   
2186   assert(Replacement != this && "I didn't contain From!");
2187   
2188   // Everyone using this now uses the replacement.
2189   uncheckedReplaceAllUsesWith(Replacement);
2190   
2191   // Delete the old constant!
2192   destroyConstant();
2193 }
2194
2195 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2196                                                  Use *U) {
2197   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2198   
2199   std::vector<Constant*> Values;
2200   Values.reserve(getNumOperands());  // Build replacement array...
2201   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2202     Constant *Val = getOperand(i);
2203     if (Val == From) Val = cast<Constant>(To);
2204     Values.push_back(Val);
2205   }
2206   
2207   Constant *Replacement = ConstantVector::get(getType(), Values);
2208   assert(Replacement != this && "I didn't contain From!");
2209   
2210   // Everyone using this now uses the replacement.
2211   uncheckedReplaceAllUsesWith(Replacement);
2212   
2213   // Delete the old constant!
2214   destroyConstant();
2215 }
2216
2217 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2218                                                Use *U) {
2219   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2220   Constant *To = cast<Constant>(ToV);
2221   
2222   Constant *Replacement = 0;
2223   if (getOpcode() == Instruction::GetElementPtr) {
2224     SmallVector<Constant*, 8> Indices;
2225     Constant *Pointer = getOperand(0);
2226     Indices.reserve(getNumOperands()-1);
2227     if (Pointer == From) Pointer = To;
2228     
2229     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2230       Constant *Val = getOperand(i);
2231       if (Val == From) Val = To;
2232       Indices.push_back(Val);
2233     }
2234     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2235                                                  &Indices[0], Indices.size());
2236   } else if (getOpcode() == Instruction::ExtractValue) {
2237     Constant *Agg = getOperand(0);
2238     if (Agg == From) Agg = To;
2239     
2240     const SmallVector<unsigned, 4> &Indices = getIndices();
2241     Replacement = ConstantExpr::getExtractValue(Agg,
2242                                                 &Indices[0], Indices.size());
2243   } else if (getOpcode() == Instruction::InsertValue) {
2244     Constant *Agg = getOperand(0);
2245     Constant *Val = getOperand(1);
2246     if (Agg == From) Agg = To;
2247     if (Val == From) Val = To;
2248     
2249     const SmallVector<unsigned, 4> &Indices = getIndices();
2250     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2251                                                &Indices[0], Indices.size());
2252   } else if (isCast()) {
2253     assert(getOperand(0) == From && "Cast only has one use!");
2254     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2255   } else if (getOpcode() == Instruction::Select) {
2256     Constant *C1 = getOperand(0);
2257     Constant *C2 = getOperand(1);
2258     Constant *C3 = getOperand(2);
2259     if (C1 == From) C1 = To;
2260     if (C2 == From) C2 = To;
2261     if (C3 == From) C3 = To;
2262     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2263   } else if (getOpcode() == Instruction::ExtractElement) {
2264     Constant *C1 = getOperand(0);
2265     Constant *C2 = getOperand(1);
2266     if (C1 == From) C1 = To;
2267     if (C2 == From) C2 = To;
2268     Replacement = ConstantExpr::getExtractElement(C1, C2);
2269   } else if (getOpcode() == Instruction::InsertElement) {
2270     Constant *C1 = getOperand(0);
2271     Constant *C2 = getOperand(1);
2272     Constant *C3 = getOperand(1);
2273     if (C1 == From) C1 = To;
2274     if (C2 == From) C2 = To;
2275     if (C3 == From) C3 = To;
2276     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2277   } else if (getOpcode() == Instruction::ShuffleVector) {
2278     Constant *C1 = getOperand(0);
2279     Constant *C2 = getOperand(1);
2280     Constant *C3 = getOperand(2);
2281     if (C1 == From) C1 = To;
2282     if (C2 == From) C2 = To;
2283     if (C3 == From) C3 = To;
2284     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2285   } else if (isCompare()) {
2286     Constant *C1 = getOperand(0);
2287     Constant *C2 = getOperand(1);
2288     if (C1 == From) C1 = To;
2289     if (C2 == From) C2 = To;
2290     if (getOpcode() == Instruction::ICmp)
2291       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2292     else {
2293       assert(getOpcode() == Instruction::FCmp);
2294       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2295     }
2296   } else if (getNumOperands() == 2) {
2297     Constant *C1 = getOperand(0);
2298     Constant *C2 = getOperand(1);
2299     if (C1 == From) C1 = To;
2300     if (C2 == From) C2 = To;
2301     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2302   } else {
2303     llvm_unreachable("Unknown ConstantExpr type!");
2304     return;
2305   }
2306   
2307   assert(Replacement != this && "I didn't contain From!");
2308   
2309   // Everyone using this now uses the replacement.
2310   uncheckedReplaceAllUsesWith(Replacement);
2311   
2312   // Delete the old constant!
2313   destroyConstant();
2314 }
2315
2316 void MDNode::replaceElement(Value *From, Value *To) {
2317   SmallVector<Value*, 4> Values;
2318   Values.reserve(getNumElements());  // Build replacement array...
2319   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2320     Value *Val = getElement(i);
2321     if (Val == From) Val = To;
2322     Values.push_back(Val);
2323   }
2324
2325   MDNode *Replacement =
2326     getType()->getContext().getMDNode(&Values[0], Values.size());
2327   assert(Replacement != this && "I didn't contain From!");
2328
2329   uncheckedReplaceAllUsesWith(Replacement);
2330
2331   destroyConstant();
2332 }