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::IntegerTyID: {
96 const IntegerType *ITy = dyn_cast<IntegerType>(Ty);
97 switch (ITy->getBitWidth()) {
99 static Constant *NullBool = ConstantInt::get(Ty, false);
103 static Constant *NullInt8 = ConstantInt::get(Ty, 0);
107 static Constant *NullInt16 = ConstantInt::get(Ty, 0);
111 static Constant *NullInt32 = ConstantInt::get(Ty, 0);
115 static Constant *NullInt64 = ConstantInt::get(Ty, 0);
119 return ConstantInt::get(Ty, 0);
122 case Type::FloatTyID: {
123 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
126 case Type::DoubleTyID: {
127 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
130 case Type::PointerTyID:
131 return ConstantPointerNull::get(cast<PointerType>(Ty));
132 case Type::StructTyID:
133 case Type::ArrayTyID:
134 case Type::PackedTyID:
135 return ConstantAggregateZero::get(Ty);
137 // Function, Label, or Opaque type?
138 assert(!"Cannot create a null constant of that type!");
144 // Static constructor to create an integral constant with all bits set
145 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
146 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
147 if (ITy->getBitWidth() == 1)
148 return ConstantInt::getTrue();
150 return ConstantInt::get(Ty, int64_t(-1));
154 /// @returns the value for an packed integer constant of the given type that
155 /// has all its bits set to true.
156 /// @brief Get the all ones value
157 ConstantPacked *ConstantPacked::getAllOnesValue(const PackedType *Ty) {
158 std::vector<Constant*> Elts;
159 Elts.resize(Ty->getNumElements(),
160 ConstantInt::getAllOnesValue(Ty->getElementType()));
161 assert(Elts[0] && "Not a packed integer type!");
162 return cast<ConstantPacked>(ConstantPacked::get(Elts));
166 //===----------------------------------------------------------------------===//
167 // ConstantXXX Classes
168 //===----------------------------------------------------------------------===//
170 //===----------------------------------------------------------------------===//
171 // Normal Constructors
173 ConstantInt::ConstantInt(bool V)
174 : Constant(Type::Int1Ty, ConstantIntVal, 0, 0), Val(uint64_t(V)) {
177 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
178 : Constant(Ty, ConstantIntVal, 0, 0), Val(Ty == Type::Int1Ty ? bool(V) : V) {
181 ConstantFP::ConstantFP(const Type *Ty, double V)
182 : Constant(Ty, ConstantFPVal, 0, 0) {
183 assert(isValueValidForType(Ty, V) && "Value too large for type!");
187 ConstantArray::ConstantArray(const ArrayType *T,
188 const std::vector<Constant*> &V)
189 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
190 assert(V.size() == T->getNumElements() &&
191 "Invalid initializer vector for constant array");
192 Use *OL = OperandList;
193 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
196 assert((C->getType() == T->getElementType() ||
198 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
199 "Initializer for array element doesn't match array element type!");
204 ConstantArray::~ConstantArray() {
205 delete [] OperandList;
208 ConstantStruct::ConstantStruct(const StructType *T,
209 const std::vector<Constant*> &V)
210 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
211 assert(V.size() == T->getNumElements() &&
212 "Invalid initializer vector for constant structure");
213 Use *OL = OperandList;
214 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
217 assert((C->getType() == T->getElementType(I-V.begin()) ||
218 ((T->getElementType(I-V.begin())->isAbstract() ||
219 C->getType()->isAbstract()) &&
220 T->getElementType(I-V.begin())->getTypeID() ==
221 C->getType()->getTypeID())) &&
222 "Initializer for struct element doesn't match struct element type!");
227 ConstantStruct::~ConstantStruct() {
228 delete [] OperandList;
232 ConstantPacked::ConstantPacked(const PackedType *T,
233 const std::vector<Constant*> &V)
234 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
235 Use *OL = OperandList;
236 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
239 assert((C->getType() == T->getElementType() ||
241 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
242 "Initializer for packed element doesn't match packed element type!");
247 ConstantPacked::~ConstantPacked() {
248 delete [] OperandList;
251 // We declare several classes private to this file, so use an anonymous
255 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
256 /// behind the scenes to implement unary constant exprs.
257 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
260 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
261 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
264 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
265 /// behind the scenes to implement binary constant exprs.
266 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
269 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
270 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
271 Ops[0].init(C1, this);
272 Ops[1].init(C2, this);
276 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
277 /// behind the scenes to implement select constant exprs.
278 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
281 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
282 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
283 Ops[0].init(C1, this);
284 Ops[1].init(C2, this);
285 Ops[2].init(C3, this);
289 /// ExtractElementConstantExpr - This class is private to
290 /// Constants.cpp, and is used behind the scenes to implement
291 /// extractelement constant exprs.
292 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
295 ExtractElementConstantExpr(Constant *C1, Constant *C2)
296 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
297 Instruction::ExtractElement, Ops, 2) {
298 Ops[0].init(C1, this);
299 Ops[1].init(C2, this);
303 /// InsertElementConstantExpr - This class is private to
304 /// Constants.cpp, and is used behind the scenes to implement
305 /// insertelement constant exprs.
306 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
309 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
310 : ConstantExpr(C1->getType(), Instruction::InsertElement,
312 Ops[0].init(C1, this);
313 Ops[1].init(C2, this);
314 Ops[2].init(C3, this);
318 /// ShuffleVectorConstantExpr - This class is private to
319 /// Constants.cpp, and is used behind the scenes to implement
320 /// shufflevector constant exprs.
321 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
324 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
325 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
327 Ops[0].init(C1, this);
328 Ops[1].init(C2, this);
329 Ops[2].init(C3, this);
333 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
334 /// used behind the scenes to implement getelementpr constant exprs.
335 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
336 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
338 : ConstantExpr(DestTy, Instruction::GetElementPtr,
339 new Use[IdxList.size()+1], IdxList.size()+1) {
340 OperandList[0].init(C, this);
341 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
342 OperandList[i+1].init(IdxList[i], this);
344 ~GetElementPtrConstantExpr() {
345 delete [] OperandList;
349 // CompareConstantExpr - This class is private to Constants.cpp, and is used
350 // behind the scenes to implement ICmp and FCmp constant expressions. This is
351 // needed in order to store the predicate value for these instructions.
352 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
353 unsigned short predicate;
355 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
356 Constant* LHS, Constant* RHS)
357 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
358 OperandList[0].init(LHS, this);
359 OperandList[1].init(RHS, this);
363 } // end anonymous namespace
366 // Utility function for determining if a ConstantExpr is a CastOp or not. This
367 // can't be inline because we don't want to #include Instruction.h into
369 bool ConstantExpr::isCast() const {
370 return Instruction::isCast(getOpcode());
373 bool ConstantExpr::isCompare() const {
374 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
377 /// ConstantExpr::get* - Return some common constants without having to
378 /// specify the full Instruction::OPCODE identifier.
380 Constant *ConstantExpr::getNeg(Constant *C) {
381 return get(Instruction::Sub,
382 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
385 Constant *ConstantExpr::getNot(Constant *C) {
386 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
387 return get(Instruction::Xor, C,
388 ConstantInt::getAllOnesValue(C->getType()));
390 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
391 return get(Instruction::Add, C1, C2);
393 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
394 return get(Instruction::Sub, C1, C2);
396 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
397 return get(Instruction::Mul, C1, C2);
399 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
400 return get(Instruction::UDiv, C1, C2);
402 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
403 return get(Instruction::SDiv, C1, C2);
405 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
406 return get(Instruction::FDiv, C1, C2);
408 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
409 return get(Instruction::URem, C1, C2);
411 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
412 return get(Instruction::SRem, C1, C2);
414 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
415 return get(Instruction::FRem, C1, C2);
417 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
418 return get(Instruction::And, C1, C2);
420 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
421 return get(Instruction::Or, C1, C2);
423 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
424 return get(Instruction::Xor, C1, C2);
426 unsigned ConstantExpr::getPredicate() const {
427 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
428 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
430 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
431 return get(Instruction::Shl, C1, C2);
433 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
434 return get(Instruction::LShr, C1, C2);
436 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
437 return get(Instruction::AShr, C1, C2);
440 /// getWithOperandReplaced - Return a constant expression identical to this
441 /// one, but with the specified operand set to the specified value.
443 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
444 assert(OpNo < getNumOperands() && "Operand num is out of range!");
445 assert(Op->getType() == getOperand(OpNo)->getType() &&
446 "Replacing operand with value of different type!");
447 if (getOperand(OpNo) == Op)
448 return const_cast<ConstantExpr*>(this);
450 Constant *Op0, *Op1, *Op2;
451 switch (getOpcode()) {
452 case Instruction::Trunc:
453 case Instruction::ZExt:
454 case Instruction::SExt:
455 case Instruction::FPTrunc:
456 case Instruction::FPExt:
457 case Instruction::UIToFP:
458 case Instruction::SIToFP:
459 case Instruction::FPToUI:
460 case Instruction::FPToSI:
461 case Instruction::PtrToInt:
462 case Instruction::IntToPtr:
463 case Instruction::BitCast:
464 return ConstantExpr::getCast(getOpcode(), Op, getType());
465 case Instruction::Select:
466 Op0 = (OpNo == 0) ? Op : getOperand(0);
467 Op1 = (OpNo == 1) ? Op : getOperand(1);
468 Op2 = (OpNo == 2) ? Op : getOperand(2);
469 return ConstantExpr::getSelect(Op0, Op1, Op2);
470 case Instruction::InsertElement:
471 Op0 = (OpNo == 0) ? Op : getOperand(0);
472 Op1 = (OpNo == 1) ? Op : getOperand(1);
473 Op2 = (OpNo == 2) ? Op : getOperand(2);
474 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
475 case Instruction::ExtractElement:
476 Op0 = (OpNo == 0) ? Op : getOperand(0);
477 Op1 = (OpNo == 1) ? Op : getOperand(1);
478 return ConstantExpr::getExtractElement(Op0, Op1);
479 case Instruction::ShuffleVector:
480 Op0 = (OpNo == 0) ? Op : getOperand(0);
481 Op1 = (OpNo == 1) ? Op : getOperand(1);
482 Op2 = (OpNo == 2) ? Op : getOperand(2);
483 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
484 case Instruction::GetElementPtr: {
485 std::vector<Constant*> Ops;
486 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
487 Ops.push_back(getOperand(i));
489 return ConstantExpr::getGetElementPtr(Op, Ops);
491 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
494 assert(getNumOperands() == 2 && "Must be binary operator?");
495 Op0 = (OpNo == 0) ? Op : getOperand(0);
496 Op1 = (OpNo == 1) ? Op : getOperand(1);
497 return ConstantExpr::get(getOpcode(), Op0, Op1);
501 /// getWithOperands - This returns the current constant expression with the
502 /// operands replaced with the specified values. The specified operands must
503 /// match count and type with the existing ones.
504 Constant *ConstantExpr::
505 getWithOperands(const std::vector<Constant*> &Ops) const {
506 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
507 bool AnyChange = false;
508 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
509 assert(Ops[i]->getType() == getOperand(i)->getType() &&
510 "Operand type mismatch!");
511 AnyChange |= Ops[i] != getOperand(i);
513 if (!AnyChange) // No operands changed, return self.
514 return const_cast<ConstantExpr*>(this);
516 switch (getOpcode()) {
517 case Instruction::Trunc:
518 case Instruction::ZExt:
519 case Instruction::SExt:
520 case Instruction::FPTrunc:
521 case Instruction::FPExt:
522 case Instruction::UIToFP:
523 case Instruction::SIToFP:
524 case Instruction::FPToUI:
525 case Instruction::FPToSI:
526 case Instruction::PtrToInt:
527 case Instruction::IntToPtr:
528 case Instruction::BitCast:
529 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
530 case Instruction::Select:
531 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
532 case Instruction::InsertElement:
533 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
534 case Instruction::ExtractElement:
535 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
536 case Instruction::ShuffleVector:
537 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
538 case Instruction::GetElementPtr: {
539 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
540 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
542 case Instruction::ICmp:
543 case Instruction::FCmp:
544 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
546 assert(getNumOperands() == 2 && "Must be binary operator?");
547 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
552 //===----------------------------------------------------------------------===//
553 // isValueValidForType implementations
555 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
556 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
557 assert(NumBits <= 64 && "Not implemented: integers > 64-bits");
558 if (Ty == Type::Int1Ty)
559 return Val == 0 || Val == 1;
561 return true; // always true, has to fit in largest type
562 uint64_t Max = (1ll << NumBits) - 1;
566 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
567 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
568 assert(NumBits <= 64 && "Not implemented: integers > 64-bits");
569 if (Ty == Type::Int1Ty)
570 return Val == 0 || Val == 1 || Val == -1;
572 return true; // always true, has to fit in largest type
573 int64_t Min = -(1ll << (NumBits-1));
574 int64_t Max = (1ll << (NumBits-1)) - 1;
575 return (Val >= Min && Val <= Max);
578 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
579 switch (Ty->getTypeID()) {
581 return false; // These can't be represented as floating point!
583 // TODO: Figure out how to test if a double can be cast to a float!
584 case Type::FloatTyID:
585 case Type::DoubleTyID:
586 return true; // This is the largest type...
590 //===----------------------------------------------------------------------===//
591 // Factory Function Implementation
593 // ConstantCreator - A class that is used to create constants by
594 // ValueMap*. This class should be partially specialized if there is
595 // something strange that needs to be done to interface to the ctor for the
599 template<class ConstantClass, class TypeClass, class ValType>
600 struct VISIBILITY_HIDDEN ConstantCreator {
601 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
602 return new ConstantClass(Ty, V);
606 template<class ConstantClass, class TypeClass>
607 struct VISIBILITY_HIDDEN ConvertConstantType {
608 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
609 assert(0 && "This type cannot be converted!\n");
614 template<class ValType, class TypeClass, class ConstantClass,
615 bool HasLargeKey = false /*true for arrays and structs*/ >
616 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
618 typedef std::pair<const Type*, ValType> MapKey;
619 typedef std::map<MapKey, Constant *> MapTy;
620 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
621 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
623 /// Map - This is the main map from the element descriptor to the Constants.
624 /// This is the primary way we avoid creating two of the same shape
628 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
629 /// from the constants to their element in Map. This is important for
630 /// removal of constants from the array, which would otherwise have to scan
631 /// through the map with very large keys.
632 InverseMapTy InverseMap;
634 /// AbstractTypeMap - Map for abstract type constants.
636 AbstractTypeMapTy AbstractTypeMap;
639 void clear(std::vector<Constant *> &Constants) {
640 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
641 Constants.push_back(I->second);
643 AbstractTypeMap.clear();
648 typename MapTy::iterator map_end() { return Map.end(); }
650 /// InsertOrGetItem - Return an iterator for the specified element.
651 /// If the element exists in the map, the returned iterator points to the
652 /// entry and Exists=true. If not, the iterator points to the newly
653 /// inserted entry and returns Exists=false. Newly inserted entries have
654 /// I->second == 0, and should be filled in.
655 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
658 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
664 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
666 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
667 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
668 IMI->second->second == CP &&
669 "InverseMap corrupt!");
673 typename MapTy::iterator I =
674 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
675 if (I == Map.end() || I->second != CP) {
676 // FIXME: This should not use a linear scan. If this gets to be a
677 // performance problem, someone should look at this.
678 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
685 /// getOrCreate - Return the specified constant from the map, creating it if
687 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
688 MapKey Lookup(Ty, V);
689 typename MapTy::iterator I = Map.lower_bound(Lookup);
691 if (I != Map.end() && I->first == Lookup)
692 return static_cast<ConstantClass *>(I->second);
694 // If no preexisting value, create one now...
695 ConstantClass *Result =
696 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
698 /// FIXME: why does this assert fail when loading 176.gcc?
699 //assert(Result->getType() == Ty && "Type specified is not correct!");
700 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
702 if (HasLargeKey) // Remember the reverse mapping if needed.
703 InverseMap.insert(std::make_pair(Result, I));
705 // If the type of the constant is abstract, make sure that an entry exists
706 // for it in the AbstractTypeMap.
707 if (Ty->isAbstract()) {
708 typename AbstractTypeMapTy::iterator TI =
709 AbstractTypeMap.lower_bound(Ty);
711 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
712 // Add ourselves to the ATU list of the type.
713 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
715 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
721 void remove(ConstantClass *CP) {
722 typename MapTy::iterator I = FindExistingElement(CP);
723 assert(I != Map.end() && "Constant not found in constant table!");
724 assert(I->second == CP && "Didn't find correct element?");
726 if (HasLargeKey) // Remember the reverse mapping if needed.
727 InverseMap.erase(CP);
729 // Now that we found the entry, make sure this isn't the entry that
730 // the AbstractTypeMap points to.
731 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
732 if (Ty->isAbstract()) {
733 assert(AbstractTypeMap.count(Ty) &&
734 "Abstract type not in AbstractTypeMap?");
735 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
736 if (ATMEntryIt == I) {
737 // Yes, we are removing the representative entry for this type.
738 // See if there are any other entries of the same type.
739 typename MapTy::iterator TmpIt = ATMEntryIt;
741 // First check the entry before this one...
742 if (TmpIt != Map.begin()) {
744 if (TmpIt->first.first != Ty) // Not the same type, move back...
748 // If we didn't find the same type, try to move forward...
749 if (TmpIt == ATMEntryIt) {
751 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
752 --TmpIt; // No entry afterwards with the same type
755 // If there is another entry in the map of the same abstract type,
756 // update the AbstractTypeMap entry now.
757 if (TmpIt != ATMEntryIt) {
760 // Otherwise, we are removing the last instance of this type
761 // from the table. Remove from the ATM, and from user list.
762 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
763 AbstractTypeMap.erase(Ty);
772 /// MoveConstantToNewSlot - If we are about to change C to be the element
773 /// specified by I, update our internal data structures to reflect this
775 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
776 // First, remove the old location of the specified constant in the map.
777 typename MapTy::iterator OldI = FindExistingElement(C);
778 assert(OldI != Map.end() && "Constant not found in constant table!");
779 assert(OldI->second == C && "Didn't find correct element?");
781 // If this constant is the representative element for its abstract type,
782 // update the AbstractTypeMap so that the representative element is I.
783 if (C->getType()->isAbstract()) {
784 typename AbstractTypeMapTy::iterator ATI =
785 AbstractTypeMap.find(C->getType());
786 assert(ATI != AbstractTypeMap.end() &&
787 "Abstract type not in AbstractTypeMap?");
788 if (ATI->second == OldI)
792 // Remove the old entry from the map.
795 // Update the inverse map so that we know that this constant is now
796 // located at descriptor I.
798 assert(I->second == C && "Bad inversemap entry!");
803 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
804 typename AbstractTypeMapTy::iterator I =
805 AbstractTypeMap.find(cast<Type>(OldTy));
807 assert(I != AbstractTypeMap.end() &&
808 "Abstract type not in AbstractTypeMap?");
810 // Convert a constant at a time until the last one is gone. The last one
811 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
812 // eliminated eventually.
814 ConvertConstantType<ConstantClass,
816 static_cast<ConstantClass *>(I->second->second),
817 cast<TypeClass>(NewTy));
819 I = AbstractTypeMap.find(cast<Type>(OldTy));
820 } while (I != AbstractTypeMap.end());
823 // If the type became concrete without being refined to any other existing
824 // type, we just remove ourselves from the ATU list.
825 void typeBecameConcrete(const DerivedType *AbsTy) {
826 AbsTy->removeAbstractTypeUser(this);
830 DOUT << "Constant.cpp: ValueMap\n";
836 //---- ConstantInt::get() implementations...
838 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
840 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
841 // to a uint64_t value that has been zero extended down to the size of the
842 // integer type of the ConstantInt. This allows the getZExtValue method to
843 // just return the stored value while getSExtValue has to convert back to sign
844 // extended. getZExtValue is more common in LLVM than getSExtValue().
845 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
846 if (Ty == Type::Int1Ty)
851 return IntConstants->getOrCreate(Ty, V & cast<IntegerType>(Ty)->getBitMask());
854 //---- ConstantFP::get() implementation...
858 struct ConstantCreator<ConstantFP, Type, uint64_t> {
859 static ConstantFP *create(const Type *Ty, uint64_t V) {
860 assert(Ty == Type::DoubleTy);
861 return new ConstantFP(Ty, BitsToDouble(V));
865 struct ConstantCreator<ConstantFP, Type, uint32_t> {
866 static ConstantFP *create(const Type *Ty, uint32_t V) {
867 assert(Ty == Type::FloatTy);
868 return new ConstantFP(Ty, BitsToFloat(V));
873 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
874 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
876 bool ConstantFP::isNullValue() const {
877 return DoubleToBits(Val) == 0;
880 bool ConstantFP::isExactlyValue(double V) const {
881 return DoubleToBits(V) == DoubleToBits(Val);
885 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
886 if (Ty == Type::FloatTy) {
887 // Force the value through memory to normalize it.
888 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
890 assert(Ty == Type::DoubleTy);
891 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
895 //---- ConstantAggregateZero::get() implementation...
898 // ConstantAggregateZero does not take extra "value" argument...
899 template<class ValType>
900 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
901 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
902 return new ConstantAggregateZero(Ty);
907 struct ConvertConstantType<ConstantAggregateZero, Type> {
908 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
909 // Make everyone now use a constant of the new type...
910 Constant *New = ConstantAggregateZero::get(NewTy);
911 assert(New != OldC && "Didn't replace constant??");
912 OldC->uncheckedReplaceAllUsesWith(New);
913 OldC->destroyConstant(); // This constant is now dead, destroy it.
918 static ManagedStatic<ValueMap<char, Type,
919 ConstantAggregateZero> > AggZeroConstants;
921 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
923 Constant *ConstantAggregateZero::get(const Type *Ty) {
924 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
925 "Cannot create an aggregate zero of non-aggregate type!");
926 return AggZeroConstants->getOrCreate(Ty, 0);
929 // destroyConstant - Remove the constant from the constant table...
931 void ConstantAggregateZero::destroyConstant() {
932 AggZeroConstants->remove(this);
933 destroyConstantImpl();
936 //---- ConstantArray::get() implementation...
940 struct ConvertConstantType<ConstantArray, ArrayType> {
941 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
942 // Make everyone now use a constant of the new type...
943 std::vector<Constant*> C;
944 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
945 C.push_back(cast<Constant>(OldC->getOperand(i)));
946 Constant *New = ConstantArray::get(NewTy, C);
947 assert(New != OldC && "Didn't replace constant??");
948 OldC->uncheckedReplaceAllUsesWith(New);
949 OldC->destroyConstant(); // This constant is now dead, destroy it.
954 static std::vector<Constant*> getValType(ConstantArray *CA) {
955 std::vector<Constant*> Elements;
956 Elements.reserve(CA->getNumOperands());
957 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
958 Elements.push_back(cast<Constant>(CA->getOperand(i)));
962 typedef ValueMap<std::vector<Constant*>, ArrayType,
963 ConstantArray, true /*largekey*/> ArrayConstantsTy;
964 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
966 Constant *ConstantArray::get(const ArrayType *Ty,
967 const std::vector<Constant*> &V) {
968 // If this is an all-zero array, return a ConstantAggregateZero object
971 if (!C->isNullValue())
972 return ArrayConstants->getOrCreate(Ty, V);
973 for (unsigned i = 1, e = V.size(); i != e; ++i)
975 return ArrayConstants->getOrCreate(Ty, V);
977 return ConstantAggregateZero::get(Ty);
980 // destroyConstant - Remove the constant from the constant table...
982 void ConstantArray::destroyConstant() {
983 ArrayConstants->remove(this);
984 destroyConstantImpl();
987 /// ConstantArray::get(const string&) - Return an array that is initialized to
988 /// contain the specified string. If length is zero then a null terminator is
989 /// added to the specified string so that it may be used in a natural way.
990 /// Otherwise, the length parameter specifies how much of the string to use
991 /// and it won't be null terminated.
993 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
994 std::vector<Constant*> ElementVals;
995 for (unsigned i = 0; i < Str.length(); ++i)
996 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
998 // Add a null terminator to the string...
1000 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1003 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1004 return ConstantArray::get(ATy, ElementVals);
1007 /// isString - This method returns true if the array is an array of i8, and
1008 /// if the elements of the array are all ConstantInt's.
1009 bool ConstantArray::isString() const {
1010 // Check the element type for i8...
1011 if (getType()->getElementType() != Type::Int8Ty)
1013 // Check the elements to make sure they are all integers, not constant
1015 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1016 if (!isa<ConstantInt>(getOperand(i)))
1021 /// isCString - This method returns true if the array is a string (see
1022 /// isString) and it ends in a null byte \0 and does not contains any other
1023 /// null bytes except its terminator.
1024 bool ConstantArray::isCString() const {
1025 // Check the element type for i8...
1026 if (getType()->getElementType() != Type::Int8Ty)
1028 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1029 // Last element must be a null.
1030 if (getOperand(getNumOperands()-1) != Zero)
1032 // Other elements must be non-null integers.
1033 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1034 if (!isa<ConstantInt>(getOperand(i)))
1036 if (getOperand(i) == Zero)
1043 // getAsString - If the sub-element type of this array is i8
1044 // then this method converts the array to an std::string and returns it.
1045 // Otherwise, it asserts out.
1047 std::string ConstantArray::getAsString() const {
1048 assert(isString() && "Not a string!");
1050 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1051 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1056 //---- ConstantStruct::get() implementation...
1061 struct ConvertConstantType<ConstantStruct, StructType> {
1062 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1063 // Make everyone now use a constant of the new type...
1064 std::vector<Constant*> C;
1065 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1066 C.push_back(cast<Constant>(OldC->getOperand(i)));
1067 Constant *New = ConstantStruct::get(NewTy, C);
1068 assert(New != OldC && "Didn't replace constant??");
1070 OldC->uncheckedReplaceAllUsesWith(New);
1071 OldC->destroyConstant(); // This constant is now dead, destroy it.
1076 typedef ValueMap<std::vector<Constant*>, StructType,
1077 ConstantStruct, true /*largekey*/> StructConstantsTy;
1078 static ManagedStatic<StructConstantsTy> StructConstants;
1080 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1081 std::vector<Constant*> Elements;
1082 Elements.reserve(CS->getNumOperands());
1083 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1084 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1088 Constant *ConstantStruct::get(const StructType *Ty,
1089 const std::vector<Constant*> &V) {
1090 // Create a ConstantAggregateZero value if all elements are zeros...
1091 for (unsigned i = 0, e = V.size(); i != e; ++i)
1092 if (!V[i]->isNullValue())
1093 return StructConstants->getOrCreate(Ty, V);
1095 return ConstantAggregateZero::get(Ty);
1098 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1099 std::vector<const Type*> StructEls;
1100 StructEls.reserve(V.size());
1101 for (unsigned i = 0, e = V.size(); i != e; ++i)
1102 StructEls.push_back(V[i]->getType());
1103 return get(StructType::get(StructEls, packed), V);
1106 // destroyConstant - Remove the constant from the constant table...
1108 void ConstantStruct::destroyConstant() {
1109 StructConstants->remove(this);
1110 destroyConstantImpl();
1113 //---- ConstantPacked::get() implementation...
1117 struct ConvertConstantType<ConstantPacked, PackedType> {
1118 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1119 // Make everyone now use a constant of the new type...
1120 std::vector<Constant*> C;
1121 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1122 C.push_back(cast<Constant>(OldC->getOperand(i)));
1123 Constant *New = ConstantPacked::get(NewTy, C);
1124 assert(New != OldC && "Didn't replace constant??");
1125 OldC->uncheckedReplaceAllUsesWith(New);
1126 OldC->destroyConstant(); // This constant is now dead, destroy it.
1131 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1132 std::vector<Constant*> Elements;
1133 Elements.reserve(CP->getNumOperands());
1134 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1135 Elements.push_back(CP->getOperand(i));
1139 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1140 ConstantPacked> > PackedConstants;
1142 Constant *ConstantPacked::get(const PackedType *Ty,
1143 const std::vector<Constant*> &V) {
1144 // If this is an all-zero packed, return a ConstantAggregateZero object
1147 if (!C->isNullValue())
1148 return PackedConstants->getOrCreate(Ty, V);
1149 for (unsigned i = 1, e = V.size(); i != e; ++i)
1151 return PackedConstants->getOrCreate(Ty, V);
1153 return ConstantAggregateZero::get(Ty);
1156 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1157 assert(!V.empty() && "Cannot infer type if V is empty");
1158 return get(PackedType::get(V.front()->getType(),V.size()), V);
1161 // destroyConstant - Remove the constant from the constant table...
1163 void ConstantPacked::destroyConstant() {
1164 PackedConstants->remove(this);
1165 destroyConstantImpl();
1168 /// This function will return true iff every element in this packed constant
1169 /// is set to all ones.
1170 /// @returns true iff this constant's emements are all set to all ones.
1171 /// @brief Determine if the value is all ones.
1172 bool ConstantPacked::isAllOnesValue() const {
1173 // Check out first element.
1174 const Constant *Elt = getOperand(0);
1175 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1176 if (!CI || !CI->isAllOnesValue()) return false;
1177 // Then make sure all remaining elements point to the same value.
1178 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1179 if (getOperand(I) != Elt) return false;
1184 //---- ConstantPointerNull::get() implementation...
1188 // ConstantPointerNull does not take extra "value" argument...
1189 template<class ValType>
1190 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1191 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1192 return new ConstantPointerNull(Ty);
1197 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1198 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1199 // Make everyone now use a constant of the new type...
1200 Constant *New = ConstantPointerNull::get(NewTy);
1201 assert(New != OldC && "Didn't replace constant??");
1202 OldC->uncheckedReplaceAllUsesWith(New);
1203 OldC->destroyConstant(); // This constant is now dead, destroy it.
1208 static ManagedStatic<ValueMap<char, PointerType,
1209 ConstantPointerNull> > NullPtrConstants;
1211 static char getValType(ConstantPointerNull *) {
1216 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1217 return NullPtrConstants->getOrCreate(Ty, 0);
1220 // destroyConstant - Remove the constant from the constant table...
1222 void ConstantPointerNull::destroyConstant() {
1223 NullPtrConstants->remove(this);
1224 destroyConstantImpl();
1228 //---- UndefValue::get() implementation...
1232 // UndefValue does not take extra "value" argument...
1233 template<class ValType>
1234 struct ConstantCreator<UndefValue, Type, ValType> {
1235 static UndefValue *create(const Type *Ty, const ValType &V) {
1236 return new UndefValue(Ty);
1241 struct ConvertConstantType<UndefValue, Type> {
1242 static void convert(UndefValue *OldC, const Type *NewTy) {
1243 // Make everyone now use a constant of the new type.
1244 Constant *New = UndefValue::get(NewTy);
1245 assert(New != OldC && "Didn't replace constant??");
1246 OldC->uncheckedReplaceAllUsesWith(New);
1247 OldC->destroyConstant(); // This constant is now dead, destroy it.
1252 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1254 static char getValType(UndefValue *) {
1259 UndefValue *UndefValue::get(const Type *Ty) {
1260 return UndefValueConstants->getOrCreate(Ty, 0);
1263 // destroyConstant - Remove the constant from the constant table.
1265 void UndefValue::destroyConstant() {
1266 UndefValueConstants->remove(this);
1267 destroyConstantImpl();
1271 //---- ConstantExpr::get() implementations...
1274 struct ExprMapKeyType {
1275 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1276 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1279 std::vector<Constant*> operands;
1280 bool operator==(const ExprMapKeyType& that) const {
1281 return this->opcode == that.opcode &&
1282 this->predicate == that.predicate &&
1283 this->operands == that.operands;
1285 bool operator<(const ExprMapKeyType & that) const {
1286 return this->opcode < that.opcode ||
1287 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1288 (this->opcode == that.opcode && this->predicate == that.predicate &&
1289 this->operands < that.operands);
1292 bool operator!=(const ExprMapKeyType& that) const {
1293 return !(*this == that);
1299 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1300 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1301 unsigned short pred = 0) {
1302 if (Instruction::isCast(V.opcode))
1303 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1304 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1305 V.opcode < Instruction::BinaryOpsEnd))
1306 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1307 if (V.opcode == Instruction::Select)
1308 return new SelectConstantExpr(V.operands[0], V.operands[1],
1310 if (V.opcode == Instruction::ExtractElement)
1311 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1312 if (V.opcode == Instruction::InsertElement)
1313 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1315 if (V.opcode == Instruction::ShuffleVector)
1316 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1318 if (V.opcode == Instruction::GetElementPtr) {
1319 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1320 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1323 // The compare instructions are weird. We have to encode the predicate
1324 // value and it is combined with the instruction opcode by multiplying
1325 // the opcode by one hundred. We must decode this to get the predicate.
1326 if (V.opcode == Instruction::ICmp)
1327 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1328 V.operands[0], V.operands[1]);
1329 if (V.opcode == Instruction::FCmp)
1330 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1331 V.operands[0], V.operands[1]);
1332 assert(0 && "Invalid ConstantExpr!");
1338 struct ConvertConstantType<ConstantExpr, Type> {
1339 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1341 switch (OldC->getOpcode()) {
1342 case Instruction::Trunc:
1343 case Instruction::ZExt:
1344 case Instruction::SExt:
1345 case Instruction::FPTrunc:
1346 case Instruction::FPExt:
1347 case Instruction::UIToFP:
1348 case Instruction::SIToFP:
1349 case Instruction::FPToUI:
1350 case Instruction::FPToSI:
1351 case Instruction::PtrToInt:
1352 case Instruction::IntToPtr:
1353 case Instruction::BitCast:
1354 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1357 case Instruction::Select:
1358 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1359 OldC->getOperand(1),
1360 OldC->getOperand(2));
1363 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1364 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1365 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1366 OldC->getOperand(1));
1368 case Instruction::GetElementPtr:
1369 // Make everyone now use a constant of the new type...
1370 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1371 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1372 &Idx[0], Idx.size());
1376 assert(New != OldC && "Didn't replace constant??");
1377 OldC->uncheckedReplaceAllUsesWith(New);
1378 OldC->destroyConstant(); // This constant is now dead, destroy it.
1381 } // end namespace llvm
1384 static ExprMapKeyType getValType(ConstantExpr *CE) {
1385 std::vector<Constant*> Operands;
1386 Operands.reserve(CE->getNumOperands());
1387 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1388 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1389 return ExprMapKeyType(CE->getOpcode(), Operands,
1390 CE->isCompare() ? CE->getPredicate() : 0);
1393 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1394 ConstantExpr> > ExprConstants;
1396 /// This is a utility function to handle folding of casts and lookup of the
1397 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1398 static inline Constant *getFoldedCast(
1399 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1400 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1401 // Fold a few common cases
1402 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1405 // Look up the constant in the table first to ensure uniqueness
1406 std::vector<Constant*> argVec(1, C);
1407 ExprMapKeyType Key(opc, argVec);
1408 return ExprConstants->getOrCreate(Ty, Key);
1411 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1412 Instruction::CastOps opc = Instruction::CastOps(oc);
1413 assert(Instruction::isCast(opc) && "opcode out of range");
1414 assert(C && Ty && "Null arguments to getCast");
1415 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1419 assert(0 && "Invalid cast opcode");
1421 case Instruction::Trunc: return getTrunc(C, Ty);
1422 case Instruction::ZExt: return getZExt(C, Ty);
1423 case Instruction::SExt: return getSExt(C, Ty);
1424 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1425 case Instruction::FPExt: return getFPExtend(C, Ty);
1426 case Instruction::UIToFP: return getUIToFP(C, Ty);
1427 case Instruction::SIToFP: return getSIToFP(C, Ty);
1428 case Instruction::FPToUI: return getFPToUI(C, Ty);
1429 case Instruction::FPToSI: return getFPToSI(C, Ty);
1430 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1431 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1432 case Instruction::BitCast: return getBitCast(C, Ty);
1437 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1438 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1439 return getCast(Instruction::BitCast, C, Ty);
1440 return getCast(Instruction::ZExt, C, Ty);
1443 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1444 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1445 return getCast(Instruction::BitCast, C, Ty);
1446 return getCast(Instruction::SExt, C, Ty);
1449 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1450 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1451 return getCast(Instruction::BitCast, C, Ty);
1452 return getCast(Instruction::Trunc, C, Ty);
1455 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1456 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1457 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1459 if (Ty->isInteger())
1460 return getCast(Instruction::PtrToInt, S, Ty);
1461 return getCast(Instruction::BitCast, S, Ty);
1464 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1466 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1467 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1468 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1469 Instruction::CastOps opcode =
1470 (SrcBits == DstBits ? Instruction::BitCast :
1471 (SrcBits > DstBits ? Instruction::Trunc :
1472 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1473 return getCast(opcode, C, Ty);
1476 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1477 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1479 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1480 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1481 if (SrcBits == DstBits)
1482 return C; // Avoid a useless cast
1483 Instruction::CastOps opcode =
1484 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1485 return getCast(opcode, C, Ty);
1488 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1489 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1490 assert(Ty->isInteger() && "Trunc produces only integral");
1491 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1492 "SrcTy must be larger than DestTy for Trunc!");
1494 return getFoldedCast(Instruction::Trunc, C, Ty);
1497 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1498 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1499 assert(Ty->isInteger() && "SExt produces only integer");
1500 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1501 "SrcTy must be smaller than DestTy for SExt!");
1503 return getFoldedCast(Instruction::SExt, C, Ty);
1506 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1507 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1508 assert(Ty->isInteger() && "ZExt produces only integer");
1509 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1510 "SrcTy must be smaller than DestTy for ZExt!");
1512 return getFoldedCast(Instruction::ZExt, C, Ty);
1515 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1516 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1517 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1518 "This is an illegal floating point truncation!");
1519 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1522 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1523 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1524 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1525 "This is an illegal floating point extension!");
1526 return getFoldedCast(Instruction::FPExt, C, Ty);
1529 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1530 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1531 "This is an illegal i32 to floating point cast!");
1532 return getFoldedCast(Instruction::UIToFP, C, Ty);
1535 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1536 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1537 "This is an illegal sint to floating point cast!");
1538 return getFoldedCast(Instruction::SIToFP, C, Ty);
1541 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1542 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1543 "This is an illegal floating point to i32 cast!");
1544 return getFoldedCast(Instruction::FPToUI, C, Ty);
1547 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1548 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1549 "This is an illegal floating point to i32 cast!");
1550 return getFoldedCast(Instruction::FPToSI, C, Ty);
1553 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1554 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1555 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1556 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1559 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1560 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1561 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1562 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1565 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1566 // BitCast implies a no-op cast of type only. No bits change. However, you
1567 // can't cast pointers to anything but pointers.
1568 const Type *SrcTy = C->getType();
1569 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1570 "BitCast cannot cast pointer to non-pointer and vice versa");
1572 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1573 // or nonptr->ptr). For all the other types, the cast is okay if source and
1574 // destination bit widths are identical.
1575 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1576 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1577 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1578 return getFoldedCast(Instruction::BitCast, C, DstTy);
1581 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1582 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1583 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1584 PointerType::get(Ty)), std::vector<Constant*>(1,
1585 ConstantInt::get(Type::Int32Ty, 1))), Type::Int64Ty);
1588 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1589 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1590 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::Int32Ty, 0));
1592 return ConstantExpr::getGetElementPtr(C, Indices);
1595 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1596 Constant *C1, Constant *C2) {
1597 // Check the operands for consistency first
1598 assert(Opcode >= Instruction::BinaryOpsBegin &&
1599 Opcode < Instruction::BinaryOpsEnd &&
1600 "Invalid opcode in binary constant expression");
1601 assert(C1->getType() == C2->getType() &&
1602 "Operand types in binary constant expression should match");
1604 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1605 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1606 return FC; // Fold a few common cases...
1608 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1609 ExprMapKeyType Key(Opcode, argVec);
1610 return ExprConstants->getOrCreate(ReqTy, Key);
1613 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1614 Constant *C1, Constant *C2) {
1615 switch (predicate) {
1616 default: assert(0 && "Invalid CmpInst predicate");
1617 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1618 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1619 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1620 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1621 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1622 case FCmpInst::FCMP_TRUE:
1623 return getFCmp(predicate, C1, C2);
1624 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1625 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1626 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1627 case ICmpInst::ICMP_SLE:
1628 return getICmp(predicate, C1, C2);
1632 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1635 case Instruction::Add:
1636 case Instruction::Sub:
1637 case Instruction::Mul:
1638 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1639 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1640 isa<PackedType>(C1->getType())) &&
1641 "Tried to create an arithmetic operation on a non-arithmetic type!");
1643 case Instruction::UDiv:
1644 case Instruction::SDiv:
1645 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1646 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1647 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1648 "Tried to create an arithmetic operation on a non-arithmetic type!");
1650 case Instruction::FDiv:
1651 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1652 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1653 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1654 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1656 case Instruction::URem:
1657 case Instruction::SRem:
1658 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1659 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1660 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1661 "Tried to create an arithmetic operation on a non-arithmetic type!");
1663 case Instruction::FRem:
1664 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1665 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1666 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1667 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1669 case Instruction::And:
1670 case Instruction::Or:
1671 case Instruction::Xor:
1672 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1673 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1674 "Tried to create a logical operation on a non-integral type!");
1676 case Instruction::Shl:
1677 case Instruction::LShr:
1678 case Instruction::AShr:
1679 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1680 assert(C1->getType()->isInteger() &&
1681 "Tried to create a shift operation on a non-integer type!");
1688 return getTy(C1->getType(), Opcode, C1, C2);
1691 Constant *ConstantExpr::getCompare(unsigned short pred,
1692 Constant *C1, Constant *C2) {
1693 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1694 return getCompareTy(pred, C1, C2);
1697 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1698 Constant *V1, Constant *V2) {
1699 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1700 assert(V1->getType() == V2->getType() && "Select value types must match!");
1701 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1703 if (ReqTy == V1->getType())
1704 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1705 return SC; // Fold common cases
1707 std::vector<Constant*> argVec(3, C);
1710 ExprMapKeyType Key(Instruction::Select, argVec);
1711 return ExprConstants->getOrCreate(ReqTy, Key);
1714 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1717 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1718 "GEP indices invalid!");
1720 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1721 return FC; // Fold a few common cases...
1723 assert(isa<PointerType>(C->getType()) &&
1724 "Non-pointer type for constant GetElementPtr expression");
1725 // Look up the constant in the table first to ensure uniqueness
1726 std::vector<Constant*> ArgVec;
1727 ArgVec.reserve(NumIdx+1);
1728 ArgVec.push_back(C);
1729 for (unsigned i = 0; i != NumIdx; ++i)
1730 ArgVec.push_back(cast<Constant>(Idxs[i]));
1731 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1732 return ExprConstants->getOrCreate(ReqTy, Key);
1735 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1737 // Get the result type of the getelementptr!
1739 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1740 assert(Ty && "GEP indices invalid!");
1741 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1744 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1746 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1751 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1752 assert(LHS->getType() == RHS->getType());
1753 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1754 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1756 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1757 return FC; // Fold a few common cases...
1759 // Look up the constant in the table first to ensure uniqueness
1760 std::vector<Constant*> ArgVec;
1761 ArgVec.push_back(LHS);
1762 ArgVec.push_back(RHS);
1763 // Get the key type with both the opcode and predicate
1764 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1765 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1769 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1770 assert(LHS->getType() == RHS->getType());
1771 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1773 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1774 return FC; // Fold a few common cases...
1776 // Look up the constant in the table first to ensure uniqueness
1777 std::vector<Constant*> ArgVec;
1778 ArgVec.push_back(LHS);
1779 ArgVec.push_back(RHS);
1780 // Get the key type with both the opcode and predicate
1781 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1782 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1785 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1787 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1788 return FC; // Fold a few common cases...
1789 // Look up the constant in the table first to ensure uniqueness
1790 std::vector<Constant*> ArgVec(1, Val);
1791 ArgVec.push_back(Idx);
1792 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1793 return ExprConstants->getOrCreate(ReqTy, Key);
1796 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1797 assert(isa<PackedType>(Val->getType()) &&
1798 "Tried to create extractelement operation on non-packed type!");
1799 assert(Idx->getType() == Type::Int32Ty &&
1800 "Extractelement index must be i32 type!");
1801 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1805 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1806 Constant *Elt, Constant *Idx) {
1807 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1808 return FC; // Fold a few common cases...
1809 // Look up the constant in the table first to ensure uniqueness
1810 std::vector<Constant*> ArgVec(1, Val);
1811 ArgVec.push_back(Elt);
1812 ArgVec.push_back(Idx);
1813 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1814 return ExprConstants->getOrCreate(ReqTy, Key);
1817 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1819 assert(isa<PackedType>(Val->getType()) &&
1820 "Tried to create insertelement operation on non-packed type!");
1821 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1822 && "Insertelement types must match!");
1823 assert(Idx->getType() == Type::Int32Ty &&
1824 "Insertelement index must be i32 type!");
1825 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1829 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1830 Constant *V2, Constant *Mask) {
1831 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1832 return FC; // Fold a few common cases...
1833 // Look up the constant in the table first to ensure uniqueness
1834 std::vector<Constant*> ArgVec(1, V1);
1835 ArgVec.push_back(V2);
1836 ArgVec.push_back(Mask);
1837 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1838 return ExprConstants->getOrCreate(ReqTy, Key);
1841 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1843 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1844 "Invalid shuffle vector constant expr operands!");
1845 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1848 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1849 if (const PackedType *PTy = dyn_cast<PackedType>(Ty))
1850 if (PTy->getElementType()->isFloatingPoint()) {
1851 std::vector<Constant*> zeros(PTy->getNumElements(),
1852 ConstantFP::get(PTy->getElementType(),-0.0));
1853 return ConstantPacked::get(PTy, zeros);
1856 if (Ty->isFloatingPoint())
1857 return ConstantFP::get(Ty, -0.0);
1859 return Constant::getNullValue(Ty);
1862 // destroyConstant - Remove the constant from the constant table...
1864 void ConstantExpr::destroyConstant() {
1865 ExprConstants->remove(this);
1866 destroyConstantImpl();
1869 const char *ConstantExpr::getOpcodeName() const {
1870 return Instruction::getOpcodeName(getOpcode());
1873 //===----------------------------------------------------------------------===//
1874 // replaceUsesOfWithOnConstant implementations
1876 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1878 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1879 Constant *ToC = cast<Constant>(To);
1881 unsigned OperandToUpdate = U-OperandList;
1882 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1884 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1885 Lookup.first.first = getType();
1886 Lookup.second = this;
1888 std::vector<Constant*> &Values = Lookup.first.second;
1889 Values.reserve(getNumOperands()); // Build replacement array.
1891 // Fill values with the modified operands of the constant array. Also,
1892 // compute whether this turns into an all-zeros array.
1893 bool isAllZeros = false;
1894 if (!ToC->isNullValue()) {
1895 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1896 Values.push_back(cast<Constant>(O->get()));
1899 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1900 Constant *Val = cast<Constant>(O->get());
1901 Values.push_back(Val);
1902 if (isAllZeros) isAllZeros = Val->isNullValue();
1905 Values[OperandToUpdate] = ToC;
1907 Constant *Replacement = 0;
1909 Replacement = ConstantAggregateZero::get(getType());
1911 // Check to see if we have this array type already.
1913 ArrayConstantsTy::MapTy::iterator I =
1914 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1917 Replacement = I->second;
1919 // Okay, the new shape doesn't exist in the system yet. Instead of
1920 // creating a new constant array, inserting it, replaceallusesof'ing the
1921 // old with the new, then deleting the old... just update the current one
1923 ArrayConstants->MoveConstantToNewSlot(this, I);
1925 // Update to the new value.
1926 setOperand(OperandToUpdate, ToC);
1931 // Otherwise, I do need to replace this with an existing value.
1932 assert(Replacement != this && "I didn't contain From!");
1934 // Everyone using this now uses the replacement.
1935 uncheckedReplaceAllUsesWith(Replacement);
1937 // Delete the old constant!
1941 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1943 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1944 Constant *ToC = cast<Constant>(To);
1946 unsigned OperandToUpdate = U-OperandList;
1947 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1949 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1950 Lookup.first.first = getType();
1951 Lookup.second = this;
1952 std::vector<Constant*> &Values = Lookup.first.second;
1953 Values.reserve(getNumOperands()); // Build replacement struct.
1956 // Fill values with the modified operands of the constant struct. Also,
1957 // compute whether this turns into an all-zeros struct.
1958 bool isAllZeros = false;
1959 if (!ToC->isNullValue()) {
1960 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1961 Values.push_back(cast<Constant>(O->get()));
1964 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1965 Constant *Val = cast<Constant>(O->get());
1966 Values.push_back(Val);
1967 if (isAllZeros) isAllZeros = Val->isNullValue();
1970 Values[OperandToUpdate] = ToC;
1972 Constant *Replacement = 0;
1974 Replacement = ConstantAggregateZero::get(getType());
1976 // Check to see if we have this array type already.
1978 StructConstantsTy::MapTy::iterator I =
1979 StructConstants->InsertOrGetItem(Lookup, Exists);
1982 Replacement = I->second;
1984 // Okay, the new shape doesn't exist in the system yet. Instead of
1985 // creating a new constant struct, inserting it, replaceallusesof'ing the
1986 // old with the new, then deleting the old... just update the current one
1988 StructConstants->MoveConstantToNewSlot(this, I);
1990 // Update to the new value.
1991 setOperand(OperandToUpdate, ToC);
1996 assert(Replacement != this && "I didn't contain From!");
1998 // Everyone using this now uses the replacement.
1999 uncheckedReplaceAllUsesWith(Replacement);
2001 // Delete the old constant!
2005 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2007 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2009 std::vector<Constant*> Values;
2010 Values.reserve(getNumOperands()); // Build replacement array...
2011 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2012 Constant *Val = getOperand(i);
2013 if (Val == From) Val = cast<Constant>(To);
2014 Values.push_back(Val);
2017 Constant *Replacement = ConstantPacked::get(getType(), Values);
2018 assert(Replacement != this && "I didn't contain From!");
2020 // Everyone using this now uses the replacement.
2021 uncheckedReplaceAllUsesWith(Replacement);
2023 // Delete the old constant!
2027 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2029 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2030 Constant *To = cast<Constant>(ToV);
2032 Constant *Replacement = 0;
2033 if (getOpcode() == Instruction::GetElementPtr) {
2034 std::vector<Constant*> Indices;
2035 Constant *Pointer = getOperand(0);
2036 Indices.reserve(getNumOperands()-1);
2037 if (Pointer == From) Pointer = To;
2039 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2040 Constant *Val = getOperand(i);
2041 if (Val == From) Val = To;
2042 Indices.push_back(Val);
2044 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2045 } else if (isCast()) {
2046 assert(getOperand(0) == From && "Cast only has one use!");
2047 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2048 } else if (getOpcode() == Instruction::Select) {
2049 Constant *C1 = getOperand(0);
2050 Constant *C2 = getOperand(1);
2051 Constant *C3 = getOperand(2);
2052 if (C1 == From) C1 = To;
2053 if (C2 == From) C2 = To;
2054 if (C3 == From) C3 = To;
2055 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2056 } else if (getOpcode() == Instruction::ExtractElement) {
2057 Constant *C1 = getOperand(0);
2058 Constant *C2 = getOperand(1);
2059 if (C1 == From) C1 = To;
2060 if (C2 == From) C2 = To;
2061 Replacement = ConstantExpr::getExtractElement(C1, C2);
2062 } else if (getOpcode() == Instruction::InsertElement) {
2063 Constant *C1 = getOperand(0);
2064 Constant *C2 = getOperand(1);
2065 Constant *C3 = getOperand(1);
2066 if (C1 == From) C1 = To;
2067 if (C2 == From) C2 = To;
2068 if (C3 == From) C3 = To;
2069 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2070 } else if (getOpcode() == Instruction::ShuffleVector) {
2071 Constant *C1 = getOperand(0);
2072 Constant *C2 = getOperand(1);
2073 Constant *C3 = getOperand(2);
2074 if (C1 == From) C1 = To;
2075 if (C2 == From) C2 = To;
2076 if (C3 == From) C3 = To;
2077 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2078 } else if (isCompare()) {
2079 Constant *C1 = getOperand(0);
2080 Constant *C2 = getOperand(1);
2081 if (C1 == From) C1 = To;
2082 if (C2 == From) C2 = To;
2083 if (getOpcode() == Instruction::ICmp)
2084 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2086 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2087 } else if (getNumOperands() == 2) {
2088 Constant *C1 = getOperand(0);
2089 Constant *C2 = getOperand(1);
2090 if (C1 == From) C1 = To;
2091 if (C2 == From) C2 = To;
2092 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2094 assert(0 && "Unknown ConstantExpr type!");
2098 assert(Replacement != this && "I didn't contain From!");
2100 // Everyone using this now uses the replacement.
2101 uncheckedReplaceAllUsesWith(Replacement);
2103 // Delete the old constant!
2108 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2109 /// global into a string value. Return an empty string if we can't do it.
2110 /// Parameter Chop determines if the result is chopped at the first null
2113 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2114 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2115 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2116 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2117 if (Init->isString()) {
2118 std::string Result = Init->getAsString();
2119 if (Offset < Result.size()) {
2120 // If we are pointing INTO The string, erase the beginning...
2121 Result.erase(Result.begin(), Result.begin()+Offset);
2123 // Take off the null terminator, and any string fragments after it.
2125 std::string::size_type NullPos = Result.find_first_of((char)0);
2126 if (NullPos != std::string::npos)
2127 Result.erase(Result.begin()+NullPos, Result.end());
2133 } else if (Constant *C = dyn_cast<Constant>(this)) {
2134 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2135 return GV->getStringValue(Chop, Offset);
2136 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2137 if (CE->getOpcode() == Instruction::GetElementPtr) {
2138 // Turn a gep into the specified offset.
2139 if (CE->getNumOperands() == 3 &&
2140 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2141 isa<ConstantInt>(CE->getOperand(2))) {
2142 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2143 return CE->getOperand(0)->getStringValue(Chop, Offset);