74c31151ac20e05041c80fa659e5437a76ef12b3
[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
1100 }
1101
1102 // destroyConstant - Remove the constant from the constant table...
1103 //
1104 void ConstantStruct::destroyConstant() {
1105   // Implicitly locked.
1106   getType()->getContext().erase(this);
1107   destroyConstantImpl();
1108 }
1109
1110 // destroyConstant - Remove the constant from the constant table...
1111 //
1112 void ConstantVector::destroyConstant() {
1113   // Implicitly locked.
1114   getType()->getContext().erase(this);
1115   destroyConstantImpl();
1116 }
1117
1118 /// This function will return true iff every element in this vector constant
1119 /// is set to all ones.
1120 /// @returns true iff this constant's emements are all set to all ones.
1121 /// @brief Determine if the value is all ones.
1122 bool ConstantVector::isAllOnesValue() const {
1123   // Check out first element.
1124   const Constant *Elt = getOperand(0);
1125   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1126   if (!CI || !CI->isAllOnesValue()) return false;
1127   // Then make sure all remaining elements point to the same value.
1128   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1129     if (getOperand(I) != Elt) return false;
1130   }
1131   return true;
1132 }
1133
1134 /// getSplatValue - If this is a splat constant, where all of the
1135 /// elements have the same value, return that value. Otherwise return null.
1136 Constant *ConstantVector::getSplatValue() {
1137   // Check out first element.
1138   Constant *Elt = getOperand(0);
1139   // Then make sure all remaining elements point to the same value.
1140   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1141     if (getOperand(I) != Elt) return 0;
1142   return Elt;
1143 }
1144
1145 //---- ConstantPointerNull::get() implementation...
1146 //
1147
1148 namespace llvm {
1149   // ConstantPointerNull does not take extra "value" argument...
1150   template<class ValType>
1151   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1152     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1153       return new ConstantPointerNull(Ty);
1154     }
1155   };
1156
1157   template<>
1158   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1159     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1160       // Make everyone now use a constant of the new type...
1161       Constant *New = ConstantPointerNull::get(NewTy);
1162       assert(New != OldC && "Didn't replace constant??");
1163       OldC->uncheckedReplaceAllUsesWith(New);
1164       OldC->destroyConstant();     // This constant is now dead, destroy it.
1165     }
1166   };
1167 }
1168
1169 static ManagedStatic<ValueMap<char, PointerType, 
1170                               ConstantPointerNull> > NullPtrConstants;
1171
1172 static char getValType(ConstantPointerNull *) {
1173   return 0;
1174 }
1175
1176
1177 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1178   // Implicitly locked.
1179   return NullPtrConstants->getOrCreate(Ty, 0);
1180 }
1181
1182 // destroyConstant - Remove the constant from the constant table...
1183 //
1184 void ConstantPointerNull::destroyConstant() {
1185   // Implicitly locked.
1186   NullPtrConstants->remove(this);
1187   destroyConstantImpl();
1188 }
1189
1190
1191 //---- UndefValue::get() implementation...
1192 //
1193
1194 namespace llvm {
1195   // UndefValue does not take extra "value" argument...
1196   template<class ValType>
1197   struct ConstantCreator<UndefValue, Type, ValType> {
1198     static UndefValue *create(const Type *Ty, const ValType &V) {
1199       return new UndefValue(Ty);
1200     }
1201   };
1202
1203   template<>
1204   struct ConvertConstantType<UndefValue, Type> {
1205     static void convert(UndefValue *OldC, const Type *NewTy) {
1206       // Make everyone now use a constant of the new type.
1207       Constant *New = UndefValue::get(NewTy);
1208       assert(New != OldC && "Didn't replace constant??");
1209       OldC->uncheckedReplaceAllUsesWith(New);
1210       OldC->destroyConstant();     // This constant is now dead, destroy it.
1211     }
1212   };
1213 }
1214
1215 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1216
1217 static char getValType(UndefValue *) {
1218   return 0;
1219 }
1220
1221
1222 UndefValue *UndefValue::get(const Type *Ty) {
1223   // Implicitly locked.
1224   return UndefValueConstants->getOrCreate(Ty, 0);
1225 }
1226
1227 // destroyConstant - Remove the constant from the constant table.
1228 //
1229 void UndefValue::destroyConstant() {
1230   // Implicitly locked.
1231   UndefValueConstants->remove(this);
1232   destroyConstantImpl();
1233 }
1234
1235 //---- MDNode::get() implementation
1236 //
1237
1238 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1239   : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1240   for (unsigned i = 0; i != NumVals; ++i)
1241     Node.push_back(WeakVH(Vals[i]));
1242 }
1243
1244 void MDNode::Profile(FoldingSetNodeID &ID) const {
1245   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1246     ID.AddPointer(*I);
1247 }
1248
1249 //---- ConstantExpr::get() implementations...
1250 //
1251
1252 namespace {
1253
1254 struct ExprMapKeyType {
1255   typedef SmallVector<unsigned, 4> IndexList;
1256
1257   ExprMapKeyType(unsigned opc,
1258       const std::vector<Constant*> &ops,
1259       unsigned short pred = 0,
1260       const IndexList &inds = IndexList())
1261         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1262   uint16_t opcode;
1263   uint16_t predicate;
1264   std::vector<Constant*> operands;
1265   IndexList indices;
1266   bool operator==(const ExprMapKeyType& that) const {
1267     return this->opcode == that.opcode &&
1268            this->predicate == that.predicate &&
1269            this->operands == that.operands &&
1270            this->indices == that.indices;
1271   }
1272   bool operator<(const ExprMapKeyType & that) const {
1273     return this->opcode < that.opcode ||
1274       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1275       (this->opcode == that.opcode && this->predicate == that.predicate &&
1276        this->operands < that.operands) ||
1277       (this->opcode == that.opcode && this->predicate == that.predicate &&
1278        this->operands == that.operands && this->indices < that.indices);
1279   }
1280
1281   bool operator!=(const ExprMapKeyType& that) const {
1282     return !(*this == that);
1283   }
1284 };
1285
1286 }
1287
1288 namespace llvm {
1289   template<>
1290   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1291     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1292         unsigned short pred = 0) {
1293       if (Instruction::isCast(V.opcode))
1294         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1295       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1296            V.opcode < Instruction::BinaryOpsEnd))
1297         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1298       if (V.opcode == Instruction::Select)
1299         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1300                                       V.operands[2]);
1301       if (V.opcode == Instruction::ExtractElement)
1302         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1303       if (V.opcode == Instruction::InsertElement)
1304         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1305                                              V.operands[2]);
1306       if (V.opcode == Instruction::ShuffleVector)
1307         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1308                                              V.operands[2]);
1309       if (V.opcode == Instruction::InsertValue)
1310         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1311                                            V.indices, Ty);
1312       if (V.opcode == Instruction::ExtractValue)
1313         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1314       if (V.opcode == Instruction::GetElementPtr) {
1315         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1316         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1317       }
1318
1319       // The compare instructions are weird. We have to encode the predicate
1320       // value and it is combined with the instruction opcode by multiplying
1321       // the opcode by one hundred. We must decode this to get the predicate.
1322       if (V.opcode == Instruction::ICmp)
1323         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1324                                        V.operands[0], V.operands[1]);
1325       if (V.opcode == Instruction::FCmp) 
1326         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1327                                        V.operands[0], V.operands[1]);
1328       llvm_unreachable("Invalid ConstantExpr!");
1329       return 0;
1330     }
1331   };
1332
1333   template<>
1334   struct ConvertConstantType<ConstantExpr, Type> {
1335     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1336       Constant *New;
1337       switch (OldC->getOpcode()) {
1338       case Instruction::Trunc:
1339       case Instruction::ZExt:
1340       case Instruction::SExt:
1341       case Instruction::FPTrunc:
1342       case Instruction::FPExt:
1343       case Instruction::UIToFP:
1344       case Instruction::SIToFP:
1345       case Instruction::FPToUI:
1346       case Instruction::FPToSI:
1347       case Instruction::PtrToInt:
1348       case Instruction::IntToPtr:
1349       case Instruction::BitCast:
1350         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1351                                     NewTy);
1352         break;
1353       case Instruction::Select:
1354         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1355                                         OldC->getOperand(1),
1356                                         OldC->getOperand(2));
1357         break;
1358       default:
1359         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1360                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1361         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1362                                   OldC->getOperand(1));
1363         break;
1364       case Instruction::GetElementPtr:
1365         // Make everyone now use a constant of the new type...
1366         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1367         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1368                                                &Idx[0], Idx.size());
1369         break;
1370       }
1371
1372       assert(New != OldC && "Didn't replace constant??");
1373       OldC->uncheckedReplaceAllUsesWith(New);
1374       OldC->destroyConstant();    // This constant is now dead, destroy it.
1375     }
1376   };
1377 } // end namespace llvm
1378
1379
1380 static ExprMapKeyType getValType(ConstantExpr *CE) {
1381   std::vector<Constant*> Operands;
1382   Operands.reserve(CE->getNumOperands());
1383   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1384     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1385   return ExprMapKeyType(CE->getOpcode(), Operands, 
1386       CE->isCompare() ? CE->getPredicate() : 0,
1387       CE->hasIndices() ?
1388         CE->getIndices() : SmallVector<unsigned, 4>());
1389 }
1390
1391 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1392                               ConstantExpr> > ExprConstants;
1393
1394 /// This is a utility function to handle folding of casts and lookup of the
1395 /// cast in the ExprConstants map. It is used by the various get* methods below.
1396 static inline Constant *getFoldedCast(
1397   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1398   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1399   // Fold a few common cases
1400   if (Constant *FC = 
1401                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1402     return FC;
1403
1404   // Look up the constant in the table first to ensure uniqueness
1405   std::vector<Constant*> argVec(1, C);
1406   ExprMapKeyType Key(opc, argVec);
1407   
1408   // Implicitly locked.
1409   return ExprConstants->getOrCreate(Ty, Key);
1410 }
1411  
1412 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1413   Instruction::CastOps opc = Instruction::CastOps(oc);
1414   assert(Instruction::isCast(opc) && "opcode out of range");
1415   assert(C && Ty && "Null arguments to getCast");
1416   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1417
1418   switch (opc) {
1419     default:
1420       llvm_unreachable("Invalid cast opcode");
1421       break;
1422     case Instruction::Trunc:    return getTrunc(C, Ty);
1423     case Instruction::ZExt:     return getZExt(C, Ty);
1424     case Instruction::SExt:     return getSExt(C, Ty);
1425     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1426     case Instruction::FPExt:    return getFPExtend(C, Ty);
1427     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1428     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1429     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1430     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1431     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1432     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1433     case Instruction::BitCast:  return getBitCast(C, Ty);
1434   }
1435   return 0;
1436
1437
1438 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1439   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1440     return getCast(Instruction::BitCast, C, Ty);
1441   return getCast(Instruction::ZExt, C, Ty);
1442 }
1443
1444 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1445   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1446     return getCast(Instruction::BitCast, C, Ty);
1447   return getCast(Instruction::SExt, C, Ty);
1448 }
1449
1450 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1451   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1452     return getCast(Instruction::BitCast, C, Ty);
1453   return getCast(Instruction::Trunc, C, Ty);
1454 }
1455
1456 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1457   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1458   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1459
1460   if (Ty->isInteger())
1461     return getCast(Instruction::PtrToInt, S, Ty);
1462   return getCast(Instruction::BitCast, S, Ty);
1463 }
1464
1465 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1466                                        bool isSigned) {
1467   assert(C->getType()->isIntOrIntVector() &&
1468          Ty->isIntOrIntVector() && "Invalid cast");
1469   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1470   unsigned DstBits = Ty->getScalarSizeInBits();
1471   Instruction::CastOps opcode =
1472     (SrcBits == DstBits ? Instruction::BitCast :
1473      (SrcBits > DstBits ? Instruction::Trunc :
1474       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1475   return getCast(opcode, C, Ty);
1476 }
1477
1478 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1479   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1480          "Invalid cast");
1481   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1482   unsigned DstBits = Ty->getScalarSizeInBits();
1483   if (SrcBits == DstBits)
1484     return C; // Avoid a useless cast
1485   Instruction::CastOps opcode =
1486      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1487   return getCast(opcode, C, Ty);
1488 }
1489
1490 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1491 #ifndef NDEBUG
1492   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1493   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1494 #endif
1495   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1496   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1497   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1498   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1499          "SrcTy must be larger than DestTy for Trunc!");
1500
1501   return getFoldedCast(Instruction::Trunc, C, Ty);
1502 }
1503
1504 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1505 #ifndef NDEBUG
1506   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1507   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1508 #endif
1509   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1510   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1511   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1512   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1513          "SrcTy must be smaller than DestTy for SExt!");
1514
1515   return getFoldedCast(Instruction::SExt, C, Ty);
1516 }
1517
1518 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1519 #ifndef NDEBUG
1520   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1521   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1522 #endif
1523   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1524   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1525   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1526   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1527          "SrcTy must be smaller than DestTy for ZExt!");
1528
1529   return getFoldedCast(Instruction::ZExt, C, Ty);
1530 }
1531
1532 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1533 #ifndef NDEBUG
1534   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1535   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1536 #endif
1537   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1538   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1539          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1540          "This is an illegal floating point truncation!");
1541   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1542 }
1543
1544 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1545 #ifndef NDEBUG
1546   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1547   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1548 #endif
1549   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1550   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1551          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1552          "This is an illegal floating point extension!");
1553   return getFoldedCast(Instruction::FPExt, C, Ty);
1554 }
1555
1556 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1557 #ifndef NDEBUG
1558   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1560 #endif
1561   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1562   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1563          "This is an illegal uint to floating point cast!");
1564   return getFoldedCast(Instruction::UIToFP, C, Ty);
1565 }
1566
1567 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1568 #ifndef NDEBUG
1569   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1570   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1571 #endif
1572   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1573   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1574          "This is an illegal sint to floating point cast!");
1575   return getFoldedCast(Instruction::SIToFP, C, Ty);
1576 }
1577
1578 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1579 #ifndef NDEBUG
1580   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1581   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1582 #endif
1583   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1584   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1585          "This is an illegal floating point to uint cast!");
1586   return getFoldedCast(Instruction::FPToUI, C, Ty);
1587 }
1588
1589 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1590 #ifndef NDEBUG
1591   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1593 #endif
1594   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1595   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1596          "This is an illegal floating point to sint cast!");
1597   return getFoldedCast(Instruction::FPToSI, C, Ty);
1598 }
1599
1600 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1601   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1602   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1603   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1604 }
1605
1606 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1607   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1608   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1609   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1610 }
1611
1612 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1613   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1614   // can't cast pointers to anything but pointers.
1615 #ifndef NDEBUG
1616   const Type *SrcTy = C->getType();
1617   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1618          "BitCast cannot cast pointer to non-pointer and vice versa");
1619
1620   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1621   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1622   // destination bit widths are identical.
1623   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1624   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1625 #endif
1626   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1627   
1628   // It is common to ask for a bitcast of a value to its own type, handle this
1629   // speedily.
1630   if (C->getType() == DstTy) return C;
1631   
1632   return getFoldedCast(Instruction::BitCast, C, DstTy);
1633 }
1634
1635 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1636                               Constant *C1, Constant *C2) {
1637   // Check the operands for consistency first
1638   assert(Opcode >= Instruction::BinaryOpsBegin &&
1639          Opcode <  Instruction::BinaryOpsEnd   &&
1640          "Invalid opcode in binary constant expression");
1641   assert(C1->getType() == C2->getType() &&
1642          "Operand types in binary constant expression should match");
1643
1644   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1645     if (Constant *FC = ConstantFoldBinaryInstruction(
1646                                             getGlobalContext(), Opcode, C1, C2))
1647       return FC;          // Fold a few common cases...
1648
1649   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1650   ExprMapKeyType Key(Opcode, argVec);
1651   
1652   // Implicitly locked.
1653   return ExprConstants->getOrCreate(ReqTy, Key);
1654 }
1655
1656 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1657                                      Constant *C1, Constant *C2) {
1658   switch (predicate) {
1659     default: llvm_unreachable("Invalid CmpInst predicate");
1660     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1661     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1662     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1663     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1664     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1665     case CmpInst::FCMP_TRUE:
1666       return getFCmp(predicate, C1, C2);
1667
1668     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1669     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1670     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1671     case CmpInst::ICMP_SLE:
1672       return getICmp(predicate, C1, C2);
1673   }
1674 }
1675
1676 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1677   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1678   if (C1->getType()->isFPOrFPVector()) {
1679     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1680     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1681     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1682   }
1683 #ifndef NDEBUG
1684   switch (Opcode) {
1685   case Instruction::Add:
1686   case Instruction::Sub:
1687   case Instruction::Mul:
1688     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689     assert(C1->getType()->isIntOrIntVector() &&
1690            "Tried to create an integer operation on a non-integer type!");
1691     break;
1692   case Instruction::FAdd:
1693   case Instruction::FSub:
1694   case Instruction::FMul:
1695     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1696     assert(C1->getType()->isFPOrFPVector() &&
1697            "Tried to create a floating-point operation on a "
1698            "non-floating-point type!");
1699     break;
1700   case Instruction::UDiv: 
1701   case Instruction::SDiv: 
1702     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1703     assert(C1->getType()->isIntOrIntVector() &&
1704            "Tried to create an arithmetic operation on a non-arithmetic type!");
1705     break;
1706   case Instruction::FDiv:
1707     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1708     assert(C1->getType()->isFPOrFPVector() &&
1709            "Tried to create an arithmetic operation on a non-arithmetic type!");
1710     break;
1711   case Instruction::URem: 
1712   case Instruction::SRem: 
1713     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1714     assert(C1->getType()->isIntOrIntVector() &&
1715            "Tried to create an arithmetic operation on a non-arithmetic type!");
1716     break;
1717   case Instruction::FRem:
1718     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1719     assert(C1->getType()->isFPOrFPVector() &&
1720            "Tried to create an arithmetic operation on a non-arithmetic type!");
1721     break;
1722   case Instruction::And:
1723   case Instruction::Or:
1724   case Instruction::Xor:
1725     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726     assert(C1->getType()->isIntOrIntVector() &&
1727            "Tried to create a logical operation on a non-integral type!");
1728     break;
1729   case Instruction::Shl:
1730   case Instruction::LShr:
1731   case Instruction::AShr:
1732     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1733     assert(C1->getType()->isIntOrIntVector() &&
1734            "Tried to create a shift operation on a non-integer type!");
1735     break;
1736   default:
1737     break;
1738   }
1739 #endif
1740
1741   return getTy(C1->getType(), Opcode, C1, C2);
1742 }
1743
1744 Constant *ConstantExpr::getCompare(unsigned short pred, 
1745                             Constant *C1, Constant *C2) {
1746   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1747   return getCompareTy(pred, C1, C2);
1748 }
1749
1750 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1751                                     Constant *V1, Constant *V2) {
1752   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1753
1754   if (ReqTy == V1->getType())
1755     if (Constant *SC = ConstantFoldSelectInstruction(
1756                                                 getGlobalContext(), C, V1, V2))
1757       return SC;        // Fold common cases
1758
1759   std::vector<Constant*> argVec(3, C);
1760   argVec[1] = V1;
1761   argVec[2] = V2;
1762   ExprMapKeyType Key(Instruction::Select, argVec);
1763   
1764   // Implicitly locked.
1765   return ExprConstants->getOrCreate(ReqTy, Key);
1766 }
1767
1768 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1769                                            Value* const *Idxs,
1770                                            unsigned NumIdx) {
1771   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1772                                            Idxs+NumIdx) ==
1773          cast<PointerType>(ReqTy)->getElementType() &&
1774          "GEP indices invalid!");
1775
1776   if (Constant *FC = ConstantFoldGetElementPtr(
1777                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1778     return FC;          // Fold a few common cases...
1779
1780   assert(isa<PointerType>(C->getType()) &&
1781          "Non-pointer type for constant GetElementPtr expression");
1782   // Look up the constant in the table first to ensure uniqueness
1783   std::vector<Constant*> ArgVec;
1784   ArgVec.reserve(NumIdx+1);
1785   ArgVec.push_back(C);
1786   for (unsigned i = 0; i != NumIdx; ++i)
1787     ArgVec.push_back(cast<Constant>(Idxs[i]));
1788   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1789
1790   // Implicitly locked.
1791   return ExprConstants->getOrCreate(ReqTy, Key);
1792 }
1793
1794 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1795                                          unsigned NumIdx) {
1796   // Get the result type of the getelementptr!
1797   const Type *Ty = 
1798     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1799   assert(Ty && "GEP indices invalid!");
1800   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1801   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1802 }
1803
1804 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1805                                          unsigned NumIdx) {
1806   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1807 }
1808
1809
1810 Constant *
1811 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1812   assert(LHS->getType() == RHS->getType());
1813   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1814          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1815
1816   if (Constant *FC = ConstantFoldCompareInstruction(
1817                                              getGlobalContext(),pred, LHS, RHS))
1818     return FC;          // Fold a few common cases...
1819
1820   // Look up the constant in the table first to ensure uniqueness
1821   std::vector<Constant*> ArgVec;
1822   ArgVec.push_back(LHS);
1823   ArgVec.push_back(RHS);
1824   // Get the key type with both the opcode and predicate
1825   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1826
1827   // Implicitly locked.
1828   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1829 }
1830
1831 Constant *
1832 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1833   assert(LHS->getType() == RHS->getType());
1834   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1835
1836   if (Constant *FC = ConstantFoldCompareInstruction(
1837                                             getGlobalContext(), pred, LHS, RHS))
1838     return FC;          // Fold a few common cases...
1839
1840   // Look up the constant in the table first to ensure uniqueness
1841   std::vector<Constant*> ArgVec;
1842   ArgVec.push_back(LHS);
1843   ArgVec.push_back(RHS);
1844   // Get the key type with both the opcode and predicate
1845   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1846   
1847   // Implicitly locked.
1848   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1849 }
1850
1851 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1852                                             Constant *Idx) {
1853   if (Constant *FC = ConstantFoldExtractElementInstruction(
1854                                                   getGlobalContext(), Val, Idx))
1855     return FC;          // Fold a few common cases...
1856   // Look up the constant in the table first to ensure uniqueness
1857   std::vector<Constant*> ArgVec(1, Val);
1858   ArgVec.push_back(Idx);
1859   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1860   
1861   // Implicitly locked.
1862   return ExprConstants->getOrCreate(ReqTy, Key);
1863 }
1864
1865 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1866   assert(isa<VectorType>(Val->getType()) &&
1867          "Tried to create extractelement operation on non-vector type!");
1868   assert(Idx->getType() == Type::Int32Ty &&
1869          "Extractelement index must be i32 type!");
1870   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1871                              Val, Idx);
1872 }
1873
1874 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1875                                            Constant *Elt, Constant *Idx) {
1876   if (Constant *FC = ConstantFoldInsertElementInstruction(
1877                                             getGlobalContext(), Val, Elt, Idx))
1878     return FC;          // Fold a few common cases...
1879   // Look up the constant in the table first to ensure uniqueness
1880   std::vector<Constant*> ArgVec(1, Val);
1881   ArgVec.push_back(Elt);
1882   ArgVec.push_back(Idx);
1883   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1884   
1885   // Implicitly locked.
1886   return ExprConstants->getOrCreate(ReqTy, Key);
1887 }
1888
1889 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1890                                          Constant *Idx) {
1891   assert(isa<VectorType>(Val->getType()) &&
1892          "Tried to create insertelement operation on non-vector type!");
1893   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1894          && "Insertelement types must match!");
1895   assert(Idx->getType() == Type::Int32Ty &&
1896          "Insertelement index must be i32 type!");
1897   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1898 }
1899
1900 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1901                                            Constant *V2, Constant *Mask) {
1902   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1903                                               getGlobalContext(), V1, V2, Mask))
1904     return FC;          // Fold a few common cases...
1905   // Look up the constant in the table first to ensure uniqueness
1906   std::vector<Constant*> ArgVec(1, V1);
1907   ArgVec.push_back(V2);
1908   ArgVec.push_back(Mask);
1909   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1910   
1911   // Implicitly locked.
1912   return ExprConstants->getOrCreate(ReqTy, Key);
1913 }
1914
1915 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1916                                          Constant *Mask) {
1917   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1918          "Invalid shuffle vector constant expr operands!");
1919
1920   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1921   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1922   const Type *ShufTy = VectorType::get(EltTy, NElts);
1923   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1924 }
1925
1926 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1927                                          Constant *Val,
1928                                         const unsigned *Idxs, unsigned NumIdx) {
1929   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1930                                           Idxs+NumIdx) == Val->getType() &&
1931          "insertvalue indices invalid!");
1932   assert(Agg->getType() == ReqTy &&
1933          "insertvalue type invalid!");
1934   assert(Agg->getType()->isFirstClassType() &&
1935          "Non-first-class type for constant InsertValue expression");
1936   Constant *FC = ConstantFoldInsertValueInstruction(
1937                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
1938   assert(FC && "InsertValue constant expr couldn't be folded!");
1939   return FC;
1940 }
1941
1942 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1943                                      const unsigned *IdxList, unsigned NumIdx) {
1944   assert(Agg->getType()->isFirstClassType() &&
1945          "Tried to create insertelement operation on non-first-class type!");
1946
1947   const Type *ReqTy = Agg->getType();
1948 #ifndef NDEBUG
1949   const Type *ValTy =
1950     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1951 #endif
1952   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1953   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1954 }
1955
1956 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1957                                         const unsigned *Idxs, unsigned NumIdx) {
1958   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1959                                           Idxs+NumIdx) == ReqTy &&
1960          "extractvalue indices invalid!");
1961   assert(Agg->getType()->isFirstClassType() &&
1962          "Non-first-class type for constant extractvalue expression");
1963   Constant *FC = ConstantFoldExtractValueInstruction(
1964                                          getGlobalContext(), Agg, Idxs, NumIdx);
1965   assert(FC && "ExtractValue constant expr couldn't be folded!");
1966   return FC;
1967 }
1968
1969 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1970                                      const unsigned *IdxList, unsigned NumIdx) {
1971   assert(Agg->getType()->isFirstClassType() &&
1972          "Tried to create extractelement operation on non-first-class type!");
1973
1974   const Type *ReqTy =
1975     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1976   assert(ReqTy && "extractvalue indices invalid!");
1977   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1978 }
1979
1980 // destroyConstant - Remove the constant from the constant table...
1981 //
1982 void ConstantExpr::destroyConstant() {
1983   // Implicitly locked.
1984   ExprConstants->remove(this);
1985   destroyConstantImpl();
1986 }
1987
1988 const char *ConstantExpr::getOpcodeName() const {
1989   return Instruction::getOpcodeName(getOpcode());
1990 }
1991
1992 //===----------------------------------------------------------------------===//
1993 //                replaceUsesOfWithOnConstant implementations
1994
1995 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1996 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1997 /// etc.
1998 ///
1999 /// Note that we intentionally replace all uses of From with To here.  Consider
2000 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2001 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2002 /// single invocation handles all 1000 uses.  Handling them one at a time would
2003 /// work, but would be really slow because it would have to unique each updated
2004 /// array instance.
2005 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2006                                                 Use *U) {
2007   Constant *Replacement =
2008     getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2009  
2010   if (!Replacement) return;
2011  
2012   // Otherwise, I do need to replace this with an existing value.
2013   assert(Replacement != this && "I didn't contain From!");
2014   
2015   // Everyone using this now uses the replacement.
2016   uncheckedReplaceAllUsesWith(Replacement);
2017   
2018   // Delete the old constant!
2019   destroyConstant();
2020 }
2021
2022 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2023                                                  Use *U) {
2024   Constant* Replacement =
2025     getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2026   if (!Replacement) return;
2027   
2028   // Everyone using this now uses the replacement.
2029   uncheckedReplaceAllUsesWith(Replacement);
2030   
2031   // Delete the old constant!
2032   destroyConstant();
2033 }
2034
2035 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2036                                                  Use *U) {
2037   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2038   
2039   std::vector<Constant*> Values;
2040   Values.reserve(getNumOperands());  // Build replacement array...
2041   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2042     Constant *Val = getOperand(i);
2043     if (Val == From) Val = cast<Constant>(To);
2044     Values.push_back(Val);
2045   }
2046   
2047   Constant *Replacement =
2048     getType()->getContext().getConstantVector(getType(), Values);
2049   assert(Replacement != this && "I didn't contain From!");
2050   
2051   // Everyone using this now uses the replacement.
2052   uncheckedReplaceAllUsesWith(Replacement);
2053   
2054   // Delete the old constant!
2055   destroyConstant();
2056 }
2057
2058 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2059                                                Use *U) {
2060   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2061   Constant *To = cast<Constant>(ToV);
2062   
2063   Constant *Replacement = 0;
2064   if (getOpcode() == Instruction::GetElementPtr) {
2065     SmallVector<Constant*, 8> Indices;
2066     Constant *Pointer = getOperand(0);
2067     Indices.reserve(getNumOperands()-1);
2068     if (Pointer == From) Pointer = To;
2069     
2070     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2071       Constant *Val = getOperand(i);
2072       if (Val == From) Val = To;
2073       Indices.push_back(Val);
2074     }
2075     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2076                                                  &Indices[0], Indices.size());
2077   } else if (getOpcode() == Instruction::ExtractValue) {
2078     Constant *Agg = getOperand(0);
2079     if (Agg == From) Agg = To;
2080     
2081     const SmallVector<unsigned, 4> &Indices = getIndices();
2082     Replacement = ConstantExpr::getExtractValue(Agg,
2083                                                 &Indices[0], Indices.size());
2084   } else if (getOpcode() == Instruction::InsertValue) {
2085     Constant *Agg = getOperand(0);
2086     Constant *Val = getOperand(1);
2087     if (Agg == From) Agg = To;
2088     if (Val == From) Val = To;
2089     
2090     const SmallVector<unsigned, 4> &Indices = getIndices();
2091     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2092                                                &Indices[0], Indices.size());
2093   } else if (isCast()) {
2094     assert(getOperand(0) == From && "Cast only has one use!");
2095     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2096   } else if (getOpcode() == Instruction::Select) {
2097     Constant *C1 = getOperand(0);
2098     Constant *C2 = getOperand(1);
2099     Constant *C3 = getOperand(2);
2100     if (C1 == From) C1 = To;
2101     if (C2 == From) C2 = To;
2102     if (C3 == From) C3 = To;
2103     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2104   } else if (getOpcode() == Instruction::ExtractElement) {
2105     Constant *C1 = getOperand(0);
2106     Constant *C2 = getOperand(1);
2107     if (C1 == From) C1 = To;
2108     if (C2 == From) C2 = To;
2109     Replacement = ConstantExpr::getExtractElement(C1, C2);
2110   } else if (getOpcode() == Instruction::InsertElement) {
2111     Constant *C1 = getOperand(0);
2112     Constant *C2 = getOperand(1);
2113     Constant *C3 = getOperand(1);
2114     if (C1 == From) C1 = To;
2115     if (C2 == From) C2 = To;
2116     if (C3 == From) C3 = To;
2117     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2118   } else if (getOpcode() == Instruction::ShuffleVector) {
2119     Constant *C1 = getOperand(0);
2120     Constant *C2 = getOperand(1);
2121     Constant *C3 = getOperand(2);
2122     if (C1 == From) C1 = To;
2123     if (C2 == From) C2 = To;
2124     if (C3 == From) C3 = To;
2125     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2126   } else if (isCompare()) {
2127     Constant *C1 = getOperand(0);
2128     Constant *C2 = getOperand(1);
2129     if (C1 == From) C1 = To;
2130     if (C2 == From) C2 = To;
2131     if (getOpcode() == Instruction::ICmp)
2132       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2133     else {
2134       assert(getOpcode() == Instruction::FCmp);
2135       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2136     }
2137   } else if (getNumOperands() == 2) {
2138     Constant *C1 = getOperand(0);
2139     Constant *C2 = getOperand(1);
2140     if (C1 == From) C1 = To;
2141     if (C2 == From) C2 = To;
2142     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2143   } else {
2144     llvm_unreachable("Unknown ConstantExpr type!");
2145     return;
2146   }
2147   
2148   assert(Replacement != this && "I didn't contain From!");
2149   
2150   // Everyone using this now uses the replacement.
2151   uncheckedReplaceAllUsesWith(Replacement);
2152   
2153   // Delete the old constant!
2154   destroyConstant();
2155 }
2156
2157 void MDNode::replaceElement(Value *From, Value *To) {
2158   SmallVector<Value*, 4> Values;
2159   Values.reserve(getNumElements());  // Build replacement array...
2160   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2161     Value *Val = getElement(i);
2162     if (Val == From) Val = To;
2163     Values.push_back(Val);
2164   }
2165
2166   MDNode *Replacement =
2167     getType()->getContext().getMDNode(&Values[0], Values.size());
2168   assert(Replacement != this && "I didn't contain From!");
2169
2170   uncheckedReplaceAllUsesWith(Replacement);
2171 }