1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
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"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
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.
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: "
49 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
53 // The constant should remove itself from our use list...
54 assert((use_empty() || use_back() != V) && "Constant not removed!");
57 // Value has no outstanding references it is safe to delete it now...
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;
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
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())
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);
99 case Type::SByteTyID: {
100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
103 case Type::UByteTyID: {
104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
107 case Type::ShortTyID: {
108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
111 case Type::UShortTyID: {
112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
115 case Type::IntTyID: {
116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
119 case Type::UIntTyID: {
120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
123 case Type::LongTyID: {
124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
127 case Type::ULongTyID: {
128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
132 case Type::FloatTyID: {
133 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
136 case Type::DoubleTyID: {
137 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
141 case Type::PointerTyID:
142 return ConstantPointerNull::get(cast<PointerType>(Ty));
144 case Type::StructTyID:
145 case Type::ArrayTyID:
146 case Type::PackedTyID:
147 return ConstantAggregateZero::get(Ty);
149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
156 // Static constructor to create an integral constant with all bits set
157 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
158 switch (Ty->getTypeID()) {
159 case Type::BoolTyID: return ConstantBool::getTrue();
160 case Type::SByteTyID:
161 case Type::ShortTyID:
163 case Type::LongTyID: return ConstantInt::get(Ty, -1);
165 case Type::UByteTyID:
166 case Type::UShortTyID:
168 case Type::ULongTyID: {
169 // Calculate ~0 of the right type...
170 unsigned TypeBits = Ty->getPrimitiveSize()*8;
171 uint64_t Val = ~0ULL; // All ones
172 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
173 return ConstantInt::get(Ty, Val);
179 //===----------------------------------------------------------------------===//
180 // ConstantXXX Classes
181 //===----------------------------------------------------------------------===//
183 //===----------------------------------------------------------------------===//
184 // Normal Constructors
186 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
187 : Constant(Ty, VT, 0, 0), Val(V) {
190 ConstantBool::ConstantBool(bool V)
191 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
194 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
195 : ConstantIntegral(Ty, ConstantIntVal, V) {
198 ConstantFP::ConstantFP(const Type *Ty, double V)
199 : Constant(Ty, ConstantFPVal, 0, 0) {
200 assert(isValueValidForType(Ty, V) && "Value too large for type!");
204 ConstantArray::ConstantArray(const ArrayType *T,
205 const std::vector<Constant*> &V)
206 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
207 assert(V.size() == T->getNumElements() &&
208 "Invalid initializer vector for constant array");
209 Use *OL = OperandList;
210 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
213 assert((C->getType() == T->getElementType() ||
215 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
216 "Initializer for array element doesn't match array element type!");
221 ConstantArray::~ConstantArray() {
222 delete [] OperandList;
225 ConstantStruct::ConstantStruct(const StructType *T,
226 const std::vector<Constant*> &V)
227 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
228 assert(V.size() == T->getNumElements() &&
229 "Invalid initializer vector for constant structure");
230 Use *OL = OperandList;
231 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
234 assert((C->getType() == T->getElementType(I-V.begin()) ||
235 ((T->getElementType(I-V.begin())->isAbstract() ||
236 C->getType()->isAbstract()) &&
237 T->getElementType(I-V.begin())->getTypeID() ==
238 C->getType()->getTypeID())) &&
239 "Initializer for struct element doesn't match struct element type!");
244 ConstantStruct::~ConstantStruct() {
245 delete [] OperandList;
249 ConstantPacked::ConstantPacked(const PackedType *T,
250 const std::vector<Constant*> &V)
251 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
252 Use *OL = OperandList;
253 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
256 assert((C->getType() == T->getElementType() ||
258 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
259 "Initializer for packed element doesn't match packed element type!");
264 ConstantPacked::~ConstantPacked() {
265 delete [] OperandList;
268 static bool isSetCC(unsigned Opcode) {
269 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
270 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
271 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
274 // We declare several classes private to this file, so use an anonymous
278 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
279 /// behind the scenes to implement unary constant exprs.
280 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
283 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
284 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
287 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
288 /// behind the scenes to implement binary constant exprs.
289 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
292 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
293 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
295 Ops[0].init(C1, this);
296 Ops[1].init(C2, this);
300 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
301 /// behind the scenes to implement select constant exprs.
302 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
305 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
306 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
307 Ops[0].init(C1, this);
308 Ops[1].init(C2, this);
309 Ops[2].init(C3, this);
313 /// ExtractElementConstantExpr - This class is private to
314 /// Constants.cpp, and is used behind the scenes to implement
315 /// extractelement constant exprs.
316 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
319 ExtractElementConstantExpr(Constant *C1, Constant *C2)
320 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
321 Instruction::ExtractElement, Ops, 2) {
322 Ops[0].init(C1, this);
323 Ops[1].init(C2, this);
327 /// InsertElementConstantExpr - This class is private to
328 /// Constants.cpp, and is used behind the scenes to implement
329 /// insertelement constant exprs.
330 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
333 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
334 : ConstantExpr(C1->getType(), Instruction::InsertElement,
336 Ops[0].init(C1, this);
337 Ops[1].init(C2, this);
338 Ops[2].init(C3, this);
342 /// ShuffleVectorConstantExpr - This class is private to
343 /// Constants.cpp, and is used behind the scenes to implement
344 /// shufflevector constant exprs.
345 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
348 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
349 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
351 Ops[0].init(C1, this);
352 Ops[1].init(C2, this);
353 Ops[2].init(C3, this);
357 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
358 /// used behind the scenes to implement getelementpr constant exprs.
359 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
360 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
362 : ConstantExpr(DestTy, Instruction::GetElementPtr,
363 new Use[IdxList.size()+1], IdxList.size()+1) {
364 OperandList[0].init(C, this);
365 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
366 OperandList[i+1].init(IdxList[i], this);
368 ~GetElementPtrConstantExpr() {
369 delete [] OperandList;
373 // CompareConstantExpr - This class is private to Constants.cpp, and is used
374 // behind the scenes to implement ICmp and FCmp constant expressions. This is
375 // needed in order to store the predicate value for these instructions.
376 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
377 unsigned short predicate;
379 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
380 Constant* LHS, Constant* RHS)
381 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
382 OperandList[0].init(LHS, this);
383 OperandList[1].init(RHS, this);
387 } // end anonymous namespace
390 // Utility function for determining if a ConstantExpr is a CastOp or not. This
391 // can't be inline because we don't want to #include Instruction.h into
393 bool ConstantExpr::isCast() const {
394 return Instruction::isCast(getOpcode());
397 bool ConstantExpr::isCompare() const {
398 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
401 /// ConstantExpr::get* - Return some common constants without having to
402 /// specify the full Instruction::OPCODE identifier.
404 Constant *ConstantExpr::getNeg(Constant *C) {
405 if (!C->getType()->isFloatingPoint())
406 return get(Instruction::Sub, getNullValue(C->getType()), C);
408 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
410 Constant *ConstantExpr::getNot(Constant *C) {
411 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
412 return get(Instruction::Xor, C,
413 ConstantIntegral::getAllOnesValue(C->getType()));
415 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
416 return get(Instruction::Add, C1, C2);
418 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
419 return get(Instruction::Sub, C1, C2);
421 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
422 return get(Instruction::Mul, C1, C2);
424 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
425 return get(Instruction::UDiv, C1, C2);
427 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
428 return get(Instruction::SDiv, C1, C2);
430 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
431 return get(Instruction::FDiv, C1, C2);
433 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
434 return get(Instruction::URem, C1, C2);
436 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
437 return get(Instruction::SRem, C1, C2);
439 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
440 return get(Instruction::FRem, C1, C2);
442 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
443 return get(Instruction::And, C1, C2);
445 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
446 return get(Instruction::Or, C1, C2);
448 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
449 return get(Instruction::Xor, C1, C2);
451 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
452 return get(Instruction::SetEQ, C1, C2);
454 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
455 return get(Instruction::SetNE, C1, C2);
457 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
458 return get(Instruction::SetLT, C1, C2);
460 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
461 return get(Instruction::SetGT, C1, C2);
463 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
464 return get(Instruction::SetLE, C1, C2);
466 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
467 return get(Instruction::SetGE, C1, C2);
469 unsigned ConstantExpr::getPredicate() const {
470 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
471 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
473 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
474 return get(Instruction::Shl, C1, C2);
476 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
477 return get(Instruction::LShr, C1, C2);
479 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
480 return get(Instruction::AShr, C1, C2);
483 /// getWithOperandReplaced - Return a constant expression identical to this
484 /// one, but with the specified operand set to the specified value.
486 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
487 assert(OpNo < getNumOperands() && "Operand num is out of range!");
488 assert(Op->getType() == getOperand(OpNo)->getType() &&
489 "Replacing operand with value of different type!");
490 if (getOperand(OpNo) == Op)
491 return const_cast<ConstantExpr*>(this);
493 Constant *Op0, *Op1, *Op2;
494 switch (getOpcode()) {
495 case Instruction::Trunc:
496 case Instruction::ZExt:
497 case Instruction::SExt:
498 case Instruction::FPTrunc:
499 case Instruction::FPExt:
500 case Instruction::UIToFP:
501 case Instruction::SIToFP:
502 case Instruction::FPToUI:
503 case Instruction::FPToSI:
504 case Instruction::PtrToInt:
505 case Instruction::IntToPtr:
506 case Instruction::BitCast:
507 return ConstantExpr::getCast(getOpcode(), Op, getType());
508 case Instruction::Select:
509 Op0 = (OpNo == 0) ? Op : getOperand(0);
510 Op1 = (OpNo == 1) ? Op : getOperand(1);
511 Op2 = (OpNo == 2) ? Op : getOperand(2);
512 return ConstantExpr::getSelect(Op0, Op1, Op2);
513 case Instruction::InsertElement:
514 Op0 = (OpNo == 0) ? Op : getOperand(0);
515 Op1 = (OpNo == 1) ? Op : getOperand(1);
516 Op2 = (OpNo == 2) ? Op : getOperand(2);
517 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
518 case Instruction::ExtractElement:
519 Op0 = (OpNo == 0) ? Op : getOperand(0);
520 Op1 = (OpNo == 1) ? Op : getOperand(1);
521 return ConstantExpr::getExtractElement(Op0, Op1);
522 case Instruction::ShuffleVector:
523 Op0 = (OpNo == 0) ? Op : getOperand(0);
524 Op1 = (OpNo == 1) ? Op : getOperand(1);
525 Op2 = (OpNo == 2) ? Op : getOperand(2);
526 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
527 case Instruction::GetElementPtr: {
528 std::vector<Constant*> Ops;
529 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
530 Ops.push_back(getOperand(i));
532 return ConstantExpr::getGetElementPtr(Op, Ops);
534 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
537 assert(getNumOperands() == 2 && "Must be binary operator?");
538 Op0 = (OpNo == 0) ? Op : getOperand(0);
539 Op1 = (OpNo == 1) ? Op : getOperand(1);
540 return ConstantExpr::get(getOpcode(), Op0, Op1);
544 /// getWithOperands - This returns the current constant expression with the
545 /// operands replaced with the specified values. The specified operands must
546 /// match count and type with the existing ones.
547 Constant *ConstantExpr::
548 getWithOperands(const std::vector<Constant*> &Ops) const {
549 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
550 bool AnyChange = false;
551 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
552 assert(Ops[i]->getType() == getOperand(i)->getType() &&
553 "Operand type mismatch!");
554 AnyChange |= Ops[i] != getOperand(i);
556 if (!AnyChange) // No operands changed, return self.
557 return const_cast<ConstantExpr*>(this);
559 switch (getOpcode()) {
560 case Instruction::Trunc:
561 case Instruction::ZExt:
562 case Instruction::SExt:
563 case Instruction::FPTrunc:
564 case Instruction::FPExt:
565 case Instruction::UIToFP:
566 case Instruction::SIToFP:
567 case Instruction::FPToUI:
568 case Instruction::FPToSI:
569 case Instruction::PtrToInt:
570 case Instruction::IntToPtr:
571 case Instruction::BitCast:
572 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
573 case Instruction::Select:
574 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
575 case Instruction::InsertElement:
576 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
577 case Instruction::ExtractElement:
578 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
579 case Instruction::ShuffleVector:
580 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
581 case Instruction::GetElementPtr: {
582 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
583 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
586 assert(getNumOperands() == 2 && "Must be binary operator?");
587 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
592 //===----------------------------------------------------------------------===//
593 // isValueValidForType implementations
595 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
596 switch (Ty->getTypeID()) {
598 return false; // These can't be represented as integers!!!
600 case Type::SByteTyID:
601 return (Val <= INT8_MAX && Val >= INT8_MIN);
602 case Type::UByteTyID:
603 return (Val >= 0) && (Val <= UINT8_MAX);
604 case Type::ShortTyID:
605 return (Val <= INT16_MAX && Val >= INT16_MIN);
606 case Type::UShortTyID:
607 return (Val >= 0) && (Val <= UINT16_MAX);
609 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
611 return (Val >= 0) && (Val <= UINT32_MAX);
613 case Type::ULongTyID:
614 return true; // always true, has to fit in largest type
618 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
619 switch (Ty->getTypeID()) {
621 return false; // These can't be represented as floating point!
623 // TODO: Figure out how to test if a double can be cast to a float!
624 case Type::FloatTyID:
625 case Type::DoubleTyID:
626 return true; // This is the largest type...
630 //===----------------------------------------------------------------------===//
631 // Factory Function Implementation
633 // ConstantCreator - A class that is used to create constants by
634 // ValueMap*. This class should be partially specialized if there is
635 // something strange that needs to be done to interface to the ctor for the
639 template<class ConstantClass, class TypeClass, class ValType>
640 struct VISIBILITY_HIDDEN ConstantCreator {
641 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
642 return new ConstantClass(Ty, V);
646 template<class ConstantClass, class TypeClass>
647 struct VISIBILITY_HIDDEN ConvertConstantType {
648 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
649 assert(0 && "This type cannot be converted!\n");
654 template<class ValType, class TypeClass, class ConstantClass,
655 bool HasLargeKey = false /*true for arrays and structs*/ >
656 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
658 typedef std::pair<const Type*, ValType> MapKey;
659 typedef std::map<MapKey, Constant *> MapTy;
660 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
661 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
663 /// Map - This is the main map from the element descriptor to the Constants.
664 /// This is the primary way we avoid creating two of the same shape
668 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
669 /// from the constants to their element in Map. This is important for
670 /// removal of constants from the array, which would otherwise have to scan
671 /// through the map with very large keys.
672 InverseMapTy InverseMap;
674 /// AbstractTypeMap - Map for abstract type constants.
676 AbstractTypeMapTy AbstractTypeMap;
679 void clear(std::vector<Constant *> &Constants) {
680 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
681 Constants.push_back(I->second);
683 AbstractTypeMap.clear();
688 typename MapTy::iterator map_end() { return Map.end(); }
690 /// InsertOrGetItem - Return an iterator for the specified element.
691 /// If the element exists in the map, the returned iterator points to the
692 /// entry and Exists=true. If not, the iterator points to the newly
693 /// inserted entry and returns Exists=false. Newly inserted entries have
694 /// I->second == 0, and should be filled in.
695 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
698 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
704 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
706 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
707 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
708 IMI->second->second == CP &&
709 "InverseMap corrupt!");
713 typename MapTy::iterator I =
714 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
715 if (I == Map.end() || I->second != CP) {
716 // FIXME: This should not use a linear scan. If this gets to be a
717 // performance problem, someone should look at this.
718 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
725 /// getOrCreate - Return the specified constant from the map, creating it if
727 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
728 MapKey Lookup(Ty, V);
729 typename MapTy::iterator I = Map.lower_bound(Lookup);
731 if (I != Map.end() && I->first == Lookup)
732 return static_cast<ConstantClass *>(I->second);
734 // If no preexisting value, create one now...
735 ConstantClass *Result =
736 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
738 /// FIXME: why does this assert fail when loading 176.gcc?
739 //assert(Result->getType() == Ty && "Type specified is not correct!");
740 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
742 if (HasLargeKey) // Remember the reverse mapping if needed.
743 InverseMap.insert(std::make_pair(Result, I));
745 // If the type of the constant is abstract, make sure that an entry exists
746 // for it in the AbstractTypeMap.
747 if (Ty->isAbstract()) {
748 typename AbstractTypeMapTy::iterator TI =
749 AbstractTypeMap.lower_bound(Ty);
751 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
752 // Add ourselves to the ATU list of the type.
753 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
755 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
761 void remove(ConstantClass *CP) {
762 typename MapTy::iterator I = FindExistingElement(CP);
763 assert(I != Map.end() && "Constant not found in constant table!");
764 assert(I->second == CP && "Didn't find correct element?");
766 if (HasLargeKey) // Remember the reverse mapping if needed.
767 InverseMap.erase(CP);
769 // Now that we found the entry, make sure this isn't the entry that
770 // the AbstractTypeMap points to.
771 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
772 if (Ty->isAbstract()) {
773 assert(AbstractTypeMap.count(Ty) &&
774 "Abstract type not in AbstractTypeMap?");
775 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
776 if (ATMEntryIt == I) {
777 // Yes, we are removing the representative entry for this type.
778 // See if there are any other entries of the same type.
779 typename MapTy::iterator TmpIt = ATMEntryIt;
781 // First check the entry before this one...
782 if (TmpIt != Map.begin()) {
784 if (TmpIt->first.first != Ty) // Not the same type, move back...
788 // If we didn't find the same type, try to move forward...
789 if (TmpIt == ATMEntryIt) {
791 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
792 --TmpIt; // No entry afterwards with the same type
795 // If there is another entry in the map of the same abstract type,
796 // update the AbstractTypeMap entry now.
797 if (TmpIt != ATMEntryIt) {
800 // Otherwise, we are removing the last instance of this type
801 // from the table. Remove from the ATM, and from user list.
802 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
803 AbstractTypeMap.erase(Ty);
812 /// MoveConstantToNewSlot - If we are about to change C to be the element
813 /// specified by I, update our internal data structures to reflect this
815 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
816 // First, remove the old location of the specified constant in the map.
817 typename MapTy::iterator OldI = FindExistingElement(C);
818 assert(OldI != Map.end() && "Constant not found in constant table!");
819 assert(OldI->second == C && "Didn't find correct element?");
821 // If this constant is the representative element for its abstract type,
822 // update the AbstractTypeMap so that the representative element is I.
823 if (C->getType()->isAbstract()) {
824 typename AbstractTypeMapTy::iterator ATI =
825 AbstractTypeMap.find(C->getType());
826 assert(ATI != AbstractTypeMap.end() &&
827 "Abstract type not in AbstractTypeMap?");
828 if (ATI->second == OldI)
832 // Remove the old entry from the map.
835 // Update the inverse map so that we know that this constant is now
836 // located at descriptor I.
838 assert(I->second == C && "Bad inversemap entry!");
843 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
844 typename AbstractTypeMapTy::iterator I =
845 AbstractTypeMap.find(cast<Type>(OldTy));
847 assert(I != AbstractTypeMap.end() &&
848 "Abstract type not in AbstractTypeMap?");
850 // Convert a constant at a time until the last one is gone. The last one
851 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
852 // eliminated eventually.
854 ConvertConstantType<ConstantClass,
856 static_cast<ConstantClass *>(I->second->second),
857 cast<TypeClass>(NewTy));
859 I = AbstractTypeMap.find(cast<Type>(OldTy));
860 } while (I != AbstractTypeMap.end());
863 // If the type became concrete without being refined to any other existing
864 // type, we just remove ourselves from the ATU list.
865 void typeBecameConcrete(const DerivedType *AbsTy) {
866 AbsTy->removeAbstractTypeUser(this);
870 DOUT << "Constant.cpp: ValueMap\n";
876 //---- ConstantBool::get*() implementation.
878 ConstantBool *ConstantBool::getTrue() {
879 static ConstantBool *T = 0;
881 return T = new ConstantBool(true);
883 ConstantBool *ConstantBool::getFalse() {
884 static ConstantBool *F = 0;
886 return F = new ConstantBool(false);
889 //---- ConstantInt::get() implementations...
891 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
893 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
894 // to a uint64_t value that has been zero extended down to the size of the
895 // integer type of the ConstantInt. This allows the getZExtValue method to
896 // just return the stored value while getSExtValue has to convert back to sign
897 // extended. getZExtValue is more common in LLVM than getSExtValue().
898 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
899 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
902 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
903 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
904 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
907 //---- ConstantFP::get() implementation...
911 struct ConstantCreator<ConstantFP, Type, uint64_t> {
912 static ConstantFP *create(const Type *Ty, uint64_t V) {
913 assert(Ty == Type::DoubleTy);
914 return new ConstantFP(Ty, BitsToDouble(V));
918 struct ConstantCreator<ConstantFP, Type, uint32_t> {
919 static ConstantFP *create(const Type *Ty, uint32_t V) {
920 assert(Ty == Type::FloatTy);
921 return new ConstantFP(Ty, BitsToFloat(V));
926 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
927 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
929 bool ConstantFP::isNullValue() const {
930 return DoubleToBits(Val) == 0;
933 bool ConstantFP::isExactlyValue(double V) const {
934 return DoubleToBits(V) == DoubleToBits(Val);
938 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
939 if (Ty == Type::FloatTy) {
940 // Force the value through memory to normalize it.
941 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
943 assert(Ty == Type::DoubleTy);
944 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
948 //---- ConstantAggregateZero::get() implementation...
951 // ConstantAggregateZero does not take extra "value" argument...
952 template<class ValType>
953 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
954 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
955 return new ConstantAggregateZero(Ty);
960 struct ConvertConstantType<ConstantAggregateZero, Type> {
961 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
962 // Make everyone now use a constant of the new type...
963 Constant *New = ConstantAggregateZero::get(NewTy);
964 assert(New != OldC && "Didn't replace constant??");
965 OldC->uncheckedReplaceAllUsesWith(New);
966 OldC->destroyConstant(); // This constant is now dead, destroy it.
971 static ManagedStatic<ValueMap<char, Type,
972 ConstantAggregateZero> > AggZeroConstants;
974 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
976 Constant *ConstantAggregateZero::get(const Type *Ty) {
977 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
978 "Cannot create an aggregate zero of non-aggregate type!");
979 return AggZeroConstants->getOrCreate(Ty, 0);
982 // destroyConstant - Remove the constant from the constant table...
984 void ConstantAggregateZero::destroyConstant() {
985 AggZeroConstants->remove(this);
986 destroyConstantImpl();
989 //---- ConstantArray::get() implementation...
993 struct ConvertConstantType<ConstantArray, ArrayType> {
994 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
995 // Make everyone now use a constant of the new type...
996 std::vector<Constant*> C;
997 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
998 C.push_back(cast<Constant>(OldC->getOperand(i)));
999 Constant *New = ConstantArray::get(NewTy, C);
1000 assert(New != OldC && "Didn't replace constant??");
1001 OldC->uncheckedReplaceAllUsesWith(New);
1002 OldC->destroyConstant(); // This constant is now dead, destroy it.
1007 static std::vector<Constant*> getValType(ConstantArray *CA) {
1008 std::vector<Constant*> Elements;
1009 Elements.reserve(CA->getNumOperands());
1010 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1011 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1015 typedef ValueMap<std::vector<Constant*>, ArrayType,
1016 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1017 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1019 Constant *ConstantArray::get(const ArrayType *Ty,
1020 const std::vector<Constant*> &V) {
1021 // If this is an all-zero array, return a ConstantAggregateZero object
1024 if (!C->isNullValue())
1025 return ArrayConstants->getOrCreate(Ty, V);
1026 for (unsigned i = 1, e = V.size(); i != e; ++i)
1028 return ArrayConstants->getOrCreate(Ty, V);
1030 return ConstantAggregateZero::get(Ty);
1033 // destroyConstant - Remove the constant from the constant table...
1035 void ConstantArray::destroyConstant() {
1036 ArrayConstants->remove(this);
1037 destroyConstantImpl();
1040 /// ConstantArray::get(const string&) - Return an array that is initialized to
1041 /// contain the specified string. If length is zero then a null terminator is
1042 /// added to the specified string so that it may be used in a natural way.
1043 /// Otherwise, the length parameter specifies how much of the string to use
1044 /// and it won't be null terminated.
1046 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1047 std::vector<Constant*> ElementVals;
1048 for (unsigned i = 0; i < Str.length(); ++i)
1049 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
1051 // Add a null terminator to the string...
1053 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
1056 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1057 return ConstantArray::get(ATy, ElementVals);
1060 /// isString - This method returns true if the array is an array of sbyte or
1061 /// ubyte, and if the elements of the array are all ConstantInt's.
1062 bool ConstantArray::isString() const {
1063 // Check the element type for sbyte or ubyte...
1064 if (getType()->getElementType() != Type::UByteTy &&
1065 getType()->getElementType() != Type::SByteTy)
1067 // Check the elements to make sure they are all integers, not constant
1069 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1070 if (!isa<ConstantInt>(getOperand(i)))
1075 /// isCString - This method returns true if the array is a string (see
1076 /// isString) and it ends in a null byte \0 and does not contains any other
1077 /// null bytes except its terminator.
1078 bool ConstantArray::isCString() const {
1079 // Check the element type for sbyte or ubyte...
1080 if (getType()->getElementType() != Type::UByteTy &&
1081 getType()->getElementType() != Type::SByteTy)
1083 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1084 // Last element must be a null.
1085 if (getOperand(getNumOperands()-1) != Zero)
1087 // Other elements must be non-null integers.
1088 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1089 if (!isa<ConstantInt>(getOperand(i)))
1091 if (getOperand(i) == Zero)
1098 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1099 // then this method converts the array to an std::string and returns it.
1100 // Otherwise, it asserts out.
1102 std::string ConstantArray::getAsString() const {
1103 assert(isString() && "Not a string!");
1105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1106 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1111 //---- ConstantStruct::get() implementation...
1116 struct ConvertConstantType<ConstantStruct, StructType> {
1117 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1118 // Make everyone now use a constant of the new type...
1119 std::vector<Constant*> C;
1120 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1121 C.push_back(cast<Constant>(OldC->getOperand(i)));
1122 Constant *New = ConstantStruct::get(NewTy, C);
1123 assert(New != OldC && "Didn't replace constant??");
1125 OldC->uncheckedReplaceAllUsesWith(New);
1126 OldC->destroyConstant(); // This constant is now dead, destroy it.
1131 typedef ValueMap<std::vector<Constant*>, StructType,
1132 ConstantStruct, true /*largekey*/> StructConstantsTy;
1133 static ManagedStatic<StructConstantsTy> StructConstants;
1135 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1136 std::vector<Constant*> Elements;
1137 Elements.reserve(CS->getNumOperands());
1138 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1139 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1143 Constant *ConstantStruct::get(const StructType *Ty,
1144 const std::vector<Constant*> &V) {
1145 // Create a ConstantAggregateZero value if all elements are zeros...
1146 for (unsigned i = 0, e = V.size(); i != e; ++i)
1147 if (!V[i]->isNullValue())
1148 return StructConstants->getOrCreate(Ty, V);
1150 return ConstantAggregateZero::get(Ty);
1153 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1154 std::vector<const Type*> StructEls;
1155 StructEls.reserve(V.size());
1156 for (unsigned i = 0, e = V.size(); i != e; ++i)
1157 StructEls.push_back(V[i]->getType());
1158 return get(StructType::get(StructEls), V);
1161 // destroyConstant - Remove the constant from the constant table...
1163 void ConstantStruct::destroyConstant() {
1164 StructConstants->remove(this);
1165 destroyConstantImpl();
1168 //---- ConstantPacked::get() implementation...
1172 struct ConvertConstantType<ConstantPacked, PackedType> {
1173 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1174 // Make everyone now use a constant of the new type...
1175 std::vector<Constant*> C;
1176 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1177 C.push_back(cast<Constant>(OldC->getOperand(i)));
1178 Constant *New = ConstantPacked::get(NewTy, C);
1179 assert(New != OldC && "Didn't replace constant??");
1180 OldC->uncheckedReplaceAllUsesWith(New);
1181 OldC->destroyConstant(); // This constant is now dead, destroy it.
1186 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1187 std::vector<Constant*> Elements;
1188 Elements.reserve(CP->getNumOperands());
1189 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1190 Elements.push_back(CP->getOperand(i));
1194 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1195 ConstantPacked> > PackedConstants;
1197 Constant *ConstantPacked::get(const PackedType *Ty,
1198 const std::vector<Constant*> &V) {
1199 // If this is an all-zero packed, return a ConstantAggregateZero object
1202 if (!C->isNullValue())
1203 return PackedConstants->getOrCreate(Ty, V);
1204 for (unsigned i = 1, e = V.size(); i != e; ++i)
1206 return PackedConstants->getOrCreate(Ty, V);
1208 return ConstantAggregateZero::get(Ty);
1211 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1212 assert(!V.empty() && "Cannot infer type if V is empty");
1213 return get(PackedType::get(V.front()->getType(),V.size()), V);
1216 // destroyConstant - Remove the constant from the constant table...
1218 void ConstantPacked::destroyConstant() {
1219 PackedConstants->remove(this);
1220 destroyConstantImpl();
1223 //---- ConstantPointerNull::get() implementation...
1227 // ConstantPointerNull does not take extra "value" argument...
1228 template<class ValType>
1229 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1230 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1231 return new ConstantPointerNull(Ty);
1236 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1237 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1238 // Make everyone now use a constant of the new type...
1239 Constant *New = ConstantPointerNull::get(NewTy);
1240 assert(New != OldC && "Didn't replace constant??");
1241 OldC->uncheckedReplaceAllUsesWith(New);
1242 OldC->destroyConstant(); // This constant is now dead, destroy it.
1247 static ManagedStatic<ValueMap<char, PointerType,
1248 ConstantPointerNull> > NullPtrConstants;
1250 static char getValType(ConstantPointerNull *) {
1255 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1256 return NullPtrConstants->getOrCreate(Ty, 0);
1259 // destroyConstant - Remove the constant from the constant table...
1261 void ConstantPointerNull::destroyConstant() {
1262 NullPtrConstants->remove(this);
1263 destroyConstantImpl();
1267 //---- UndefValue::get() implementation...
1271 // UndefValue does not take extra "value" argument...
1272 template<class ValType>
1273 struct ConstantCreator<UndefValue, Type, ValType> {
1274 static UndefValue *create(const Type *Ty, const ValType &V) {
1275 return new UndefValue(Ty);
1280 struct ConvertConstantType<UndefValue, Type> {
1281 static void convert(UndefValue *OldC, const Type *NewTy) {
1282 // Make everyone now use a constant of the new type.
1283 Constant *New = UndefValue::get(NewTy);
1284 assert(New != OldC && "Didn't replace constant??");
1285 OldC->uncheckedReplaceAllUsesWith(New);
1286 OldC->destroyConstant(); // This constant is now dead, destroy it.
1291 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1293 static char getValType(UndefValue *) {
1298 UndefValue *UndefValue::get(const Type *Ty) {
1299 return UndefValueConstants->getOrCreate(Ty, 0);
1302 // destroyConstant - Remove the constant from the constant table.
1304 void UndefValue::destroyConstant() {
1305 UndefValueConstants->remove(this);
1306 destroyConstantImpl();
1310 //---- ConstantExpr::get() implementations...
1312 struct ExprMapKeyType {
1313 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1314 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1317 std::vector<Constant*> operands;
1318 bool operator==(const ExprMapKeyType& that) const {
1319 return this->opcode == that.opcode &&
1320 this->predicate == that.predicate &&
1321 this->operands == that.operands;
1323 bool operator<(const ExprMapKeyType & that) const {
1324 return this->opcode < that.opcode ||
1325 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1326 (this->opcode == that.opcode && this->predicate == that.predicate &&
1327 this->operands < that.operands);
1330 bool operator!=(const ExprMapKeyType& that) const {
1331 return !(*this == that);
1337 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1338 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1339 unsigned short pred = 0) {
1340 if (Instruction::isCast(V.opcode))
1341 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1342 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1343 V.opcode < Instruction::BinaryOpsEnd) ||
1344 V.opcode == Instruction::Shl ||
1345 V.opcode == Instruction::LShr ||
1346 V.opcode == Instruction::AShr)
1347 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1348 if (V.opcode == Instruction::Select)
1349 return new SelectConstantExpr(V.operands[0], V.operands[1],
1351 if (V.opcode == Instruction::ExtractElement)
1352 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1353 if (V.opcode == Instruction::InsertElement)
1354 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1356 if (V.opcode == Instruction::ShuffleVector)
1357 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1359 if (V.opcode == Instruction::GetElementPtr) {
1360 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1361 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1364 // The compare instructions are weird. We have to encode the predicate
1365 // value and it is combined with the instruction opcode by multiplying
1366 // the opcode by one hundred. We must decode this to get the predicate.
1367 if (V.opcode == Instruction::ICmp)
1368 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1369 V.operands[0], V.operands[1]);
1370 if (V.opcode == Instruction::FCmp)
1371 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1372 V.operands[0], V.operands[1]);
1373 assert(0 && "Invalid ConstantExpr!");
1378 struct ConvertConstantType<ConstantExpr, Type> {
1379 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1381 switch (OldC->getOpcode()) {
1382 case Instruction::Trunc:
1383 case Instruction::ZExt:
1384 case Instruction::SExt:
1385 case Instruction::FPTrunc:
1386 case Instruction::FPExt:
1387 case Instruction::UIToFP:
1388 case Instruction::SIToFP:
1389 case Instruction::FPToUI:
1390 case Instruction::FPToSI:
1391 case Instruction::PtrToInt:
1392 case Instruction::IntToPtr:
1393 case Instruction::BitCast:
1394 New = ConstantExpr::getCast(
1395 OldC->getOpcode(), OldC->getOperand(0), NewTy);
1397 case Instruction::Select:
1398 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1399 OldC->getOperand(1),
1400 OldC->getOperand(2));
1402 case Instruction::Shl:
1403 case Instruction::LShr:
1404 case Instruction::AShr:
1405 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1406 OldC->getOperand(0), OldC->getOperand(1));
1409 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1410 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1411 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1412 OldC->getOperand(1));
1414 case Instruction::GetElementPtr:
1415 // Make everyone now use a constant of the new type...
1416 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1417 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1421 assert(New != OldC && "Didn't replace constant??");
1422 OldC->uncheckedReplaceAllUsesWith(New);
1423 OldC->destroyConstant(); // This constant is now dead, destroy it.
1426 } // end namespace llvm
1429 static ExprMapKeyType getValType(ConstantExpr *CE) {
1430 std::vector<Constant*> Operands;
1431 Operands.reserve(CE->getNumOperands());
1432 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1433 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1434 return ExprMapKeyType(CE->getOpcode(), Operands,
1435 CE->isCompare() ? CE->getPredicate() : 0);
1438 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1439 ConstantExpr> > ExprConstants;
1441 /// This is a utility function to handle folding of casts and lookup of the
1442 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1443 static inline Constant *getFoldedCast(
1444 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1445 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1446 // Fold a few common cases
1447 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1450 // Look up the constant in the table first to ensure uniqueness
1451 std::vector<Constant*> argVec(1, C);
1452 ExprMapKeyType Key(opc, argVec);
1453 return ExprConstants->getOrCreate(Ty, Key);
1456 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1457 Instruction::CastOps opc = Instruction::CastOps(oc);
1458 assert(Instruction::isCast(opc) && "opcode out of range");
1459 assert(C && Ty && "Null arguments to getCast");
1460 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1464 assert(0 && "Invalid cast opcode");
1466 case Instruction::Trunc: return getTrunc(C, Ty);
1467 case Instruction::ZExt: return getZeroExtend(C, Ty);
1468 case Instruction::SExt: return getSignExtend(C, Ty);
1469 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1470 case Instruction::FPExt: return getFPExtend(C, Ty);
1471 case Instruction::UIToFP: return getUIToFP(C, Ty);
1472 case Instruction::SIToFP: return getSIToFP(C, Ty);
1473 case Instruction::FPToUI: return getFPToUI(C, Ty);
1474 case Instruction::FPToSI: return getFPToSI(C, Ty);
1475 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1476 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1477 case Instruction::BitCast: return getBitCast(C, Ty);
1482 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1483 // Note: we can't inline this because it requires the Instructions.h header
1484 return getCast(CastInst::getCastOpcode(
1485 C, C->getType()->isSigned(), Ty, Ty->isSigned()), C, Ty);
1489 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1490 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1491 return getCast(Instruction::BitCast, C, Ty);
1492 return getCast(Instruction::ZExt, C, Ty);
1495 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1496 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1497 return getCast(Instruction::BitCast, C, Ty);
1498 return getCast(Instruction::SExt, C, Ty);
1501 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1502 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1503 return getCast(Instruction::BitCast, C, Ty);
1504 return getCast(Instruction::Trunc, C, Ty);
1507 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1508 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1509 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1512 if (Ty->isIntegral())
1513 return getCast(Instruction::PtrToInt, S, Ty);
1514 return getCast(Instruction::BitCast, S, Ty);
1517 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1518 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1519 assert(Ty->isIntegral() && "Trunc produces only integral");
1520 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1521 "SrcTy must be larger than DestTy for Trunc!");
1523 return getFoldedCast(Instruction::Trunc, C, Ty);
1526 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1527 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1528 assert(Ty->isInteger() && "SExt produces only integer");
1529 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1530 "SrcTy must be smaller than DestTy for SExt!");
1532 return getFoldedCast(Instruction::SExt, C, Ty);
1535 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1536 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1537 assert(Ty->isInteger() && "ZExt produces only integer");
1538 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1539 "SrcTy must be smaller than DestTy for ZExt!");
1541 return getFoldedCast(Instruction::ZExt, C, Ty);
1544 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1545 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1546 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1547 "This is an illegal floating point truncation!");
1548 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1551 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1552 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1553 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1554 "This is an illegal floating point extension!");
1555 return getFoldedCast(Instruction::FPExt, C, Ty);
1558 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1559 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1560 "This is an illegal uint to floating point cast!");
1561 return getFoldedCast(Instruction::UIToFP, C, Ty);
1564 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1565 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1566 "This is an illegal sint to floating point cast!");
1567 return getFoldedCast(Instruction::SIToFP, C, Ty);
1570 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1571 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1572 "This is an illegal floating point to uint cast!");
1573 return getFoldedCast(Instruction::FPToUI, C, Ty);
1576 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1577 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1578 "This is an illegal floating point to sint cast!");
1579 return getFoldedCast(Instruction::FPToSI, C, Ty);
1582 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1583 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1584 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1585 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1588 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1589 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1590 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1591 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1594 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1595 // BitCast implies a no-op cast of type only. No bits change. However, you
1596 // can't cast pointers to anything but pointers.
1597 const Type *SrcTy = C->getType();
1598 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1599 "BitCast cannot cast pointer to non-pointer and vice versa");
1601 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1602 // or nonptr->ptr). For all the other types, the cast is okay if source and
1603 // destination bit widths are identical.
1604 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1605 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1606 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1607 return getFoldedCast(Instruction::BitCast, C, DstTy);
1610 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1611 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1612 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1613 PointerType::get(Ty)), std::vector<Constant*>(1,
1614 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
1617 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1618 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1619 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1621 return ConstantExpr::getGetElementPtr(C, Indices);
1624 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1625 Constant *C1, Constant *C2) {
1626 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1627 Opcode == Instruction::AShr)
1628 return getShiftTy(ReqTy, Opcode, C1, C2);
1630 // Check the operands for consistency first
1631 assert(Opcode >= Instruction::BinaryOpsBegin &&
1632 Opcode < Instruction::BinaryOpsEnd &&
1633 "Invalid opcode in binary constant expression");
1634 assert(C1->getType() == C2->getType() &&
1635 "Operand types in binary constant expression should match");
1637 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1638 ReqTy == Type::BoolTy))
1639 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1640 return FC; // Fold a few common cases...
1642 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1643 ExprMapKeyType Key(Opcode, argVec);
1644 return ExprConstants->getOrCreate(ReqTy, Key);
1647 Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1648 Constant *C1, Constant *C2) {
1649 if (Opcode == Instruction::ICmp)
1650 return getICmp(predicate, C1, C2);
1651 return getFCmp(predicate, C1, C2);
1654 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1657 case Instruction::Add:
1658 case Instruction::Sub:
1659 case Instruction::Mul:
1660 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1661 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1662 isa<PackedType>(C1->getType())) &&
1663 "Tried to create an arithmetic operation on a non-arithmetic type!");
1665 case Instruction::UDiv:
1666 case Instruction::SDiv:
1667 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1668 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1669 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1670 "Tried to create an arithmetic operation on a non-arithmetic type!");
1672 case Instruction::FDiv:
1673 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1674 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1675 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1676 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1678 case Instruction::URem:
1679 case Instruction::SRem:
1680 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1681 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1682 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1683 "Tried to create an arithmetic operation on a non-arithmetic type!");
1685 case Instruction::FRem:
1686 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1687 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1688 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1689 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1691 case Instruction::And:
1692 case Instruction::Or:
1693 case Instruction::Xor:
1694 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1695 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1696 "Tried to create a logical operation on a non-integral type!");
1698 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1699 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1700 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1702 case Instruction::Shl:
1703 case Instruction::LShr:
1704 case Instruction::AShr:
1705 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1706 assert(C1->getType()->isInteger() &&
1707 "Tried to create a shift operation on a non-integer type!");
1714 return getTy(C1->getType(), Opcode, C1, C2);
1717 Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1718 Constant *C1, Constant *C2) {
1719 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1720 return getCompareTy(Opcode, pred, C1, C2);
1723 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1724 Constant *V1, Constant *V2) {
1725 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1726 assert(V1->getType() == V2->getType() && "Select value types must match!");
1727 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1729 if (ReqTy == V1->getType())
1730 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1731 return SC; // Fold common cases
1733 std::vector<Constant*> argVec(3, C);
1736 ExprMapKeyType Key(Instruction::Select, argVec);
1737 return ExprConstants->getOrCreate(ReqTy, Key);
1740 /// getShiftTy - Return a shift left or shift right constant expr
1741 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1742 Constant *C1, Constant *C2) {
1743 // Check the operands for consistency first
1744 assert((Opcode == Instruction::Shl ||
1745 Opcode == Instruction::LShr ||
1746 Opcode == Instruction::AShr) &&
1747 "Invalid opcode in binary constant expression");
1748 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1749 "Invalid operand types for Shift constant expr!");
1751 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1752 return FC; // Fold a few common cases...
1754 // Look up the constant in the table first to ensure uniqueness
1755 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1756 ExprMapKeyType Key(Opcode, argVec);
1757 return ExprConstants->getOrCreate(ReqTy, Key);
1760 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1761 const std::vector<Value*> &IdxList) {
1762 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1763 "GEP indices invalid!");
1765 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1766 return FC; // Fold a few common cases...
1768 assert(isa<PointerType>(C->getType()) &&
1769 "Non-pointer type for constant GetElementPtr expression");
1770 // Look up the constant in the table first to ensure uniqueness
1771 std::vector<Constant*> ArgVec;
1772 ArgVec.reserve(IdxList.size()+1);
1773 ArgVec.push_back(C);
1774 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1775 ArgVec.push_back(cast<Constant>(IdxList[i]));
1776 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1777 return ExprConstants->getOrCreate(ReqTy, Key);
1780 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1781 const std::vector<Constant*> &IdxList){
1782 // Get the result type of the getelementptr!
1783 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1785 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1787 assert(Ty && "GEP indices invalid!");
1788 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1791 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1792 const std::vector<Value*> &IdxList) {
1793 // Get the result type of the getelementptr!
1794 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1796 assert(Ty && "GEP indices invalid!");
1797 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1801 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1802 assert(LHS->getType() == RHS->getType());
1803 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1804 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1806 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1807 return FC; // Fold a few common cases...
1809 // Look up the constant in the table first to ensure uniqueness
1810 std::vector<Constant*> ArgVec;
1811 ArgVec.push_back(LHS);
1812 ArgVec.push_back(RHS);
1813 // Fake up an opcode value that encodes both the opcode and predicate
1814 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1815 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1819 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1820 assert(LHS->getType() == RHS->getType());
1821 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1823 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1824 return FC; // Fold a few common cases...
1826 // Look up the constant in the table first to ensure uniqueness
1827 std::vector<Constant*> ArgVec;
1828 ArgVec.push_back(LHS);
1829 ArgVec.push_back(RHS);
1830 // Fake up an opcode value that encodes both the opcode and predicate
1831 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1832 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1835 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1837 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1838 return FC; // Fold a few common cases...
1839 // Look up the constant in the table first to ensure uniqueness
1840 std::vector<Constant*> ArgVec(1, Val);
1841 ArgVec.push_back(Idx);
1842 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1843 return ExprConstants->getOrCreate(ReqTy, Key);
1846 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1847 assert(isa<PackedType>(Val->getType()) &&
1848 "Tried to create extractelement operation on non-packed type!");
1849 assert(Idx->getType() == Type::UIntTy &&
1850 "Extractelement index must be uint type!");
1851 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1855 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1856 Constant *Elt, Constant *Idx) {
1857 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1858 return FC; // Fold a few common cases...
1859 // Look up the constant in the table first to ensure uniqueness
1860 std::vector<Constant*> ArgVec(1, Val);
1861 ArgVec.push_back(Elt);
1862 ArgVec.push_back(Idx);
1863 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1864 return ExprConstants->getOrCreate(ReqTy, Key);
1867 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1869 assert(isa<PackedType>(Val->getType()) &&
1870 "Tried to create insertelement operation on non-packed type!");
1871 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1872 && "Insertelement types must match!");
1873 assert(Idx->getType() == Type::UIntTy &&
1874 "Insertelement index must be uint type!");
1875 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1879 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1880 Constant *V2, Constant *Mask) {
1881 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1882 return FC; // Fold a few common cases...
1883 // Look up the constant in the table first to ensure uniqueness
1884 std::vector<Constant*> ArgVec(1, V1);
1885 ArgVec.push_back(V2);
1886 ArgVec.push_back(Mask);
1887 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1888 return ExprConstants->getOrCreate(ReqTy, Key);
1891 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1893 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1894 "Invalid shuffle vector constant expr operands!");
1895 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1898 // destroyConstant - Remove the constant from the constant table...
1900 void ConstantExpr::destroyConstant() {
1901 ExprConstants->remove(this);
1902 destroyConstantImpl();
1905 const char *ConstantExpr::getOpcodeName() const {
1906 return Instruction::getOpcodeName(getOpcode());
1909 //===----------------------------------------------------------------------===//
1910 // replaceUsesOfWithOnConstant implementations
1912 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1914 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1915 Constant *ToC = cast<Constant>(To);
1917 unsigned OperandToUpdate = U-OperandList;
1918 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1920 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1921 Lookup.first.first = getType();
1922 Lookup.second = this;
1924 std::vector<Constant*> &Values = Lookup.first.second;
1925 Values.reserve(getNumOperands()); // Build replacement array.
1927 // Fill values with the modified operands of the constant array. Also,
1928 // compute whether this turns into an all-zeros array.
1929 bool isAllZeros = false;
1930 if (!ToC->isNullValue()) {
1931 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1932 Values.push_back(cast<Constant>(O->get()));
1935 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1936 Constant *Val = cast<Constant>(O->get());
1937 Values.push_back(Val);
1938 if (isAllZeros) isAllZeros = Val->isNullValue();
1941 Values[OperandToUpdate] = ToC;
1943 Constant *Replacement = 0;
1945 Replacement = ConstantAggregateZero::get(getType());
1947 // Check to see if we have this array type already.
1949 ArrayConstantsTy::MapTy::iterator I =
1950 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1953 Replacement = I->second;
1955 // Okay, the new shape doesn't exist in the system yet. Instead of
1956 // creating a new constant array, inserting it, replaceallusesof'ing the
1957 // old with the new, then deleting the old... just update the current one
1959 ArrayConstants->MoveConstantToNewSlot(this, I);
1961 // Update to the new value.
1962 setOperand(OperandToUpdate, ToC);
1967 // Otherwise, I do need to replace this with an existing value.
1968 assert(Replacement != this && "I didn't contain From!");
1970 // Everyone using this now uses the replacement.
1971 uncheckedReplaceAllUsesWith(Replacement);
1973 // Delete the old constant!
1977 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1979 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1980 Constant *ToC = cast<Constant>(To);
1982 unsigned OperandToUpdate = U-OperandList;
1983 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1985 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1986 Lookup.first.first = getType();
1987 Lookup.second = this;
1988 std::vector<Constant*> &Values = Lookup.first.second;
1989 Values.reserve(getNumOperands()); // Build replacement struct.
1992 // Fill values with the modified operands of the constant struct. Also,
1993 // compute whether this turns into an all-zeros struct.
1994 bool isAllZeros = false;
1995 if (!ToC->isNullValue()) {
1996 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1997 Values.push_back(cast<Constant>(O->get()));
2000 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2001 Constant *Val = cast<Constant>(O->get());
2002 Values.push_back(Val);
2003 if (isAllZeros) isAllZeros = Val->isNullValue();
2006 Values[OperandToUpdate] = ToC;
2008 Constant *Replacement = 0;
2010 Replacement = ConstantAggregateZero::get(getType());
2012 // Check to see if we have this array type already.
2014 StructConstantsTy::MapTy::iterator I =
2015 StructConstants->InsertOrGetItem(Lookup, Exists);
2018 Replacement = I->second;
2020 // Okay, the new shape doesn't exist in the system yet. Instead of
2021 // creating a new constant struct, inserting it, replaceallusesof'ing the
2022 // old with the new, then deleting the old... just update the current one
2024 StructConstants->MoveConstantToNewSlot(this, I);
2026 // Update to the new value.
2027 setOperand(OperandToUpdate, ToC);
2032 assert(Replacement != this && "I didn't contain From!");
2034 // Everyone using this now uses the replacement.
2035 uncheckedReplaceAllUsesWith(Replacement);
2037 // Delete the old constant!
2041 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2043 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2045 std::vector<Constant*> Values;
2046 Values.reserve(getNumOperands()); // Build replacement array...
2047 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2048 Constant *Val = getOperand(i);
2049 if (Val == From) Val = cast<Constant>(To);
2050 Values.push_back(Val);
2053 Constant *Replacement = ConstantPacked::get(getType(), Values);
2054 assert(Replacement != this && "I didn't contain From!");
2056 // Everyone using this now uses the replacement.
2057 uncheckedReplaceAllUsesWith(Replacement);
2059 // Delete the old constant!
2063 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2065 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2066 Constant *To = cast<Constant>(ToV);
2068 Constant *Replacement = 0;
2069 if (getOpcode() == Instruction::GetElementPtr) {
2070 std::vector<Constant*> Indices;
2071 Constant *Pointer = getOperand(0);
2072 Indices.reserve(getNumOperands()-1);
2073 if (Pointer == From) Pointer = To;
2075 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2076 Constant *Val = getOperand(i);
2077 if (Val == From) Val = To;
2078 Indices.push_back(Val);
2080 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2081 } else if (isCast()) {
2082 assert(getOperand(0) == From && "Cast only has one use!");
2083 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2084 } else if (getOpcode() == Instruction::Select) {
2085 Constant *C1 = getOperand(0);
2086 Constant *C2 = getOperand(1);
2087 Constant *C3 = getOperand(2);
2088 if (C1 == From) C1 = To;
2089 if (C2 == From) C2 = To;
2090 if (C3 == From) C3 = To;
2091 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2092 } else if (getOpcode() == Instruction::ExtractElement) {
2093 Constant *C1 = getOperand(0);
2094 Constant *C2 = getOperand(1);
2095 if (C1 == From) C1 = To;
2096 if (C2 == From) C2 = To;
2097 Replacement = ConstantExpr::getExtractElement(C1, C2);
2098 } else if (getOpcode() == Instruction::InsertElement) {
2099 Constant *C1 = getOperand(0);
2100 Constant *C2 = getOperand(1);
2101 Constant *C3 = getOperand(1);
2102 if (C1 == From) C1 = To;
2103 if (C2 == From) C2 = To;
2104 if (C3 == From) C3 = To;
2105 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2106 } else if (getOpcode() == Instruction::ShuffleVector) {
2107 Constant *C1 = getOperand(0);
2108 Constant *C2 = getOperand(1);
2109 Constant *C3 = getOperand(2);
2110 if (C1 == From) C1 = To;
2111 if (C2 == From) C2 = To;
2112 if (C3 == From) C3 = To;
2113 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2114 } else if (isCompare()) {
2115 Constant *C1 = getOperand(0);
2116 Constant *C2 = getOperand(1);
2117 if (C1 == From) C1 = To;
2118 if (C2 == From) C2 = To;
2119 if (getOpcode() == Instruction::ICmp)
2120 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2122 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2123 } else if (getNumOperands() == 2) {
2124 Constant *C1 = getOperand(0);
2125 Constant *C2 = getOperand(1);
2126 if (C1 == From) C1 = To;
2127 if (C2 == From) C2 = To;
2128 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2130 assert(0 && "Unknown ConstantExpr type!");
2134 assert(Replacement != this && "I didn't contain From!");
2136 // Everyone using this now uses the replacement.
2137 uncheckedReplaceAllUsesWith(Replacement);
2139 // Delete the old constant!
2144 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2145 /// global into a string value. Return an empty string if we can't do it.
2146 /// Parameter Chop determines if the result is chopped at the first null
2149 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2151 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2152 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2153 if (Init->isString()) {
2154 std::string Result = Init->getAsString();
2155 if (Offset < Result.size()) {
2156 // If we are pointing INTO The string, erase the beginning...
2157 Result.erase(Result.begin(), Result.begin()+Offset);
2159 // Take off the null terminator, and any string fragments after it.
2161 std::string::size_type NullPos = Result.find_first_of((char)0);
2162 if (NullPos != std::string::npos)
2163 Result.erase(Result.begin()+NullPos, Result.end());
2169 } else if (Constant *C = dyn_cast<Constant>(this)) {
2170 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2171 return GV->getStringValue(Chop, Offset);
2172 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2173 if (CE->getOpcode() == Instruction::GetElementPtr) {
2174 // Turn a gep into the specified offset.
2175 if (CE->getNumOperands() == 3 &&
2176 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2177 isa<ConstantInt>(CE->getOperand(2))) {
2178 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2179 return CE->getOperand(0)->getStringValue(Chop, Offset);