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