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