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