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