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