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/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/SmallVector.h"
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 void Constant::destroyConstantImpl() {
35 // When a Constant is destroyed, there may be lingering
36 // references to the constant by other constants in the constant pool. These
37 // constants are implicitly dependent on the module that is being deleted,
38 // but they don't know that. Because we only find out when the CPV is
39 // deleted, we must now notify all of our users (that should only be
40 // Constants) that they are, in fact, invalid now and should be deleted.
42 while (!use_empty()) {
43 Value *V = use_back();
44 #ifndef NDEBUG // Only in -g mode...
45 if (!isa<Constant>(V))
46 DOUT << "While deleting: " << *this
47 << "\n\nUse still stuck around after Def is destroyed: "
50 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
51 Constant *CV = cast<Constant>(V);
52 CV->destroyConstant();
54 // The constant should remove itself from our use list...
55 assert((use_empty() || use_back() != V) && "Constant not removed!");
58 // Value has no outstanding references it is safe to delete it now...
62 /// canTrap - Return true if evaluation of this constant could trap. This is
63 /// true for things like constant expressions that could divide by zero.
64 bool Constant::canTrap() const {
65 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
66 // The only thing that could possibly trap are constant exprs.
67 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
68 if (!CE) return false;
70 // ConstantExpr traps if any operands can trap.
71 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
72 if (getOperand(i)->canTrap())
75 // Otherwise, only specific operations can trap.
76 switch (CE->getOpcode()) {
79 case Instruction::UDiv:
80 case Instruction::SDiv:
81 case Instruction::FDiv:
82 case Instruction::URem:
83 case Instruction::SRem:
84 case Instruction::FRem:
85 // Div and rem can trap if the RHS is not known to be non-zero.
86 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::IntegerTyID:
96 return ConstantInt::get(Ty, 0);
98 case Type::DoubleTyID:
99 return ConstantFP::get(Ty, 0.0);
100 case Type::PointerTyID:
101 return ConstantPointerNull::get(cast<PointerType>(Ty));
102 case Type::StructTyID:
103 case Type::ArrayTyID:
104 case Type::VectorTyID:
105 return ConstantAggregateZero::get(Ty);
107 // Function, Label, or Opaque type?
108 assert(!"Cannot create a null constant of that type!");
114 // Static constructor to create an integral constant with all bits set
115 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
116 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
117 if (ITy->getBitWidth() == 1)
118 return ConstantInt::getTrue();
120 return ConstantInt::get(Ty, int64_t(-1));
124 /// @returns the value for an packed integer constant of the given type that
125 /// has all its bits set to true.
126 /// @brief Get the all ones value
127 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
128 std::vector<Constant*> Elts;
129 Elts.resize(Ty->getNumElements(),
130 ConstantInt::getAllOnesValue(Ty->getElementType()));
131 assert(Elts[0] && "Not a packed integer type!");
132 return cast<ConstantVector>(ConstantVector::get(Elts));
136 //===----------------------------------------------------------------------===//
137 // ConstantXXX Classes
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
141 // Normal Constructors
143 ConstantInt::ConstantInt(const IntegerType *Ty, uint64_t V)
144 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
147 ConstantFP::ConstantFP(const Type *Ty, double V)
148 : Constant(Ty, ConstantFPVal, 0, 0) {
149 assert(isValueValidForType(Ty, V) && "Value too large for type!");
153 ConstantArray::ConstantArray(const ArrayType *T,
154 const std::vector<Constant*> &V)
155 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
156 assert(V.size() == T->getNumElements() &&
157 "Invalid initializer vector for constant array");
158 Use *OL = OperandList;
159 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
162 assert((C->getType() == T->getElementType() ||
164 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
165 "Initializer for array element doesn't match array element type!");
170 ConstantArray::~ConstantArray() {
171 delete [] OperandList;
174 ConstantStruct::ConstantStruct(const StructType *T,
175 const std::vector<Constant*> &V)
176 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
177 assert(V.size() == T->getNumElements() &&
178 "Invalid initializer vector for constant structure");
179 Use *OL = OperandList;
180 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
183 assert((C->getType() == T->getElementType(I-V.begin()) ||
184 ((T->getElementType(I-V.begin())->isAbstract() ||
185 C->getType()->isAbstract()) &&
186 T->getElementType(I-V.begin())->getTypeID() ==
187 C->getType()->getTypeID())) &&
188 "Initializer for struct element doesn't match struct element type!");
193 ConstantStruct::~ConstantStruct() {
194 delete [] OperandList;
198 ConstantVector::ConstantVector(const VectorType *T,
199 const std::vector<Constant*> &V)
200 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
201 Use *OL = OperandList;
202 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
205 assert((C->getType() == T->getElementType() ||
207 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
208 "Initializer for packed element doesn't match packed element type!");
213 ConstantVector::~ConstantVector() {
214 delete [] OperandList;
217 // We declare several classes private to this file, so use an anonymous
221 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
222 /// behind the scenes to implement unary constant exprs.
223 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
226 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
227 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
230 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
231 /// behind the scenes to implement binary constant exprs.
232 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
235 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
236 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
237 Ops[0].init(C1, this);
238 Ops[1].init(C2, this);
242 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
243 /// behind the scenes to implement select constant exprs.
244 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
247 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
248 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
249 Ops[0].init(C1, this);
250 Ops[1].init(C2, this);
251 Ops[2].init(C3, this);
255 /// ExtractElementConstantExpr - This class is private to
256 /// Constants.cpp, and is used behind the scenes to implement
257 /// extractelement constant exprs.
258 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
261 ExtractElementConstantExpr(Constant *C1, Constant *C2)
262 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
263 Instruction::ExtractElement, Ops, 2) {
264 Ops[0].init(C1, this);
265 Ops[1].init(C2, this);
269 /// InsertElementConstantExpr - This class is private to
270 /// Constants.cpp, and is used behind the scenes to implement
271 /// insertelement constant exprs.
272 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
275 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
276 : ConstantExpr(C1->getType(), Instruction::InsertElement,
278 Ops[0].init(C1, this);
279 Ops[1].init(C2, this);
280 Ops[2].init(C3, this);
284 /// ShuffleVectorConstantExpr - This class is private to
285 /// Constants.cpp, and is used behind the scenes to implement
286 /// shufflevector constant exprs.
287 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
290 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
291 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
293 Ops[0].init(C1, this);
294 Ops[1].init(C2, this);
295 Ops[2].init(C3, this);
299 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
300 /// used behind the scenes to implement getelementpr constant exprs.
301 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
302 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
304 : ConstantExpr(DestTy, Instruction::GetElementPtr,
305 new Use[IdxList.size()+1], IdxList.size()+1) {
306 OperandList[0].init(C, this);
307 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
308 OperandList[i+1].init(IdxList[i], this);
310 ~GetElementPtrConstantExpr() {
311 delete [] OperandList;
315 // CompareConstantExpr - This class is private to Constants.cpp, and is used
316 // behind the scenes to implement ICmp and FCmp constant expressions. This is
317 // needed in order to store the predicate value for these instructions.
318 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
319 unsigned short predicate;
321 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
322 Constant* LHS, Constant* RHS)
323 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
324 OperandList[0].init(LHS, this);
325 OperandList[1].init(RHS, this);
329 } // end anonymous namespace
332 // Utility function for determining if a ConstantExpr is a CastOp or not. This
333 // can't be inline because we don't want to #include Instruction.h into
335 bool ConstantExpr::isCast() const {
336 return Instruction::isCast(getOpcode());
339 bool ConstantExpr::isCompare() const {
340 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
343 /// ConstantExpr::get* - Return some common constants without having to
344 /// specify the full Instruction::OPCODE identifier.
346 Constant *ConstantExpr::getNeg(Constant *C) {
347 return get(Instruction::Sub,
348 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
351 Constant *ConstantExpr::getNot(Constant *C) {
352 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
353 return get(Instruction::Xor, C,
354 ConstantInt::getAllOnesValue(C->getType()));
356 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
357 return get(Instruction::Add, C1, C2);
359 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
360 return get(Instruction::Sub, C1, C2);
362 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
363 return get(Instruction::Mul, C1, C2);
365 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
366 return get(Instruction::UDiv, C1, C2);
368 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
369 return get(Instruction::SDiv, C1, C2);
371 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
372 return get(Instruction::FDiv, C1, C2);
374 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
375 return get(Instruction::URem, C1, C2);
377 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
378 return get(Instruction::SRem, C1, C2);
380 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
381 return get(Instruction::FRem, C1, C2);
383 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
384 return get(Instruction::And, C1, C2);
386 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
387 return get(Instruction::Or, C1, C2);
389 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
390 return get(Instruction::Xor, C1, C2);
392 unsigned ConstantExpr::getPredicate() const {
393 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
394 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
396 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
397 return get(Instruction::Shl, C1, C2);
399 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
400 return get(Instruction::LShr, C1, C2);
402 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
403 return get(Instruction::AShr, C1, C2);
406 /// getWithOperandReplaced - Return a constant expression identical to this
407 /// one, but with the specified operand set to the specified value.
409 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
410 assert(OpNo < getNumOperands() && "Operand num is out of range!");
411 assert(Op->getType() == getOperand(OpNo)->getType() &&
412 "Replacing operand with value of different type!");
413 if (getOperand(OpNo) == Op)
414 return const_cast<ConstantExpr*>(this);
416 Constant *Op0, *Op1, *Op2;
417 switch (getOpcode()) {
418 case Instruction::Trunc:
419 case Instruction::ZExt:
420 case Instruction::SExt:
421 case Instruction::FPTrunc:
422 case Instruction::FPExt:
423 case Instruction::UIToFP:
424 case Instruction::SIToFP:
425 case Instruction::FPToUI:
426 case Instruction::FPToSI:
427 case Instruction::PtrToInt:
428 case Instruction::IntToPtr:
429 case Instruction::BitCast:
430 return ConstantExpr::getCast(getOpcode(), Op, getType());
431 case Instruction::Select:
432 Op0 = (OpNo == 0) ? Op : getOperand(0);
433 Op1 = (OpNo == 1) ? Op : getOperand(1);
434 Op2 = (OpNo == 2) ? Op : getOperand(2);
435 return ConstantExpr::getSelect(Op0, Op1, Op2);
436 case Instruction::InsertElement:
437 Op0 = (OpNo == 0) ? Op : getOperand(0);
438 Op1 = (OpNo == 1) ? Op : getOperand(1);
439 Op2 = (OpNo == 2) ? Op : getOperand(2);
440 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
441 case Instruction::ExtractElement:
442 Op0 = (OpNo == 0) ? Op : getOperand(0);
443 Op1 = (OpNo == 1) ? Op : getOperand(1);
444 return ConstantExpr::getExtractElement(Op0, Op1);
445 case Instruction::ShuffleVector:
446 Op0 = (OpNo == 0) ? Op : getOperand(0);
447 Op1 = (OpNo == 1) ? Op : getOperand(1);
448 Op2 = (OpNo == 2) ? Op : getOperand(2);
449 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
450 case Instruction::GetElementPtr: {
451 SmallVector<Constant*, 8> Ops;
452 Ops.resize(getNumOperands());
453 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
454 Ops[i] = getOperand(i);
456 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
458 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
461 assert(getNumOperands() == 2 && "Must be binary operator?");
462 Op0 = (OpNo == 0) ? Op : getOperand(0);
463 Op1 = (OpNo == 1) ? Op : getOperand(1);
464 return ConstantExpr::get(getOpcode(), Op0, Op1);
468 /// getWithOperands - This returns the current constant expression with the
469 /// operands replaced with the specified values. The specified operands must
470 /// match count and type with the existing ones.
471 Constant *ConstantExpr::
472 getWithOperands(const std::vector<Constant*> &Ops) const {
473 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
474 bool AnyChange = false;
475 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
476 assert(Ops[i]->getType() == getOperand(i)->getType() &&
477 "Operand type mismatch!");
478 AnyChange |= Ops[i] != getOperand(i);
480 if (!AnyChange) // No operands changed, return self.
481 return const_cast<ConstantExpr*>(this);
483 switch (getOpcode()) {
484 case Instruction::Trunc:
485 case Instruction::ZExt:
486 case Instruction::SExt:
487 case Instruction::FPTrunc:
488 case Instruction::FPExt:
489 case Instruction::UIToFP:
490 case Instruction::SIToFP:
491 case Instruction::FPToUI:
492 case Instruction::FPToSI:
493 case Instruction::PtrToInt:
494 case Instruction::IntToPtr:
495 case Instruction::BitCast:
496 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
497 case Instruction::Select:
498 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
499 case Instruction::InsertElement:
500 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
501 case Instruction::ExtractElement:
502 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
503 case Instruction::ShuffleVector:
504 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
505 case Instruction::GetElementPtr:
506 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
507 case Instruction::ICmp:
508 case Instruction::FCmp:
509 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
511 assert(getNumOperands() == 2 && "Must be binary operator?");
512 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
517 //===----------------------------------------------------------------------===//
518 // isValueValidForType implementations
520 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
521 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
522 if (Ty == Type::Int1Ty)
523 return Val == 0 || Val == 1;
525 return true; // always true, has to fit in largest type
526 uint64_t Max = (1ll << NumBits) - 1;
530 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
531 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
532 if (Ty == Type::Int1Ty)
533 return Val == 0 || Val == 1 || Val == -1;
535 return true; // always true, has to fit in largest type
536 int64_t Min = -(1ll << (NumBits-1));
537 int64_t Max = (1ll << (NumBits-1)) - 1;
538 return (Val >= Min && Val <= Max);
541 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
542 switch (Ty->getTypeID()) {
544 return false; // These can't be represented as floating point!
546 // TODO: Figure out how to test if a double can be cast to a float!
547 case Type::FloatTyID:
548 case Type::DoubleTyID:
549 return true; // This is the largest type...
553 //===----------------------------------------------------------------------===//
554 // Factory Function Implementation
556 // ConstantCreator - A class that is used to create constants by
557 // ValueMap*. This class should be partially specialized if there is
558 // something strange that needs to be done to interface to the ctor for the
562 template<class ConstantClass, class TypeClass, class ValType>
563 struct VISIBILITY_HIDDEN ConstantCreator {
564 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
565 return new ConstantClass(Ty, V);
569 template<class ConstantClass, class TypeClass>
570 struct VISIBILITY_HIDDEN ConvertConstantType {
571 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
572 assert(0 && "This type cannot be converted!\n");
577 template<class ValType, class TypeClass, class ConstantClass,
578 bool HasLargeKey = false /*true for arrays and structs*/ >
579 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
581 typedef std::pair<const Type*, ValType> MapKey;
582 typedef std::map<MapKey, Constant *> MapTy;
583 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
584 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
586 /// Map - This is the main map from the element descriptor to the Constants.
587 /// This is the primary way we avoid creating two of the same shape
591 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
592 /// from the constants to their element in Map. This is important for
593 /// removal of constants from the array, which would otherwise have to scan
594 /// through the map with very large keys.
595 InverseMapTy InverseMap;
597 /// AbstractTypeMap - Map for abstract type constants.
599 AbstractTypeMapTy AbstractTypeMap;
602 void clear(std::vector<Constant *> &Constants) {
603 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
604 Constants.push_back(I->second);
606 AbstractTypeMap.clear();
611 typename MapTy::iterator map_end() { return Map.end(); }
613 /// InsertOrGetItem - Return an iterator for the specified element.
614 /// If the element exists in the map, the returned iterator points to the
615 /// entry and Exists=true. If not, the iterator points to the newly
616 /// inserted entry and returns Exists=false. Newly inserted entries have
617 /// I->second == 0, and should be filled in.
618 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
621 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
627 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
629 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
630 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
631 IMI->second->second == CP &&
632 "InverseMap corrupt!");
636 typename MapTy::iterator I =
637 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
638 if (I == Map.end() || I->second != CP) {
639 // FIXME: This should not use a linear scan. If this gets to be a
640 // performance problem, someone should look at this.
641 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
648 /// getOrCreate - Return the specified constant from the map, creating it if
650 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
651 MapKey Lookup(Ty, V);
652 typename MapTy::iterator I = Map.lower_bound(Lookup);
654 if (I != Map.end() && I->first == Lookup)
655 return static_cast<ConstantClass *>(I->second);
657 // If no preexisting value, create one now...
658 ConstantClass *Result =
659 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
661 /// FIXME: why does this assert fail when loading 176.gcc?
662 //assert(Result->getType() == Ty && "Type specified is not correct!");
663 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
665 if (HasLargeKey) // Remember the reverse mapping if needed.
666 InverseMap.insert(std::make_pair(Result, I));
668 // If the type of the constant is abstract, make sure that an entry exists
669 // for it in the AbstractTypeMap.
670 if (Ty->isAbstract()) {
671 typename AbstractTypeMapTy::iterator TI =
672 AbstractTypeMap.lower_bound(Ty);
674 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
675 // Add ourselves to the ATU list of the type.
676 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
678 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
684 void remove(ConstantClass *CP) {
685 typename MapTy::iterator I = FindExistingElement(CP);
686 assert(I != Map.end() && "Constant not found in constant table!");
687 assert(I->second == CP && "Didn't find correct element?");
689 if (HasLargeKey) // Remember the reverse mapping if needed.
690 InverseMap.erase(CP);
692 // Now that we found the entry, make sure this isn't the entry that
693 // the AbstractTypeMap points to.
694 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
695 if (Ty->isAbstract()) {
696 assert(AbstractTypeMap.count(Ty) &&
697 "Abstract type not in AbstractTypeMap?");
698 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
699 if (ATMEntryIt == I) {
700 // Yes, we are removing the representative entry for this type.
701 // See if there are any other entries of the same type.
702 typename MapTy::iterator TmpIt = ATMEntryIt;
704 // First check the entry before this one...
705 if (TmpIt != Map.begin()) {
707 if (TmpIt->first.first != Ty) // Not the same type, move back...
711 // If we didn't find the same type, try to move forward...
712 if (TmpIt == ATMEntryIt) {
714 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
715 --TmpIt; // No entry afterwards with the same type
718 // If there is another entry in the map of the same abstract type,
719 // update the AbstractTypeMap entry now.
720 if (TmpIt != ATMEntryIt) {
723 // Otherwise, we are removing the last instance of this type
724 // from the table. Remove from the ATM, and from user list.
725 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
726 AbstractTypeMap.erase(Ty);
735 /// MoveConstantToNewSlot - If we are about to change C to be the element
736 /// specified by I, update our internal data structures to reflect this
738 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
739 // First, remove the old location of the specified constant in the map.
740 typename MapTy::iterator OldI = FindExistingElement(C);
741 assert(OldI != Map.end() && "Constant not found in constant table!");
742 assert(OldI->second == C && "Didn't find correct element?");
744 // If this constant is the representative element for its abstract type,
745 // update the AbstractTypeMap so that the representative element is I.
746 if (C->getType()->isAbstract()) {
747 typename AbstractTypeMapTy::iterator ATI =
748 AbstractTypeMap.find(C->getType());
749 assert(ATI != AbstractTypeMap.end() &&
750 "Abstract type not in AbstractTypeMap?");
751 if (ATI->second == OldI)
755 // Remove the old entry from the map.
758 // Update the inverse map so that we know that this constant is now
759 // located at descriptor I.
761 assert(I->second == C && "Bad inversemap entry!");
766 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
767 typename AbstractTypeMapTy::iterator I =
768 AbstractTypeMap.find(cast<Type>(OldTy));
770 assert(I != AbstractTypeMap.end() &&
771 "Abstract type not in AbstractTypeMap?");
773 // Convert a constant at a time until the last one is gone. The last one
774 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
775 // eliminated eventually.
777 ConvertConstantType<ConstantClass,
779 static_cast<ConstantClass *>(I->second->second),
780 cast<TypeClass>(NewTy));
782 I = AbstractTypeMap.find(cast<Type>(OldTy));
783 } while (I != AbstractTypeMap.end());
786 // If the type became concrete without being refined to any other existing
787 // type, we just remove ourselves from the ATU list.
788 void typeBecameConcrete(const DerivedType *AbsTy) {
789 AbsTy->removeAbstractTypeUser(this);
793 DOUT << "Constant.cpp: ValueMap\n";
799 //---- ConstantInt::get() implementations...
801 static ManagedStatic<ValueMap<uint64_t, IntegerType, ConstantInt> >IntConstants;
803 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
804 // to a uint64_t value that has been zero extended down to the size of the
805 // integer type of the ConstantInt. This allows the getZExtValue method to
806 // just return the stored value while getSExtValue has to convert back to sign
807 // extended. getZExtValue is more common in LLVM than getSExtValue().
808 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
809 const IntegerType *ITy = cast<IntegerType>(Ty);
810 if (Ty == Type::Int1Ty)
815 return IntConstants->getOrCreate(ITy, V & ITy->getBitMask());
818 //---- ConstantFP::get() implementation...
822 struct ConstantCreator<ConstantFP, Type, uint64_t> {
823 static ConstantFP *create(const Type *Ty, uint64_t V) {
824 assert(Ty == Type::DoubleTy);
825 return new ConstantFP(Ty, BitsToDouble(V));
829 struct ConstantCreator<ConstantFP, Type, uint32_t> {
830 static ConstantFP *create(const Type *Ty, uint32_t V) {
831 assert(Ty == Type::FloatTy);
832 return new ConstantFP(Ty, BitsToFloat(V));
837 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
838 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
840 bool ConstantFP::isNullValue() const {
841 return DoubleToBits(Val) == 0;
844 bool ConstantFP::isExactlyValue(double V) const {
845 return DoubleToBits(V) == DoubleToBits(Val);
849 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
850 if (Ty == Type::FloatTy) {
851 // Force the value through memory to normalize it.
852 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
854 assert(Ty == Type::DoubleTy);
855 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
859 //---- ConstantAggregateZero::get() implementation...
862 // ConstantAggregateZero does not take extra "value" argument...
863 template<class ValType>
864 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
865 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
866 return new ConstantAggregateZero(Ty);
871 struct ConvertConstantType<ConstantAggregateZero, Type> {
872 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
873 // Make everyone now use a constant of the new type...
874 Constant *New = ConstantAggregateZero::get(NewTy);
875 assert(New != OldC && "Didn't replace constant??");
876 OldC->uncheckedReplaceAllUsesWith(New);
877 OldC->destroyConstant(); // This constant is now dead, destroy it.
882 static ManagedStatic<ValueMap<char, Type,
883 ConstantAggregateZero> > AggZeroConstants;
885 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
887 Constant *ConstantAggregateZero::get(const Type *Ty) {
888 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
889 "Cannot create an aggregate zero of non-aggregate type!");
890 return AggZeroConstants->getOrCreate(Ty, 0);
893 // destroyConstant - Remove the constant from the constant table...
895 void ConstantAggregateZero::destroyConstant() {
896 AggZeroConstants->remove(this);
897 destroyConstantImpl();
900 //---- ConstantArray::get() implementation...
904 struct ConvertConstantType<ConstantArray, ArrayType> {
905 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
906 // Make everyone now use a constant of the new type...
907 std::vector<Constant*> C;
908 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
909 C.push_back(cast<Constant>(OldC->getOperand(i)));
910 Constant *New = ConstantArray::get(NewTy, C);
911 assert(New != OldC && "Didn't replace constant??");
912 OldC->uncheckedReplaceAllUsesWith(New);
913 OldC->destroyConstant(); // This constant is now dead, destroy it.
918 static std::vector<Constant*> getValType(ConstantArray *CA) {
919 std::vector<Constant*> Elements;
920 Elements.reserve(CA->getNumOperands());
921 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
922 Elements.push_back(cast<Constant>(CA->getOperand(i)));
926 typedef ValueMap<std::vector<Constant*>, ArrayType,
927 ConstantArray, true /*largekey*/> ArrayConstantsTy;
928 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
930 Constant *ConstantArray::get(const ArrayType *Ty,
931 const std::vector<Constant*> &V) {
932 // If this is an all-zero array, return a ConstantAggregateZero object
935 if (!C->isNullValue())
936 return ArrayConstants->getOrCreate(Ty, V);
937 for (unsigned i = 1, e = V.size(); i != e; ++i)
939 return ArrayConstants->getOrCreate(Ty, V);
941 return ConstantAggregateZero::get(Ty);
944 // destroyConstant - Remove the constant from the constant table...
946 void ConstantArray::destroyConstant() {
947 ArrayConstants->remove(this);
948 destroyConstantImpl();
951 /// ConstantArray::get(const string&) - Return an array that is initialized to
952 /// contain the specified string. If length is zero then a null terminator is
953 /// added to the specified string so that it may be used in a natural way.
954 /// Otherwise, the length parameter specifies how much of the string to use
955 /// and it won't be null terminated.
957 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
958 std::vector<Constant*> ElementVals;
959 for (unsigned i = 0; i < Str.length(); ++i)
960 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
962 // Add a null terminator to the string...
964 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
967 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
968 return ConstantArray::get(ATy, ElementVals);
971 /// isString - This method returns true if the array is an array of i8, and
972 /// if the elements of the array are all ConstantInt's.
973 bool ConstantArray::isString() const {
974 // Check the element type for i8...
975 if (getType()->getElementType() != Type::Int8Ty)
977 // Check the elements to make sure they are all integers, not constant
979 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
980 if (!isa<ConstantInt>(getOperand(i)))
985 /// isCString - This method returns true if the array is a string (see
986 /// isString) and it ends in a null byte \0 and does not contains any other
987 /// null bytes except its terminator.
988 bool ConstantArray::isCString() const {
989 // Check the element type for i8...
990 if (getType()->getElementType() != Type::Int8Ty)
992 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
993 // Last element must be a null.
994 if (getOperand(getNumOperands()-1) != Zero)
996 // Other elements must be non-null integers.
997 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
998 if (!isa<ConstantInt>(getOperand(i)))
1000 if (getOperand(i) == Zero)
1007 // getAsString - If the sub-element type of this array is i8
1008 // then this method converts the array to an std::string and returns it.
1009 // Otherwise, it asserts out.
1011 std::string ConstantArray::getAsString() const {
1012 assert(isString() && "Not a string!");
1014 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1015 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1020 //---- ConstantStruct::get() implementation...
1025 struct ConvertConstantType<ConstantStruct, StructType> {
1026 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1027 // Make everyone now use a constant of the new type...
1028 std::vector<Constant*> C;
1029 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1030 C.push_back(cast<Constant>(OldC->getOperand(i)));
1031 Constant *New = ConstantStruct::get(NewTy, C);
1032 assert(New != OldC && "Didn't replace constant??");
1034 OldC->uncheckedReplaceAllUsesWith(New);
1035 OldC->destroyConstant(); // This constant is now dead, destroy it.
1040 typedef ValueMap<std::vector<Constant*>, StructType,
1041 ConstantStruct, true /*largekey*/> StructConstantsTy;
1042 static ManagedStatic<StructConstantsTy> StructConstants;
1044 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1045 std::vector<Constant*> Elements;
1046 Elements.reserve(CS->getNumOperands());
1047 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1048 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1052 Constant *ConstantStruct::get(const StructType *Ty,
1053 const std::vector<Constant*> &V) {
1054 // Create a ConstantAggregateZero value if all elements are zeros...
1055 for (unsigned i = 0, e = V.size(); i != e; ++i)
1056 if (!V[i]->isNullValue())
1057 return StructConstants->getOrCreate(Ty, V);
1059 return ConstantAggregateZero::get(Ty);
1062 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1063 std::vector<const Type*> StructEls;
1064 StructEls.reserve(V.size());
1065 for (unsigned i = 0, e = V.size(); i != e; ++i)
1066 StructEls.push_back(V[i]->getType());
1067 return get(StructType::get(StructEls, packed), V);
1070 // destroyConstant - Remove the constant from the constant table...
1072 void ConstantStruct::destroyConstant() {
1073 StructConstants->remove(this);
1074 destroyConstantImpl();
1077 //---- ConstantVector::get() implementation...
1081 struct ConvertConstantType<ConstantVector, VectorType> {
1082 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1083 // Make everyone now use a constant of the new type...
1084 std::vector<Constant*> C;
1085 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1086 C.push_back(cast<Constant>(OldC->getOperand(i)));
1087 Constant *New = ConstantVector::get(NewTy, C);
1088 assert(New != OldC && "Didn't replace constant??");
1089 OldC->uncheckedReplaceAllUsesWith(New);
1090 OldC->destroyConstant(); // This constant is now dead, destroy it.
1095 static std::vector<Constant*> getValType(ConstantVector *CP) {
1096 std::vector<Constant*> Elements;
1097 Elements.reserve(CP->getNumOperands());
1098 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1099 Elements.push_back(CP->getOperand(i));
1103 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1104 ConstantVector> > VectorConstants;
1106 Constant *ConstantVector::get(const VectorType *Ty,
1107 const std::vector<Constant*> &V) {
1108 // If this is an all-zero packed, return a ConstantAggregateZero object
1111 if (!C->isNullValue())
1112 return VectorConstants->getOrCreate(Ty, V);
1113 for (unsigned i = 1, e = V.size(); i != e; ++i)
1115 return VectorConstants->getOrCreate(Ty, V);
1117 return ConstantAggregateZero::get(Ty);
1120 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1121 assert(!V.empty() && "Cannot infer type if V is empty");
1122 return get(VectorType::get(V.front()->getType(),V.size()), V);
1125 // destroyConstant - Remove the constant from the constant table...
1127 void ConstantVector::destroyConstant() {
1128 VectorConstants->remove(this);
1129 destroyConstantImpl();
1132 /// This function will return true iff every element in this packed constant
1133 /// is set to all ones.
1134 /// @returns true iff this constant's emements are all set to all ones.
1135 /// @brief Determine if the value is all ones.
1136 bool ConstantVector::isAllOnesValue() const {
1137 // Check out first element.
1138 const Constant *Elt = getOperand(0);
1139 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1140 if (!CI || !CI->isAllOnesValue()) return false;
1141 // Then make sure all remaining elements point to the same value.
1142 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1143 if (getOperand(I) != Elt) return false;
1148 //---- ConstantPointerNull::get() implementation...
1152 // ConstantPointerNull does not take extra "value" argument...
1153 template<class ValType>
1154 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1155 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1156 return new ConstantPointerNull(Ty);
1161 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1162 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1163 // Make everyone now use a constant of the new type...
1164 Constant *New = ConstantPointerNull::get(NewTy);
1165 assert(New != OldC && "Didn't replace constant??");
1166 OldC->uncheckedReplaceAllUsesWith(New);
1167 OldC->destroyConstant(); // This constant is now dead, destroy it.
1172 static ManagedStatic<ValueMap<char, PointerType,
1173 ConstantPointerNull> > NullPtrConstants;
1175 static char getValType(ConstantPointerNull *) {
1180 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1181 return NullPtrConstants->getOrCreate(Ty, 0);
1184 // destroyConstant - Remove the constant from the constant table...
1186 void ConstantPointerNull::destroyConstant() {
1187 NullPtrConstants->remove(this);
1188 destroyConstantImpl();
1192 //---- UndefValue::get() implementation...
1196 // UndefValue does not take extra "value" argument...
1197 template<class ValType>
1198 struct ConstantCreator<UndefValue, Type, ValType> {
1199 static UndefValue *create(const Type *Ty, const ValType &V) {
1200 return new UndefValue(Ty);
1205 struct ConvertConstantType<UndefValue, Type> {
1206 static void convert(UndefValue *OldC, const Type *NewTy) {
1207 // Make everyone now use a constant of the new type.
1208 Constant *New = UndefValue::get(NewTy);
1209 assert(New != OldC && "Didn't replace constant??");
1210 OldC->uncheckedReplaceAllUsesWith(New);
1211 OldC->destroyConstant(); // This constant is now dead, destroy it.
1216 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1218 static char getValType(UndefValue *) {
1223 UndefValue *UndefValue::get(const Type *Ty) {
1224 return UndefValueConstants->getOrCreate(Ty, 0);
1227 // destroyConstant - Remove the constant from the constant table.
1229 void UndefValue::destroyConstant() {
1230 UndefValueConstants->remove(this);
1231 destroyConstantImpl();
1235 //---- ConstantExpr::get() implementations...
1238 struct ExprMapKeyType {
1239 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1240 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1243 std::vector<Constant*> operands;
1244 bool operator==(const ExprMapKeyType& that) const {
1245 return this->opcode == that.opcode &&
1246 this->predicate == that.predicate &&
1247 this->operands == that.operands;
1249 bool operator<(const ExprMapKeyType & that) const {
1250 return this->opcode < that.opcode ||
1251 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1252 (this->opcode == that.opcode && this->predicate == that.predicate &&
1253 this->operands < that.operands);
1256 bool operator!=(const ExprMapKeyType& that) const {
1257 return !(*this == that);
1263 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1264 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1265 unsigned short pred = 0) {
1266 if (Instruction::isCast(V.opcode))
1267 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1268 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1269 V.opcode < Instruction::BinaryOpsEnd))
1270 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1271 if (V.opcode == Instruction::Select)
1272 return new SelectConstantExpr(V.operands[0], V.operands[1],
1274 if (V.opcode == Instruction::ExtractElement)
1275 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1276 if (V.opcode == Instruction::InsertElement)
1277 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1279 if (V.opcode == Instruction::ShuffleVector)
1280 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1282 if (V.opcode == Instruction::GetElementPtr) {
1283 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1284 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1287 // The compare instructions are weird. We have to encode the predicate
1288 // value and it is combined with the instruction opcode by multiplying
1289 // the opcode by one hundred. We must decode this to get the predicate.
1290 if (V.opcode == Instruction::ICmp)
1291 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1292 V.operands[0], V.operands[1]);
1293 if (V.opcode == Instruction::FCmp)
1294 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1295 V.operands[0], V.operands[1]);
1296 assert(0 && "Invalid ConstantExpr!");
1302 struct ConvertConstantType<ConstantExpr, Type> {
1303 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1305 switch (OldC->getOpcode()) {
1306 case Instruction::Trunc:
1307 case Instruction::ZExt:
1308 case Instruction::SExt:
1309 case Instruction::FPTrunc:
1310 case Instruction::FPExt:
1311 case Instruction::UIToFP:
1312 case Instruction::SIToFP:
1313 case Instruction::FPToUI:
1314 case Instruction::FPToSI:
1315 case Instruction::PtrToInt:
1316 case Instruction::IntToPtr:
1317 case Instruction::BitCast:
1318 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1321 case Instruction::Select:
1322 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1323 OldC->getOperand(1),
1324 OldC->getOperand(2));
1327 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1328 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1329 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1330 OldC->getOperand(1));
1332 case Instruction::GetElementPtr:
1333 // Make everyone now use a constant of the new type...
1334 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1335 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1336 &Idx[0], Idx.size());
1340 assert(New != OldC && "Didn't replace constant??");
1341 OldC->uncheckedReplaceAllUsesWith(New);
1342 OldC->destroyConstant(); // This constant is now dead, destroy it.
1345 } // end namespace llvm
1348 static ExprMapKeyType getValType(ConstantExpr *CE) {
1349 std::vector<Constant*> Operands;
1350 Operands.reserve(CE->getNumOperands());
1351 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1352 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1353 return ExprMapKeyType(CE->getOpcode(), Operands,
1354 CE->isCompare() ? CE->getPredicate() : 0);
1357 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1358 ConstantExpr> > ExprConstants;
1360 /// This is a utility function to handle folding of casts and lookup of the
1361 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1362 static inline Constant *getFoldedCast(
1363 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1364 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1365 // Fold a few common cases
1366 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1369 // Look up the constant in the table first to ensure uniqueness
1370 std::vector<Constant*> argVec(1, C);
1371 ExprMapKeyType Key(opc, argVec);
1372 return ExprConstants->getOrCreate(Ty, Key);
1375 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1376 Instruction::CastOps opc = Instruction::CastOps(oc);
1377 assert(Instruction::isCast(opc) && "opcode out of range");
1378 assert(C && Ty && "Null arguments to getCast");
1379 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1383 assert(0 && "Invalid cast opcode");
1385 case Instruction::Trunc: return getTrunc(C, Ty);
1386 case Instruction::ZExt: return getZExt(C, Ty);
1387 case Instruction::SExt: return getSExt(C, Ty);
1388 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1389 case Instruction::FPExt: return getFPExtend(C, Ty);
1390 case Instruction::UIToFP: return getUIToFP(C, Ty);
1391 case Instruction::SIToFP: return getSIToFP(C, Ty);
1392 case Instruction::FPToUI: return getFPToUI(C, Ty);
1393 case Instruction::FPToSI: return getFPToSI(C, Ty);
1394 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1395 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1396 case Instruction::BitCast: return getBitCast(C, Ty);
1401 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1402 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1403 return getCast(Instruction::BitCast, C, Ty);
1404 return getCast(Instruction::ZExt, C, Ty);
1407 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1408 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1409 return getCast(Instruction::BitCast, C, Ty);
1410 return getCast(Instruction::SExt, C, Ty);
1413 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1414 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1415 return getCast(Instruction::BitCast, C, Ty);
1416 return getCast(Instruction::Trunc, C, Ty);
1419 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1420 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1421 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1423 if (Ty->isInteger())
1424 return getCast(Instruction::PtrToInt, S, Ty);
1425 return getCast(Instruction::BitCast, S, Ty);
1428 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1430 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1431 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1432 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1433 Instruction::CastOps opcode =
1434 (SrcBits == DstBits ? Instruction::BitCast :
1435 (SrcBits > DstBits ? Instruction::Trunc :
1436 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1437 return getCast(opcode, C, Ty);
1440 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1441 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1443 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1444 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1445 if (SrcBits == DstBits)
1446 return C; // Avoid a useless cast
1447 Instruction::CastOps opcode =
1448 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1449 return getCast(opcode, C, Ty);
1452 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1453 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1454 assert(Ty->isInteger() && "Trunc produces only integral");
1455 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1456 "SrcTy must be larger than DestTy for Trunc!");
1458 return getFoldedCast(Instruction::Trunc, C, Ty);
1461 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1462 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1463 assert(Ty->isInteger() && "SExt produces only integer");
1464 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1465 "SrcTy must be smaller than DestTy for SExt!");
1467 return getFoldedCast(Instruction::SExt, C, Ty);
1470 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1471 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1472 assert(Ty->isInteger() && "ZExt produces only integer");
1473 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1474 "SrcTy must be smaller than DestTy for ZExt!");
1476 return getFoldedCast(Instruction::ZExt, C, Ty);
1479 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1480 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1481 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1482 "This is an illegal floating point truncation!");
1483 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1486 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1487 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1488 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1489 "This is an illegal floating point extension!");
1490 return getFoldedCast(Instruction::FPExt, C, Ty);
1493 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1494 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1495 "This is an illegal i32 to floating point cast!");
1496 return getFoldedCast(Instruction::UIToFP, C, Ty);
1499 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1500 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1501 "This is an illegal sint to floating point cast!");
1502 return getFoldedCast(Instruction::SIToFP, C, Ty);
1505 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1506 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1507 "This is an illegal floating point to i32 cast!");
1508 return getFoldedCast(Instruction::FPToUI, C, Ty);
1511 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1512 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1513 "This is an illegal floating point to i32 cast!");
1514 return getFoldedCast(Instruction::FPToSI, C, Ty);
1517 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1518 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1519 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1520 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1523 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1524 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1525 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1526 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1529 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1530 // BitCast implies a no-op cast of type only. No bits change. However, you
1531 // can't cast pointers to anything but pointers.
1532 const Type *SrcTy = C->getType();
1533 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1534 "BitCast cannot cast pointer to non-pointer and vice versa");
1536 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1537 // or nonptr->ptr). For all the other types, the cast is okay if source and
1538 // destination bit widths are identical.
1539 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1540 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1541 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1542 return getFoldedCast(Instruction::BitCast, C, DstTy);
1545 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1546 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1547 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1549 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1550 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1553 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1554 Constant *C1, Constant *C2) {
1555 // Check the operands for consistency first
1556 assert(Opcode >= Instruction::BinaryOpsBegin &&
1557 Opcode < Instruction::BinaryOpsEnd &&
1558 "Invalid opcode in binary constant expression");
1559 assert(C1->getType() == C2->getType() &&
1560 "Operand types in binary constant expression should match");
1562 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1563 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1564 return FC; // Fold a few common cases...
1566 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1567 ExprMapKeyType Key(Opcode, argVec);
1568 return ExprConstants->getOrCreate(ReqTy, Key);
1571 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1572 Constant *C1, Constant *C2) {
1573 switch (predicate) {
1574 default: assert(0 && "Invalid CmpInst predicate");
1575 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1576 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1577 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1578 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1579 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1580 case FCmpInst::FCMP_TRUE:
1581 return getFCmp(predicate, C1, C2);
1582 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1583 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1584 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1585 case ICmpInst::ICMP_SLE:
1586 return getICmp(predicate, C1, C2);
1590 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1593 case Instruction::Add:
1594 case Instruction::Sub:
1595 case Instruction::Mul:
1596 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1597 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1598 isa<VectorType>(C1->getType())) &&
1599 "Tried to create an arithmetic operation on a non-arithmetic type!");
1601 case Instruction::UDiv:
1602 case Instruction::SDiv:
1603 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1604 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1605 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1606 "Tried to create an arithmetic operation on a non-arithmetic type!");
1608 case Instruction::FDiv:
1609 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1610 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1611 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1612 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1614 case Instruction::URem:
1615 case Instruction::SRem:
1616 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1617 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1618 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1619 "Tried to create an arithmetic operation on a non-arithmetic type!");
1621 case Instruction::FRem:
1622 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1623 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1624 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1625 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1627 case Instruction::And:
1628 case Instruction::Or:
1629 case Instruction::Xor:
1630 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1631 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1632 "Tried to create a logical operation on a non-integral type!");
1634 case Instruction::Shl:
1635 case Instruction::LShr:
1636 case Instruction::AShr:
1637 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1638 assert(C1->getType()->isInteger() &&
1639 "Tried to create a shift operation on a non-integer type!");
1646 return getTy(C1->getType(), Opcode, C1, C2);
1649 Constant *ConstantExpr::getCompare(unsigned short pred,
1650 Constant *C1, Constant *C2) {
1651 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1652 return getCompareTy(pred, C1, C2);
1655 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1656 Constant *V1, Constant *V2) {
1657 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1658 assert(V1->getType() == V2->getType() && "Select value types must match!");
1659 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1661 if (ReqTy == V1->getType())
1662 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1663 return SC; // Fold common cases
1665 std::vector<Constant*> argVec(3, C);
1668 ExprMapKeyType Key(Instruction::Select, argVec);
1669 return ExprConstants->getOrCreate(ReqTy, Key);
1672 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1675 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1676 "GEP indices invalid!");
1678 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1679 return FC; // Fold a few common cases...
1681 assert(isa<PointerType>(C->getType()) &&
1682 "Non-pointer type for constant GetElementPtr expression");
1683 // Look up the constant in the table first to ensure uniqueness
1684 std::vector<Constant*> ArgVec;
1685 ArgVec.reserve(NumIdx+1);
1686 ArgVec.push_back(C);
1687 for (unsigned i = 0; i != NumIdx; ++i)
1688 ArgVec.push_back(cast<Constant>(Idxs[i]));
1689 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1690 return ExprConstants->getOrCreate(ReqTy, Key);
1693 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1695 // Get the result type of the getelementptr!
1697 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1698 assert(Ty && "GEP indices invalid!");
1699 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1702 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1704 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1709 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1710 assert(LHS->getType() == RHS->getType());
1711 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1712 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1714 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1715 return FC; // Fold a few common cases...
1717 // Look up the constant in the table first to ensure uniqueness
1718 std::vector<Constant*> ArgVec;
1719 ArgVec.push_back(LHS);
1720 ArgVec.push_back(RHS);
1721 // Get the key type with both the opcode and predicate
1722 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1723 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1727 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1728 assert(LHS->getType() == RHS->getType());
1729 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1731 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1732 return FC; // Fold a few common cases...
1734 // Look up the constant in the table first to ensure uniqueness
1735 std::vector<Constant*> ArgVec;
1736 ArgVec.push_back(LHS);
1737 ArgVec.push_back(RHS);
1738 // Get the key type with both the opcode and predicate
1739 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1740 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1743 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1745 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1746 return FC; // Fold a few common cases...
1747 // Look up the constant in the table first to ensure uniqueness
1748 std::vector<Constant*> ArgVec(1, Val);
1749 ArgVec.push_back(Idx);
1750 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1751 return ExprConstants->getOrCreate(ReqTy, Key);
1754 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1755 assert(isa<VectorType>(Val->getType()) &&
1756 "Tried to create extractelement operation on non-vector type!");
1757 assert(Idx->getType() == Type::Int32Ty &&
1758 "Extractelement index must be i32 type!");
1759 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1763 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1764 Constant *Elt, Constant *Idx) {
1765 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1766 return FC; // Fold a few common cases...
1767 // Look up the constant in the table first to ensure uniqueness
1768 std::vector<Constant*> ArgVec(1, Val);
1769 ArgVec.push_back(Elt);
1770 ArgVec.push_back(Idx);
1771 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1772 return ExprConstants->getOrCreate(ReqTy, Key);
1775 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1777 assert(isa<VectorType>(Val->getType()) &&
1778 "Tried to create insertelement operation on non-vector type!");
1779 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1780 && "Insertelement types must match!");
1781 assert(Idx->getType() == Type::Int32Ty &&
1782 "Insertelement index must be i32 type!");
1783 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1787 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1788 Constant *V2, Constant *Mask) {
1789 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1790 return FC; // Fold a few common cases...
1791 // Look up the constant in the table first to ensure uniqueness
1792 std::vector<Constant*> ArgVec(1, V1);
1793 ArgVec.push_back(V2);
1794 ArgVec.push_back(Mask);
1795 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1796 return ExprConstants->getOrCreate(ReqTy, Key);
1799 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1801 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1802 "Invalid shuffle vector constant expr operands!");
1803 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1806 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1807 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1808 if (PTy->getElementType()->isFloatingPoint()) {
1809 std::vector<Constant*> zeros(PTy->getNumElements(),
1810 ConstantFP::get(PTy->getElementType(),-0.0));
1811 return ConstantVector::get(PTy, zeros);
1814 if (Ty->isFloatingPoint())
1815 return ConstantFP::get(Ty, -0.0);
1817 return Constant::getNullValue(Ty);
1820 // destroyConstant - Remove the constant from the constant table...
1822 void ConstantExpr::destroyConstant() {
1823 ExprConstants->remove(this);
1824 destroyConstantImpl();
1827 const char *ConstantExpr::getOpcodeName() const {
1828 return Instruction::getOpcodeName(getOpcode());
1831 //===----------------------------------------------------------------------===//
1832 // replaceUsesOfWithOnConstant implementations
1834 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1836 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1837 Constant *ToC = cast<Constant>(To);
1839 unsigned OperandToUpdate = U-OperandList;
1840 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1842 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1843 Lookup.first.first = getType();
1844 Lookup.second = this;
1846 std::vector<Constant*> &Values = Lookup.first.second;
1847 Values.reserve(getNumOperands()); // Build replacement array.
1849 // Fill values with the modified operands of the constant array. Also,
1850 // compute whether this turns into an all-zeros array.
1851 bool isAllZeros = false;
1852 if (!ToC->isNullValue()) {
1853 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1854 Values.push_back(cast<Constant>(O->get()));
1857 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1858 Constant *Val = cast<Constant>(O->get());
1859 Values.push_back(Val);
1860 if (isAllZeros) isAllZeros = Val->isNullValue();
1863 Values[OperandToUpdate] = ToC;
1865 Constant *Replacement = 0;
1867 Replacement = ConstantAggregateZero::get(getType());
1869 // Check to see if we have this array type already.
1871 ArrayConstantsTy::MapTy::iterator I =
1872 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1875 Replacement = I->second;
1877 // Okay, the new shape doesn't exist in the system yet. Instead of
1878 // creating a new constant array, inserting it, replaceallusesof'ing the
1879 // old with the new, then deleting the old... just update the current one
1881 ArrayConstants->MoveConstantToNewSlot(this, I);
1883 // Update to the new value.
1884 setOperand(OperandToUpdate, ToC);
1889 // Otherwise, I do need to replace this with an existing value.
1890 assert(Replacement != this && "I didn't contain From!");
1892 // Everyone using this now uses the replacement.
1893 uncheckedReplaceAllUsesWith(Replacement);
1895 // Delete the old constant!
1899 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1901 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1902 Constant *ToC = cast<Constant>(To);
1904 unsigned OperandToUpdate = U-OperandList;
1905 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1907 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1908 Lookup.first.first = getType();
1909 Lookup.second = this;
1910 std::vector<Constant*> &Values = Lookup.first.second;
1911 Values.reserve(getNumOperands()); // Build replacement struct.
1914 // Fill values with the modified operands of the constant struct. Also,
1915 // compute whether this turns into an all-zeros struct.
1916 bool isAllZeros = false;
1917 if (!ToC->isNullValue()) {
1918 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1919 Values.push_back(cast<Constant>(O->get()));
1922 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1923 Constant *Val = cast<Constant>(O->get());
1924 Values.push_back(Val);
1925 if (isAllZeros) isAllZeros = Val->isNullValue();
1928 Values[OperandToUpdate] = ToC;
1930 Constant *Replacement = 0;
1932 Replacement = ConstantAggregateZero::get(getType());
1934 // Check to see if we have this array type already.
1936 StructConstantsTy::MapTy::iterator I =
1937 StructConstants->InsertOrGetItem(Lookup, Exists);
1940 Replacement = I->second;
1942 // Okay, the new shape doesn't exist in the system yet. Instead of
1943 // creating a new constant struct, inserting it, replaceallusesof'ing the
1944 // old with the new, then deleting the old... just update the current one
1946 StructConstants->MoveConstantToNewSlot(this, I);
1948 // Update to the new value.
1949 setOperand(OperandToUpdate, ToC);
1954 assert(Replacement != this && "I didn't contain From!");
1956 // Everyone using this now uses the replacement.
1957 uncheckedReplaceAllUsesWith(Replacement);
1959 // Delete the old constant!
1963 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1965 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1967 std::vector<Constant*> Values;
1968 Values.reserve(getNumOperands()); // Build replacement array...
1969 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1970 Constant *Val = getOperand(i);
1971 if (Val == From) Val = cast<Constant>(To);
1972 Values.push_back(Val);
1975 Constant *Replacement = ConstantVector::get(getType(), Values);
1976 assert(Replacement != this && "I didn't contain From!");
1978 // Everyone using this now uses the replacement.
1979 uncheckedReplaceAllUsesWith(Replacement);
1981 // Delete the old constant!
1985 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1987 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1988 Constant *To = cast<Constant>(ToV);
1990 Constant *Replacement = 0;
1991 if (getOpcode() == Instruction::GetElementPtr) {
1992 SmallVector<Constant*, 8> Indices;
1993 Constant *Pointer = getOperand(0);
1994 Indices.reserve(getNumOperands()-1);
1995 if (Pointer == From) Pointer = To;
1997 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1998 Constant *Val = getOperand(i);
1999 if (Val == From) Val = To;
2000 Indices.push_back(Val);
2002 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2003 &Indices[0], Indices.size());
2004 } else if (isCast()) {
2005 assert(getOperand(0) == From && "Cast only has one use!");
2006 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2007 } else if (getOpcode() == Instruction::Select) {
2008 Constant *C1 = getOperand(0);
2009 Constant *C2 = getOperand(1);
2010 Constant *C3 = getOperand(2);
2011 if (C1 == From) C1 = To;
2012 if (C2 == From) C2 = To;
2013 if (C3 == From) C3 = To;
2014 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2015 } else if (getOpcode() == Instruction::ExtractElement) {
2016 Constant *C1 = getOperand(0);
2017 Constant *C2 = getOperand(1);
2018 if (C1 == From) C1 = To;
2019 if (C2 == From) C2 = To;
2020 Replacement = ConstantExpr::getExtractElement(C1, C2);
2021 } else if (getOpcode() == Instruction::InsertElement) {
2022 Constant *C1 = getOperand(0);
2023 Constant *C2 = getOperand(1);
2024 Constant *C3 = getOperand(1);
2025 if (C1 == From) C1 = To;
2026 if (C2 == From) C2 = To;
2027 if (C3 == From) C3 = To;
2028 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2029 } else if (getOpcode() == Instruction::ShuffleVector) {
2030 Constant *C1 = getOperand(0);
2031 Constant *C2 = getOperand(1);
2032 Constant *C3 = getOperand(2);
2033 if (C1 == From) C1 = To;
2034 if (C2 == From) C2 = To;
2035 if (C3 == From) C3 = To;
2036 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2037 } else if (isCompare()) {
2038 Constant *C1 = getOperand(0);
2039 Constant *C2 = getOperand(1);
2040 if (C1 == From) C1 = To;
2041 if (C2 == From) C2 = To;
2042 if (getOpcode() == Instruction::ICmp)
2043 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2045 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2046 } else if (getNumOperands() == 2) {
2047 Constant *C1 = getOperand(0);
2048 Constant *C2 = getOperand(1);
2049 if (C1 == From) C1 = To;
2050 if (C2 == From) C2 = To;
2051 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2053 assert(0 && "Unknown ConstantExpr type!");
2057 assert(Replacement != this && "I didn't contain From!");
2059 // Everyone using this now uses the replacement.
2060 uncheckedReplaceAllUsesWith(Replacement);
2062 // Delete the old constant!
2067 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2068 /// global into a string value. Return an empty string if we can't do it.
2069 /// Parameter Chop determines if the result is chopped at the first null
2072 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2073 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2074 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2075 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2076 if (Init->isString()) {
2077 std::string Result = Init->getAsString();
2078 if (Offset < Result.size()) {
2079 // If we are pointing INTO The string, erase the beginning...
2080 Result.erase(Result.begin(), Result.begin()+Offset);
2082 // Take off the null terminator, and any string fragments after it.
2084 std::string::size_type NullPos = Result.find_first_of((char)0);
2085 if (NullPos != std::string::npos)
2086 Result.erase(Result.begin()+NullPos, Result.end());
2092 } else if (Constant *C = dyn_cast<Constant>(this)) {
2093 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2094 return GV->getStringValue(Chop, Offset);
2095 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2096 if (CE->getOpcode() == Instruction::GetElementPtr) {
2097 // Turn a gep into the specified offset.
2098 if (CE->getNumOperands() == 3 &&
2099 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2100 isa<ConstantInt>(CE->getOperand(2))) {
2101 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2102 return CE->getOperand(0)->getStringValue(Chop, Offset);