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