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 "ConstantFold.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/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
37 // references to the constant by other constants in the constant pool. These
38 // constants are implicitly dependent on the module that is being deleted,
39 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
41 // Constants) that they are, in fact, invalid now and should be deleted.
43 while (!use_empty()) {
44 Value *V = use_back();
45 #ifndef NDEBUG // Only in -g mode...
46 if (!isa<Constant>(V))
47 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
51 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
55 // The constant should remove itself from our use list...
56 assert((use_empty() || use_back() != V) && "Constant not removed!");
59 // Value has no outstanding references it is safe to delete it now...
63 /// canTrap - Return true if evaluation of this constant could trap. This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
80 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
83 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
86 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106 static uint64_t zero[2] = {0, 0};
107 switch (Ty->getTypeID()) {
108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
111 return ConstantFP::get(Ty, APFloat(APInt(32, 0)));
112 case Type::DoubleTyID:
113 return ConstantFP::get(Ty, APFloat(APInt(64, 0)));
114 case Type::X86_FP80TyID:
115 return ConstantFP::get(Ty, APFloat(APInt(80, 2, zero)));
116 case Type::FP128TyID:
117 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero), true));
118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero)));
120 case Type::PointerTyID:
121 return ConstantPointerNull::get(cast<PointerType>(Ty));
122 case Type::StructTyID:
123 case Type::ArrayTyID:
124 case Type::VectorTyID:
125 return ConstantAggregateZero::get(Ty);
127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
152 ConstantInt::getAllOnesValue(Ty->getElementType()));
153 assert(Elts[0] && "Not a vector integer type!");
154 return cast<ConstantVector>(ConstantVector::get(Elts));
158 //===----------------------------------------------------------------------===//
160 //===----------------------------------------------------------------------===//
162 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
167 ConstantInt *ConstantInt::TheTrueVal = 0;
168 ConstantInt *ConstantInt::TheFalseVal = 0;
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
176 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
178 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
186 return WhichOne ? TheTrueVal : TheFalseVal;
191 struct DenseMapAPIntKeyInfo {
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
206 static unsigned getHashValue(const KeyTy &Key) {
207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
208 Key.val.getHashValue();
210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
213 static bool isPod() { return false; }
218 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
220 static ManagedStatic<IntMapTy> IntConstants;
222 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
223 const IntegerType *ITy = cast<IntegerType>(Ty);
224 return get(APInt(ITy->getBitWidth(), V, isSigned));
227 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
228 // as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
229 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
230 // compare APInt's of different widths, which would violate an APInt class
231 // invariant which generates an assertion.
232 ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
235 // get an existing value or the insertion position
236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
241 // otherwise create a new one, insert it, and return it.
242 return Slot = new ConstantInt(ITy, V);
245 //===----------------------------------------------------------------------===//
247 //===----------------------------------------------------------------------===//
249 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
250 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
252 if (Ty==Type::FloatTy)
253 assert(&V.getSemantics()==&APFloat::IEEEsingle);
254 else if (Ty==Type::DoubleTy)
255 assert(&V.getSemantics()==&APFloat::IEEEdouble);
256 else if (Ty==Type::X86_FP80Ty)
257 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
258 else if (Ty==Type::FP128Ty)
259 assert(&V.getSemantics()==&APFloat::IEEEquad);
260 else if (Ty==Type::PPC_FP128Ty)
261 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
266 bool ConstantFP::isNullValue() const {
267 return Val.isZero() && !Val.isNegative();
270 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
271 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
273 return ConstantFP::get(Ty, apf);
276 bool ConstantFP::isExactlyValue(const APFloat& V) const {
277 return Val.bitwiseIsEqual(V);
281 struct DenseMapAPFloatKeyInfo {
284 KeyTy(const APFloat& V) : val(V){}
285 KeyTy(const KeyTy& that) : val(that.val) {}
286 bool operator==(const KeyTy& that) const {
287 return this->val.bitwiseIsEqual(that.val);
289 bool operator!=(const KeyTy& that) const {
290 return !this->operator==(that);
293 static inline KeyTy getEmptyKey() {
294 return KeyTy(APFloat(APFloat::Bogus,1));
296 static inline KeyTy getTombstoneKey() {
297 return KeyTy(APFloat(APFloat::Bogus,2));
299 static unsigned getHashValue(const KeyTy &Key) {
300 return Key.val.getHashValue();
302 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
305 static bool isPod() { return false; }
309 //---- ConstantFP::get() implementation...
311 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
312 DenseMapAPFloatKeyInfo> FPMapTy;
314 static ManagedStatic<FPMapTy> FPConstants;
316 ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
318 if (Ty==Type::FloatTy)
319 assert(&V.getSemantics()==&APFloat::IEEEsingle);
320 else if (Ty==Type::DoubleTy)
321 assert(&V.getSemantics()==&APFloat::IEEEdouble);
322 else if (Ty==Type::X86_FP80Ty)
323 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
324 else if (Ty==Type::FP128Ty)
325 assert(&V.getSemantics()==&APFloat::IEEEquad);
326 else if (Ty==Type::PPC_FP128Ty)
327 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
331 DenseMapAPFloatKeyInfo::KeyTy Key(V);
332 ConstantFP *&Slot = (*FPConstants)[Key];
333 if (Slot) return Slot;
334 return Slot = new ConstantFP(Ty, V);
337 //===----------------------------------------------------------------------===//
338 // ConstantXXX Classes
339 //===----------------------------------------------------------------------===//
342 ConstantArray::ConstantArray(const ArrayType *T,
343 const std::vector<Constant*> &V)
344 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
345 assert(V.size() == T->getNumElements() &&
346 "Invalid initializer vector for constant array");
347 Use *OL = OperandList;
348 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
351 assert((C->getType() == T->getElementType() ||
353 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
354 "Initializer for array element doesn't match array element type!");
359 void ConstantArray::destroyThis(ConstantArray*v) {
360 delete [] v->OperandList;
361 Constant::destroyThis(v);
364 ConstantStruct::ConstantStruct(const StructType *T,
365 const std::vector<Constant*> &V)
366 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
367 assert(V.size() == T->getNumElements() &&
368 "Invalid initializer vector for constant structure");
369 Use *OL = OperandList;
370 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
373 assert((C->getType() == T->getElementType(I-V.begin()) ||
374 ((T->getElementType(I-V.begin())->isAbstract() ||
375 C->getType()->isAbstract()) &&
376 T->getElementType(I-V.begin())->getTypeID() ==
377 C->getType()->getTypeID())) &&
378 "Initializer for struct element doesn't match struct element type!");
383 void ConstantStruct::destroyThis(ConstantStruct*v) {
384 delete [] v->OperandList;
385 Constant::destroyThis(v);
389 ConstantVector::ConstantVector(const VectorType *T,
390 const std::vector<Constant*> &V)
391 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
392 Use *OL = OperandList;
393 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
396 assert((C->getType() == T->getElementType() ||
398 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
399 "Initializer for vector element doesn't match vector element type!");
404 void ConstantVector::destroyThis(ConstantVector*v) {
405 delete [] v->OperandList;
406 Constant::destroyThis(v);
409 UnaryConstantExpr::UnaryConstantExpr(unsigned Opcode,
410 Constant *C, const Type *Ty)
411 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {
414 SelectConstantExpr::SelectConstantExpr(Constant *C1,
415 Constant *C2, Constant *C3)
416 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
417 Ops[0].init(C1, this);
418 Ops[1].init(C2, this);
419 Ops[2].init(C3, this);
422 ExtractElementConstantExpr::ExtractElementConstantExpr(Constant *C1,
424 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
425 Instruction::ExtractElement, Ops, 2) {
426 Ops[0].init(C1, this);
427 Ops[1].init(C2, this);
430 InsertElementConstantExpr::InsertElementConstantExpr(Constant *C1,
433 : ConstantExpr(C1->getType(), Instruction::InsertElement, Ops, 3) {
434 Ops[0].init(C1, this);
435 Ops[1].init(C2, this);
436 Ops[2].init(C3, this);
439 ShuffleVectorConstantExpr::ShuffleVectorConstantExpr(Constant *C1,
442 : ConstantExpr(C1->getType(), Instruction::ShuffleVector, Ops, 3) {
443 Ops[0].init(C1, this);
444 Ops[1].init(C2, this);
445 Ops[2].init(C3, this);
448 CompareConstantExpr::CompareConstantExpr(unsigned opc, unsigned short pred,
449 Constant* LHS, Constant* RHS)
450 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
451 OperandList[0].init(LHS, this);
452 OperandList[1].init(RHS, this);
455 GetElementPtrConstantExpr::GetElementPtrConstantExpr(Constant *C,
456 const std::vector<Constant*>
457 &IdxList, const Type *DestTy)
458 : ConstantExpr(DestTy, Instruction::GetElementPtr,
459 new Use[IdxList.size()+1], IdxList.size()+1)
461 OperandList[0].init(C, this);
462 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
463 OperandList[i+1].init(IdxList[i], this);
466 // Utility function for determining if a ConstantExpr is a CastOp or not. This
467 // can't be inline because we don't want to #include Instruction.h into
469 bool ConstantExpr::isCast() const {
470 return Instruction::isCast(getOpcode());
473 bool ConstantExpr::isCompare() const {
474 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
477 /// ConstantExpr::get* - Return some common constants without having to
478 /// specify the full Instruction::OPCODE identifier.
480 Constant *ConstantExpr::getNeg(Constant *C) {
481 return get(Instruction::Sub,
482 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
485 Constant *ConstantExpr::getNot(Constant *C) {
486 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
487 return get(Instruction::Xor, C,
488 ConstantInt::getAllOnesValue(C->getType()));
490 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
491 return get(Instruction::Add, C1, C2);
493 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
494 return get(Instruction::Sub, C1, C2);
496 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
497 return get(Instruction::Mul, C1, C2);
499 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
500 return get(Instruction::UDiv, C1, C2);
502 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
503 return get(Instruction::SDiv, C1, C2);
505 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
506 return get(Instruction::FDiv, C1, C2);
508 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
509 return get(Instruction::URem, C1, C2);
511 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
512 return get(Instruction::SRem, C1, C2);
514 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
515 return get(Instruction::FRem, C1, C2);
517 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
518 return get(Instruction::And, C1, C2);
520 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
521 return get(Instruction::Or, C1, C2);
523 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
524 return get(Instruction::Xor, C1, C2);
526 unsigned ConstantExpr::getPredicate() const {
527 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
528 return ((const CompareConstantExpr*)this)->predicate;
530 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
531 return get(Instruction::Shl, C1, C2);
533 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
534 return get(Instruction::LShr, C1, C2);
536 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
537 return get(Instruction::AShr, C1, C2);
540 /// getWithOperandReplaced - Return a constant expression identical to this
541 /// one, but with the specified operand set to the specified value.
543 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
544 assert(OpNo < getNumOperands() && "Operand num is out of range!");
545 assert(Op->getType() == getOperand(OpNo)->getType() &&
546 "Replacing operand with value of different type!");
547 if (getOperand(OpNo) == Op)
548 return const_cast<ConstantExpr*>(this);
550 Constant *Op0, *Op1, *Op2;
551 switch (getOpcode()) {
552 case Instruction::Trunc:
553 case Instruction::ZExt:
554 case Instruction::SExt:
555 case Instruction::FPTrunc:
556 case Instruction::FPExt:
557 case Instruction::UIToFP:
558 case Instruction::SIToFP:
559 case Instruction::FPToUI:
560 case Instruction::FPToSI:
561 case Instruction::PtrToInt:
562 case Instruction::IntToPtr:
563 case Instruction::BitCast:
564 return ConstantExpr::getCast(getOpcode(), Op, getType());
565 case Instruction::Select:
566 Op0 = (OpNo == 0) ? Op : getOperand(0);
567 Op1 = (OpNo == 1) ? Op : getOperand(1);
568 Op2 = (OpNo == 2) ? Op : getOperand(2);
569 return ConstantExpr::getSelect(Op0, Op1, Op2);
570 case Instruction::InsertElement:
571 Op0 = (OpNo == 0) ? Op : getOperand(0);
572 Op1 = (OpNo == 1) ? Op : getOperand(1);
573 Op2 = (OpNo == 2) ? Op : getOperand(2);
574 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
575 case Instruction::ExtractElement:
576 Op0 = (OpNo == 0) ? Op : getOperand(0);
577 Op1 = (OpNo == 1) ? Op : getOperand(1);
578 return ConstantExpr::getExtractElement(Op0, Op1);
579 case Instruction::ShuffleVector:
580 Op0 = (OpNo == 0) ? Op : getOperand(0);
581 Op1 = (OpNo == 1) ? Op : getOperand(1);
582 Op2 = (OpNo == 2) ? Op : getOperand(2);
583 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
584 case Instruction::GetElementPtr: {
585 SmallVector<Constant*, 8> Ops;
586 Ops.resize(getNumOperands());
587 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
588 Ops[i] = getOperand(i);
590 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
592 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
595 assert(getNumOperands() == 2 && "Must be binary operator?");
596 Op0 = (OpNo == 0) ? Op : getOperand(0);
597 Op1 = (OpNo == 1) ? Op : getOperand(1);
598 return ConstantExpr::get(getOpcode(), Op0, Op1);
602 /// getWithOperands - This returns the current constant expression with the
603 /// operands replaced with the specified values. The specified operands must
604 /// match count and type with the existing ones.
605 Constant *ConstantExpr::
606 getWithOperands(const std::vector<Constant*> &Ops) const {
607 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
608 bool AnyChange = false;
609 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
610 assert(Ops[i]->getType() == getOperand(i)->getType() &&
611 "Operand type mismatch!");
612 AnyChange |= Ops[i] != getOperand(i);
614 if (!AnyChange) // No operands changed, return self.
615 return const_cast<ConstantExpr*>(this);
617 switch (getOpcode()) {
618 case Instruction::Trunc:
619 case Instruction::ZExt:
620 case Instruction::SExt:
621 case Instruction::FPTrunc:
622 case Instruction::FPExt:
623 case Instruction::UIToFP:
624 case Instruction::SIToFP:
625 case Instruction::FPToUI:
626 case Instruction::FPToSI:
627 case Instruction::PtrToInt:
628 case Instruction::IntToPtr:
629 case Instruction::BitCast:
630 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
631 case Instruction::Select:
632 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
633 case Instruction::InsertElement:
634 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
635 case Instruction::ExtractElement:
636 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
637 case Instruction::ShuffleVector:
638 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
639 case Instruction::GetElementPtr:
640 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
641 case Instruction::ICmp:
642 case Instruction::FCmp:
643 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
645 assert(getNumOperands() == 2 && "Must be binary operator?");
646 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
651 //===----------------------------------------------------------------------===//
652 // isValueValidForType implementations
654 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
655 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
656 if (Ty == Type::Int1Ty)
657 return Val == 0 || Val == 1;
659 return true; // always true, has to fit in largest type
660 uint64_t Max = (1ll << NumBits) - 1;
664 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
665 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
666 if (Ty == Type::Int1Ty)
667 return Val == 0 || Val == 1 || Val == -1;
669 return true; // always true, has to fit in largest type
670 int64_t Min = -(1ll << (NumBits-1));
671 int64_t Max = (1ll << (NumBits-1)) - 1;
672 return (Val >= Min && Val <= Max);
675 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
676 // convert modifies in place, so make a copy.
677 APFloat Val2 = APFloat(Val);
678 switch (Ty->getTypeID()) {
680 return false; // These can't be represented as floating point!
682 // FIXME rounding mode needs to be more flexible
683 case Type::FloatTyID:
684 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
685 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
687 case Type::DoubleTyID:
688 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
689 &Val2.getSemantics() == &APFloat::IEEEdouble ||
690 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
692 case Type::X86_FP80TyID:
693 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
694 &Val2.getSemantics() == &APFloat::IEEEdouble ||
695 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
696 case Type::FP128TyID:
697 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
698 &Val2.getSemantics() == &APFloat::IEEEdouble ||
699 &Val2.getSemantics() == &APFloat::IEEEquad;
700 case Type::PPC_FP128TyID:
701 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
702 &Val2.getSemantics() == &APFloat::IEEEdouble ||
703 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
707 //===----------------------------------------------------------------------===//
708 // Factory Function Implementation
710 // ConstantCreator - A class that is used to create constants by
711 // ValueMap*. This class should be partially specialized if there is
712 // something strange that needs to be done to interface to the ctor for the
716 template<class ConstantClass, class TypeClass, class ValType>
717 struct VISIBILITY_HIDDEN ConstantCreator {
718 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
719 return new ConstantClass(Ty, V);
723 template<class ConstantClass, class TypeClass>
724 struct VISIBILITY_HIDDEN ConvertConstantType {
725 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
726 assert(0 && "This type cannot be converted!\n");
731 template<class ValType, class TypeClass, class ConstantClass,
732 bool HasLargeKey = false /*true for arrays and structs*/ >
733 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
735 typedef std::pair<const Type*, ValType> MapKey;
736 typedef std::map<MapKey, Constant *> MapTy;
737 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
738 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
740 /// Map - This is the main map from the element descriptor to the Constants.
741 /// This is the primary way we avoid creating two of the same shape
745 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
746 /// from the constants to their element in Map. This is important for
747 /// removal of constants from the array, which would otherwise have to scan
748 /// through the map with very large keys.
749 InverseMapTy InverseMap;
751 /// AbstractTypeMap - Map for abstract type constants.
753 AbstractTypeMapTy AbstractTypeMap;
756 typename MapTy::iterator map_end() { return Map.end(); }
758 /// InsertOrGetItem - Return an iterator for the specified element.
759 /// If the element exists in the map, the returned iterator points to the
760 /// entry and Exists=true. If not, the iterator points to the newly
761 /// inserted entry and returns Exists=false. Newly inserted entries have
762 /// I->second == 0, and should be filled in.
763 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
766 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
772 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
774 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
775 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
776 IMI->second->second == CP &&
777 "InverseMap corrupt!");
781 typename MapTy::iterator I =
782 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
783 if (I == Map.end() || I->second != CP) {
784 // FIXME: This should not use a linear scan. If this gets to be a
785 // performance problem, someone should look at this.
786 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
793 /// getOrCreate - Return the specified constant from the map, creating it if
795 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
796 MapKey Lookup(Ty, V);
797 typename MapTy::iterator I = Map.lower_bound(Lookup);
799 if (I != Map.end() && I->first == Lookup)
800 return static_cast<ConstantClass *>(I->second);
802 // If no preexisting value, create one now...
803 ConstantClass *Result =
804 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
806 /// FIXME: why does this assert fail when loading 176.gcc?
807 //assert(Result->getType() == Ty && "Type specified is not correct!");
808 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
810 if (HasLargeKey) // Remember the reverse mapping if needed.
811 InverseMap.insert(std::make_pair(Result, I));
813 // If the type of the constant is abstract, make sure that an entry exists
814 // for it in the AbstractTypeMap.
815 if (Ty->isAbstract()) {
816 typename AbstractTypeMapTy::iterator TI =
817 AbstractTypeMap.lower_bound(Ty);
819 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
820 // Add ourselves to the ATU list of the type.
821 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
823 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
829 void remove(ConstantClass *CP) {
830 typename MapTy::iterator I = FindExistingElement(CP);
831 assert(I != Map.end() && "Constant not found in constant table!");
832 assert(I->second == CP && "Didn't find correct element?");
834 if (HasLargeKey) // Remember the reverse mapping if needed.
835 InverseMap.erase(CP);
837 // Now that we found the entry, make sure this isn't the entry that
838 // the AbstractTypeMap points to.
839 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
840 if (Ty->isAbstract()) {
841 assert(AbstractTypeMap.count(Ty) &&
842 "Abstract type not in AbstractTypeMap?");
843 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
844 if (ATMEntryIt == I) {
845 // Yes, we are removing the representative entry for this type.
846 // See if there are any other entries of the same type.
847 typename MapTy::iterator TmpIt = ATMEntryIt;
849 // First check the entry before this one...
850 if (TmpIt != Map.begin()) {
852 if (TmpIt->first.first != Ty) // Not the same type, move back...
856 // If we didn't find the same type, try to move forward...
857 if (TmpIt == ATMEntryIt) {
859 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
860 --TmpIt; // No entry afterwards with the same type
863 // If there is another entry in the map of the same abstract type,
864 // update the AbstractTypeMap entry now.
865 if (TmpIt != ATMEntryIt) {
868 // Otherwise, we are removing the last instance of this type
869 // from the table. Remove from the ATM, and from user list.
870 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
871 AbstractTypeMap.erase(Ty);
880 /// MoveConstantToNewSlot - If we are about to change C to be the element
881 /// specified by I, update our internal data structures to reflect this
883 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
884 // First, remove the old location of the specified constant in the map.
885 typename MapTy::iterator OldI = FindExistingElement(C);
886 assert(OldI != Map.end() && "Constant not found in constant table!");
887 assert(OldI->second == C && "Didn't find correct element?");
889 // If this constant is the representative element for its abstract type,
890 // update the AbstractTypeMap so that the representative element is I.
891 if (C->getType()->isAbstract()) {
892 typename AbstractTypeMapTy::iterator ATI =
893 AbstractTypeMap.find(C->getType());
894 assert(ATI != AbstractTypeMap.end() &&
895 "Abstract type not in AbstractTypeMap?");
896 if (ATI->second == OldI)
900 // Remove the old entry from the map.
903 // Update the inverse map so that we know that this constant is now
904 // located at descriptor I.
906 assert(I->second == C && "Bad inversemap entry!");
911 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
912 typename AbstractTypeMapTy::iterator I =
913 AbstractTypeMap.find(cast<Type>(OldTy));
915 assert(I != AbstractTypeMap.end() &&
916 "Abstract type not in AbstractTypeMap?");
918 // Convert a constant at a time until the last one is gone. The last one
919 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
920 // eliminated eventually.
922 ConvertConstantType<ConstantClass,
924 static_cast<ConstantClass *>(I->second->second),
925 cast<TypeClass>(NewTy));
927 I = AbstractTypeMap.find(cast<Type>(OldTy));
928 } while (I != AbstractTypeMap.end());
931 // If the type became concrete without being refined to any other existing
932 // type, we just remove ourselves from the ATU list.
933 void typeBecameConcrete(const DerivedType *AbsTy) {
934 AbsTy->removeAbstractTypeUser(this);
938 DOUT << "Constant.cpp: ValueMap\n";
945 //---- ConstantAggregateZero::get() implementation...
948 // ConstantAggregateZero does not take extra "value" argument...
949 template<class ValType>
950 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
951 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
952 return new ConstantAggregateZero(Ty);
957 struct ConvertConstantType<ConstantAggregateZero, Type> {
958 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
959 // Make everyone now use a constant of the new type...
960 Constant *New = ConstantAggregateZero::get(NewTy);
961 assert(New != OldC && "Didn't replace constant??");
962 OldC->uncheckedReplaceAllUsesWith(New);
963 OldC->destroyConstant(); // This constant is now dead, destroy it.
968 static ManagedStatic<ValueMap<char, Type,
969 ConstantAggregateZero> > AggZeroConstants;
971 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
973 Constant *ConstantAggregateZero::get(const Type *Ty) {
974 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
975 "Cannot create an aggregate zero of non-aggregate type!");
976 return AggZeroConstants->getOrCreate(Ty, 0);
979 // destroyConstant - Remove the constant from the constant table...
981 void ConstantAggregateZero::destroyConstant() {
982 AggZeroConstants->remove(this);
983 destroyConstantImpl();
986 //---- ConstantArray::get() implementation...
990 struct ConvertConstantType<ConstantArray, ArrayType> {
991 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
992 // Make everyone now use a constant of the new type...
993 std::vector<Constant*> C;
994 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
995 C.push_back(cast<Constant>(OldC->getOperand(i)));
996 Constant *New = ConstantArray::get(NewTy, C);
997 assert(New != OldC && "Didn't replace constant??");
998 OldC->uncheckedReplaceAllUsesWith(New);
999 OldC->destroyConstant(); // This constant is now dead, destroy it.
1004 static std::vector<Constant*> getValType(ConstantArray *CA) {
1005 std::vector<Constant*> Elements;
1006 Elements.reserve(CA->getNumOperands());
1007 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1008 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1012 typedef ValueMap<std::vector<Constant*>, ArrayType,
1013 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1014 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1016 Constant *ConstantArray::get(const ArrayType *Ty,
1017 const std::vector<Constant*> &V) {
1018 // If this is an all-zero array, return a ConstantAggregateZero object
1021 if (!C->isNullValue())
1022 return ArrayConstants->getOrCreate(Ty, V);
1023 for (unsigned i = 1, e = V.size(); i != e; ++i)
1025 return ArrayConstants->getOrCreate(Ty, V);
1027 return ConstantAggregateZero::get(Ty);
1030 // destroyConstant - Remove the constant from the constant table...
1032 void ConstantArray::destroyConstant() {
1033 ArrayConstants->remove(this);
1034 destroyConstantImpl();
1037 /// ConstantArray::get(const string&) - Return an array that is initialized to
1038 /// contain the specified string. If length is zero then a null terminator is
1039 /// added to the specified string so that it may be used in a natural way.
1040 /// Otherwise, the length parameter specifies how much of the string to use
1041 /// and it won't be null terminated.
1043 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1044 std::vector<Constant*> ElementVals;
1045 for (unsigned i = 0; i < Str.length(); ++i)
1046 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1048 // Add a null terminator to the string...
1050 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1053 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1054 return ConstantArray::get(ATy, ElementVals);
1057 /// isString - This method returns true if the array is an array of i8, and
1058 /// if the elements of the array are all ConstantInt's.
1059 bool ConstantArray::isString() const {
1060 // Check the element type for i8...
1061 if (getType()->getElementType() != Type::Int8Ty)
1063 // Check the elements to make sure they are all integers, not constant
1065 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1066 if (!isa<ConstantInt>(getOperand(i)))
1071 /// isCString - This method returns true if the array is a string (see
1072 /// isString) and it ends in a null byte \0 and does not contains any other
1073 /// null bytes except its terminator.
1074 bool ConstantArray::isCString() const {
1075 // Check the element type for i8...
1076 if (getType()->getElementType() != Type::Int8Ty)
1078 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1079 // Last element must be a null.
1080 if (getOperand(getNumOperands()-1) != Zero)
1082 // Other elements must be non-null integers.
1083 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1084 if (!isa<ConstantInt>(getOperand(i)))
1086 if (getOperand(i) == Zero)
1093 // getAsString - If the sub-element type of this array is i8
1094 // then this method converts the array to an std::string and returns it.
1095 // Otherwise, it asserts out.
1097 std::string ConstantArray::getAsString() const {
1098 assert(isString() && "Not a string!");
1100 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1101 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1106 //---- ConstantStruct::get() implementation...
1111 struct ConvertConstantType<ConstantStruct, StructType> {
1112 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1113 // Make everyone now use a constant of the new type...
1114 std::vector<Constant*> C;
1115 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1116 C.push_back(cast<Constant>(OldC->getOperand(i)));
1117 Constant *New = ConstantStruct::get(NewTy, C);
1118 assert(New != OldC && "Didn't replace constant??");
1120 OldC->uncheckedReplaceAllUsesWith(New);
1121 OldC->destroyConstant(); // This constant is now dead, destroy it.
1126 typedef ValueMap<std::vector<Constant*>, StructType,
1127 ConstantStruct, true /*largekey*/> StructConstantsTy;
1128 static ManagedStatic<StructConstantsTy> StructConstants;
1130 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1131 std::vector<Constant*> Elements;
1132 Elements.reserve(CS->getNumOperands());
1133 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1134 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1138 Constant *ConstantStruct::get(const StructType *Ty,
1139 const std::vector<Constant*> &V) {
1140 // Create a ConstantAggregateZero value if all elements are zeros...
1141 for (unsigned i = 0, e = V.size(); i != e; ++i)
1142 if (!V[i]->isNullValue())
1143 return StructConstants->getOrCreate(Ty, V);
1145 return ConstantAggregateZero::get(Ty);
1148 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1149 std::vector<const Type*> StructEls;
1150 StructEls.reserve(V.size());
1151 for (unsigned i = 0, e = V.size(); i != e; ++i)
1152 StructEls.push_back(V[i]->getType());
1153 return get(StructType::get(StructEls, packed), V);
1156 // destroyConstant - Remove the constant from the constant table...
1158 void ConstantStruct::destroyConstant() {
1159 StructConstants->remove(this);
1160 destroyConstantImpl();
1163 //---- ConstantVector::get() implementation...
1167 struct ConvertConstantType<ConstantVector, VectorType> {
1168 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1169 // Make everyone now use a constant of the new type...
1170 std::vector<Constant*> C;
1171 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1172 C.push_back(cast<Constant>(OldC->getOperand(i)));
1173 Constant *New = ConstantVector::get(NewTy, C);
1174 assert(New != OldC && "Didn't replace constant??");
1175 OldC->uncheckedReplaceAllUsesWith(New);
1176 OldC->destroyConstant(); // This constant is now dead, destroy it.
1181 static std::vector<Constant*> getValType(ConstantVector *CP) {
1182 std::vector<Constant*> Elements;
1183 Elements.reserve(CP->getNumOperands());
1184 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1185 Elements.push_back(CP->getOperand(i));
1189 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1190 ConstantVector> > VectorConstants;
1192 Constant *ConstantVector::get(const VectorType *Ty,
1193 const std::vector<Constant*> &V) {
1194 // If this is an all-zero vector, return a ConstantAggregateZero object
1197 if (!C->isNullValue())
1198 return VectorConstants->getOrCreate(Ty, V);
1199 for (unsigned i = 1, e = V.size(); i != e; ++i)
1201 return VectorConstants->getOrCreate(Ty, V);
1203 return ConstantAggregateZero::get(Ty);
1206 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1207 assert(!V.empty() && "Cannot infer type if V is empty");
1208 return get(VectorType::get(V.front()->getType(),V.size()), V);
1211 // destroyConstant - Remove the constant from the constant table...
1213 void ConstantVector::destroyConstant() {
1214 VectorConstants->remove(this);
1215 destroyConstantImpl();
1218 /// This function will return true iff every element in this vector constant
1219 /// is set to all ones.
1220 /// @returns true iff this constant's emements are all set to all ones.
1221 /// @brief Determine if the value is all ones.
1222 bool ConstantVector::isAllOnesValue() const {
1223 // Check out first element.
1224 const Constant *Elt = getOperand(0);
1225 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1226 if (!CI || !CI->isAllOnesValue()) return false;
1227 // Then make sure all remaining elements point to the same value.
1228 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1229 if (getOperand(I) != Elt) return false;
1234 /// getSplatValue - If this is a splat constant, where all of the
1235 /// elements have the same value, return that value. Otherwise return null.
1236 Constant *ConstantVector::getSplatValue() {
1237 // Check out first element.
1238 Constant *Elt = getOperand(0);
1239 // Then make sure all remaining elements point to the same value.
1240 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1241 if (getOperand(I) != Elt) return 0;
1245 //---- ConstantPointerNull::get() implementation...
1249 // ConstantPointerNull does not take extra "value" argument...
1250 template<class ValType>
1251 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1252 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1253 return new ConstantPointerNull(Ty);
1258 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1259 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1260 // Make everyone now use a constant of the new type...
1261 Constant *New = ConstantPointerNull::get(NewTy);
1262 assert(New != OldC && "Didn't replace constant??");
1263 OldC->uncheckedReplaceAllUsesWith(New);
1264 OldC->destroyConstant(); // This constant is now dead, destroy it.
1269 static ManagedStatic<ValueMap<char, PointerType,
1270 ConstantPointerNull> > NullPtrConstants;
1272 static char getValType(ConstantPointerNull *) {
1277 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1278 return NullPtrConstants->getOrCreate(Ty, 0);
1281 // destroyConstant - Remove the constant from the constant table...
1283 void ConstantPointerNull::destroyConstant() {
1284 NullPtrConstants->remove(this);
1285 destroyConstantImpl();
1289 //---- UndefValue::get() implementation...
1293 // UndefValue does not take extra "value" argument...
1294 template<class ValType>
1295 struct ConstantCreator<UndefValue, Type, ValType> {
1296 static UndefValue *create(const Type *Ty, const ValType &V) {
1297 return new UndefValue(Ty);
1302 struct ConvertConstantType<UndefValue, Type> {
1303 static void convert(UndefValue *OldC, const Type *NewTy) {
1304 // Make everyone now use a constant of the new type.
1305 Constant *New = UndefValue::get(NewTy);
1306 assert(New != OldC && "Didn't replace constant??");
1307 OldC->uncheckedReplaceAllUsesWith(New);
1308 OldC->destroyConstant(); // This constant is now dead, destroy it.
1313 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1315 static char getValType(UndefValue *) {
1320 UndefValue *UndefValue::get(const Type *Ty) {
1321 return UndefValueConstants->getOrCreate(Ty, 0);
1324 // destroyConstant - Remove the constant from the constant table.
1326 void UndefValue::destroyConstant() {
1327 UndefValueConstants->remove(this);
1328 destroyConstantImpl();
1332 //---- ConstantExpr::get() implementations...
1335 struct ExprMapKeyType {
1336 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1337 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1340 std::vector<Constant*> operands;
1341 bool operator==(const ExprMapKeyType& that) const {
1342 return this->opcode == that.opcode &&
1343 this->predicate == that.predicate &&
1344 this->operands == that.operands;
1346 bool operator<(const ExprMapKeyType & that) const {
1347 return this->opcode < that.opcode ||
1348 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1349 (this->opcode == that.opcode && this->predicate == that.predicate &&
1350 this->operands < that.operands);
1353 bool operator!=(const ExprMapKeyType& that) const {
1354 return !(*this == that);
1360 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1361 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1362 unsigned short pred = 0) {
1363 if (Instruction::isCast(V.opcode))
1364 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1365 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1366 V.opcode < Instruction::BinaryOpsEnd))
1367 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1368 if (V.opcode == Instruction::Select)
1369 return new SelectConstantExpr(V.operands[0], V.operands[1],
1371 if (V.opcode == Instruction::ExtractElement)
1372 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1373 if (V.opcode == Instruction::InsertElement)
1374 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1376 if (V.opcode == Instruction::ShuffleVector)
1377 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1379 if (V.opcode == Instruction::GetElementPtr) {
1380 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1381 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1384 // The compare instructions are weird. We have to encode the predicate
1385 // value and it is combined with the instruction opcode by multiplying
1386 // the opcode by one hundred. We must decode this to get the predicate.
1387 if (V.opcode == Instruction::ICmp)
1388 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1389 V.operands[0], V.operands[1]);
1390 if (V.opcode == Instruction::FCmp)
1391 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1392 V.operands[0], V.operands[1]);
1393 assert(0 && "Invalid ConstantExpr!");
1399 struct ConvertConstantType<ConstantExpr, Type> {
1400 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1402 switch (OldC->getOpcode()) {
1403 case Instruction::Trunc:
1404 case Instruction::ZExt:
1405 case Instruction::SExt:
1406 case Instruction::FPTrunc:
1407 case Instruction::FPExt:
1408 case Instruction::UIToFP:
1409 case Instruction::SIToFP:
1410 case Instruction::FPToUI:
1411 case Instruction::FPToSI:
1412 case Instruction::PtrToInt:
1413 case Instruction::IntToPtr:
1414 case Instruction::BitCast:
1415 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1418 case Instruction::Select:
1419 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1420 OldC->getOperand(1),
1421 OldC->getOperand(2));
1424 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1425 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1426 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1427 OldC->getOperand(1));
1429 case Instruction::GetElementPtr:
1430 // Make everyone now use a constant of the new type...
1431 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1432 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1433 &Idx[0], Idx.size());
1437 assert(New != OldC && "Didn't replace constant??");
1438 OldC->uncheckedReplaceAllUsesWith(New);
1439 OldC->destroyConstant(); // This constant is now dead, destroy it.
1442 } // end namespace llvm
1445 static ExprMapKeyType getValType(ConstantExpr *CE) {
1446 std::vector<Constant*> Operands;
1447 Operands.reserve(CE->getNumOperands());
1448 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1449 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1450 return ExprMapKeyType(CE->getOpcode(), Operands,
1451 CE->isCompare() ? CE->getPredicate() : 0);
1454 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1455 ConstantExpr> > ExprConstants;
1457 /// This is a utility function to handle folding of casts and lookup of the
1458 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1459 static inline Constant *getFoldedCast(
1460 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1461 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1462 // Fold a few common cases
1463 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1466 // Look up the constant in the table first to ensure uniqueness
1467 std::vector<Constant*> argVec(1, C);
1468 ExprMapKeyType Key(opc, argVec);
1469 return ExprConstants->getOrCreate(Ty, Key);
1472 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1473 Instruction::CastOps opc = Instruction::CastOps(oc);
1474 assert(Instruction::isCast(opc) && "opcode out of range");
1475 assert(C && Ty && "Null arguments to getCast");
1476 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1480 assert(0 && "Invalid cast opcode");
1482 case Instruction::Trunc: return getTrunc(C, Ty);
1483 case Instruction::ZExt: return getZExt(C, Ty);
1484 case Instruction::SExt: return getSExt(C, Ty);
1485 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1486 case Instruction::FPExt: return getFPExtend(C, Ty);
1487 case Instruction::UIToFP: return getUIToFP(C, Ty);
1488 case Instruction::SIToFP: return getSIToFP(C, Ty);
1489 case Instruction::FPToUI: return getFPToUI(C, Ty);
1490 case Instruction::FPToSI: return getFPToSI(C, Ty);
1491 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1492 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1493 case Instruction::BitCast: return getBitCast(C, Ty);
1498 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1499 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1500 return getCast(Instruction::BitCast, C, Ty);
1501 return getCast(Instruction::ZExt, C, Ty);
1504 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1505 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1506 return getCast(Instruction::BitCast, C, Ty);
1507 return getCast(Instruction::SExt, C, Ty);
1510 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1511 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1512 return getCast(Instruction::BitCast, C, Ty);
1513 return getCast(Instruction::Trunc, C, Ty);
1516 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1517 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1518 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1520 if (Ty->isInteger())
1521 return getCast(Instruction::PtrToInt, S, Ty);
1522 return getCast(Instruction::BitCast, S, Ty);
1525 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1527 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1528 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1529 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1530 Instruction::CastOps opcode =
1531 (SrcBits == DstBits ? Instruction::BitCast :
1532 (SrcBits > DstBits ? Instruction::Trunc :
1533 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1534 return getCast(opcode, C, Ty);
1537 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1538 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1540 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1541 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1542 if (SrcBits == DstBits)
1543 return C; // Avoid a useless cast
1544 Instruction::CastOps opcode =
1545 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1546 return getCast(opcode, C, Ty);
1549 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1550 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1551 assert(Ty->isInteger() && "Trunc produces only integral");
1552 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1553 "SrcTy must be larger than DestTy for Trunc!");
1555 return getFoldedCast(Instruction::Trunc, C, Ty);
1558 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1559 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1560 assert(Ty->isInteger() && "SExt produces only integer");
1561 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1562 "SrcTy must be smaller than DestTy for SExt!");
1564 return getFoldedCast(Instruction::SExt, C, Ty);
1567 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1568 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1569 assert(Ty->isInteger() && "ZExt produces only integer");
1570 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1571 "SrcTy must be smaller than DestTy for ZExt!");
1573 return getFoldedCast(Instruction::ZExt, C, Ty);
1576 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1577 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1578 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1579 "This is an illegal floating point truncation!");
1580 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1583 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1584 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1585 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1586 "This is an illegal floating point extension!");
1587 return getFoldedCast(Instruction::FPExt, C, Ty);
1590 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1591 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1593 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1594 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1595 "This is an illegal uint to floating point cast!");
1596 return getFoldedCast(Instruction::UIToFP, C, Ty);
1599 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1600 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1601 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1602 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1603 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1604 "This is an illegal sint to floating point cast!");
1605 return getFoldedCast(Instruction::SIToFP, C, Ty);
1608 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1609 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1610 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1611 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1612 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1613 "This is an illegal floating point to uint cast!");
1614 return getFoldedCast(Instruction::FPToUI, C, Ty);
1617 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1618 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1619 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1620 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1621 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1622 "This is an illegal floating point to sint cast!");
1623 return getFoldedCast(Instruction::FPToSI, C, Ty);
1626 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1627 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1628 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1629 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1632 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1633 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1634 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1635 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1638 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1639 // BitCast implies a no-op cast of type only. No bits change. However, you
1640 // can't cast pointers to anything but pointers.
1641 const Type *SrcTy = C->getType();
1642 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1643 "BitCast cannot cast pointer to non-pointer and vice versa");
1645 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1646 // or nonptr->ptr). For all the other types, the cast is okay if source and
1647 // destination bit widths are identical.
1648 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1649 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1650 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1651 return getFoldedCast(Instruction::BitCast, C, DstTy);
1654 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1655 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1656 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1658 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1659 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1662 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1663 Constant *C1, Constant *C2) {
1664 // Check the operands for consistency first
1665 assert(Opcode >= Instruction::BinaryOpsBegin &&
1666 Opcode < Instruction::BinaryOpsEnd &&
1667 "Invalid opcode in binary constant expression");
1668 assert(C1->getType() == C2->getType() &&
1669 "Operand types in binary constant expression should match");
1671 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1672 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1673 return FC; // Fold a few common cases...
1675 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1676 ExprMapKeyType Key(Opcode, argVec);
1677 return ExprConstants->getOrCreate(ReqTy, Key);
1680 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1681 Constant *C1, Constant *C2) {
1682 switch (predicate) {
1683 default: assert(0 && "Invalid CmpInst predicate");
1684 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1685 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1686 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1687 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1688 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1689 case FCmpInst::FCMP_TRUE:
1690 return getFCmp(predicate, C1, C2);
1691 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1692 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1693 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1694 case ICmpInst::ICMP_SLE:
1695 return getICmp(predicate, C1, C2);
1699 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1702 case Instruction::Add:
1703 case Instruction::Sub:
1704 case Instruction::Mul:
1705 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1706 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1707 isa<VectorType>(C1->getType())) &&
1708 "Tried to create an arithmetic operation on a non-arithmetic type!");
1710 case Instruction::UDiv:
1711 case Instruction::SDiv:
1712 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1713 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1714 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1715 "Tried to create an arithmetic operation on a non-arithmetic type!");
1717 case Instruction::FDiv:
1718 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1719 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1720 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1721 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1723 case Instruction::URem:
1724 case Instruction::SRem:
1725 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1727 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1728 "Tried to create an arithmetic operation on a non-arithmetic type!");
1730 case Instruction::FRem:
1731 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1732 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1733 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1734 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1736 case Instruction::And:
1737 case Instruction::Or:
1738 case Instruction::Xor:
1739 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1740 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1741 "Tried to create a logical operation on a non-integral type!");
1743 case Instruction::Shl:
1744 case Instruction::LShr:
1745 case Instruction::AShr:
1746 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1747 assert(C1->getType()->isInteger() &&
1748 "Tried to create a shift operation on a non-integer type!");
1755 return getTy(C1->getType(), Opcode, C1, C2);
1758 Constant *ConstantExpr::getCompare(unsigned short pred,
1759 Constant *C1, Constant *C2) {
1760 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1761 return getCompareTy(pred, C1, C2);
1764 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1765 Constant *V1, Constant *V2) {
1766 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1767 assert(V1->getType() == V2->getType() && "Select value types must match!");
1768 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1770 if (ReqTy == V1->getType())
1771 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1772 return SC; // Fold common cases
1774 std::vector<Constant*> argVec(3, C);
1777 ExprMapKeyType Key(Instruction::Select, argVec);
1778 return ExprConstants->getOrCreate(ReqTy, Key);
1781 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1784 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
1785 "GEP indices invalid!");
1787 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1788 return FC; // Fold a few common cases...
1790 assert(isa<PointerType>(C->getType()) &&
1791 "Non-pointer type for constant GetElementPtr expression");
1792 // Look up the constant in the table first to ensure uniqueness
1793 std::vector<Constant*> ArgVec;
1794 ArgVec.reserve(NumIdx+1);
1795 ArgVec.push_back(C);
1796 for (unsigned i = 0; i != NumIdx; ++i)
1797 ArgVec.push_back(cast<Constant>(Idxs[i]));
1798 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1799 return ExprConstants->getOrCreate(ReqTy, Key);
1802 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1804 // Get the result type of the getelementptr!
1806 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
1807 assert(Ty && "GEP indices invalid!");
1808 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1811 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1813 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1818 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1819 assert(LHS->getType() == RHS->getType());
1820 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1821 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1823 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1824 return FC; // Fold a few common cases...
1826 // Look up the constant in the table first to ensure uniqueness
1827 std::vector<Constant*> ArgVec;
1828 ArgVec.push_back(LHS);
1829 ArgVec.push_back(RHS);
1830 // Get the key type with both the opcode and predicate
1831 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1832 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1836 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1837 assert(LHS->getType() == RHS->getType());
1838 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1840 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1841 return FC; // Fold a few common cases...
1843 // Look up the constant in the table first to ensure uniqueness
1844 std::vector<Constant*> ArgVec;
1845 ArgVec.push_back(LHS);
1846 ArgVec.push_back(RHS);
1847 // Get the key type with both the opcode and predicate
1848 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1849 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1852 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1854 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1855 return FC; // Fold a few common cases...
1856 // Look up the constant in the table first to ensure uniqueness
1857 std::vector<Constant*> ArgVec(1, Val);
1858 ArgVec.push_back(Idx);
1859 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1860 return ExprConstants->getOrCreate(ReqTy, Key);
1863 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1864 assert(isa<VectorType>(Val->getType()) &&
1865 "Tried to create extractelement operation on non-vector type!");
1866 assert(Idx->getType() == Type::Int32Ty &&
1867 "Extractelement index must be i32 type!");
1868 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1872 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1873 Constant *Elt, Constant *Idx) {
1874 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1875 return FC; // Fold a few common cases...
1876 // Look up the constant in the table first to ensure uniqueness
1877 std::vector<Constant*> ArgVec(1, Val);
1878 ArgVec.push_back(Elt);
1879 ArgVec.push_back(Idx);
1880 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1881 return ExprConstants->getOrCreate(ReqTy, Key);
1884 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1886 assert(isa<VectorType>(Val->getType()) &&
1887 "Tried to create insertelement operation on non-vector type!");
1888 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1889 && "Insertelement types must match!");
1890 assert(Idx->getType() == Type::Int32Ty &&
1891 "Insertelement index must be i32 type!");
1892 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1896 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1897 Constant *V2, Constant *Mask) {
1898 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1899 return FC; // Fold a few common cases...
1900 // Look up the constant in the table first to ensure uniqueness
1901 std::vector<Constant*> ArgVec(1, V1);
1902 ArgVec.push_back(V2);
1903 ArgVec.push_back(Mask);
1904 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1905 return ExprConstants->getOrCreate(ReqTy, Key);
1908 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1910 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1911 "Invalid shuffle vector constant expr operands!");
1912 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1915 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1916 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1917 if (PTy->getElementType()->isFloatingPoint()) {
1918 std::vector<Constant*> zeros(PTy->getNumElements(),
1919 ConstantFP::getNegativeZero(PTy->getElementType()));
1920 return ConstantVector::get(PTy, zeros);
1923 if (Ty->isFloatingPoint())
1924 return ConstantFP::getNegativeZero(Ty);
1926 return Constant::getNullValue(Ty);
1929 // destroyConstant - Remove the constant from the constant table...
1931 void ConstantExpr::destroyConstant() {
1932 ExprConstants->remove(this);
1933 destroyConstantImpl();
1936 const char *ConstantExpr::getOpcodeName() const {
1937 return Instruction::getOpcodeName(getOpcode());
1940 //===----------------------------------------------------------------------===//
1941 // replaceUsesOfWithOnConstant implementations
1943 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1944 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1947 /// Note that we intentionally replace all uses of From with To here. Consider
1948 /// a large array that uses 'From' 1000 times. By handling this case all here,
1949 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1950 /// single invocation handles all 1000 uses. Handling them one at a time would
1951 /// work, but would be really slow because it would have to unique each updated
1953 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1955 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1956 Constant *ToC = cast<Constant>(To);
1958 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1959 Lookup.first.first = getType();
1960 Lookup.second = this;
1962 std::vector<Constant*> &Values = Lookup.first.second;
1963 Values.reserve(getNumOperands()); // Build replacement array.
1965 // Fill values with the modified operands of the constant array. Also,
1966 // compute whether this turns into an all-zeros array.
1967 bool isAllZeros = false;
1968 unsigned NumUpdated = 0;
1969 if (!ToC->isNullValue()) {
1970 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1971 Constant *Val = cast<Constant>(O->get());
1976 Values.push_back(Val);
1980 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1981 Constant *Val = cast<Constant>(O->get());
1986 Values.push_back(Val);
1987 if (isAllZeros) isAllZeros = Val->isNullValue();
1991 Constant *Replacement = 0;
1993 Replacement = ConstantAggregateZero::get(getType());
1995 // Check to see if we have this array type already.
1997 ArrayConstantsTy::MapTy::iterator I =
1998 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2001 Replacement = I->second;
2003 // Okay, the new shape doesn't exist in the system yet. Instead of
2004 // creating a new constant array, inserting it, replaceallusesof'ing the
2005 // old with the new, then deleting the old... just update the current one
2007 ArrayConstants->MoveConstantToNewSlot(this, I);
2009 // Update to the new value. Optimize for the case when we have a single
2010 // operand that we're changing, but handle bulk updates efficiently.
2011 if (NumUpdated == 1) {
2012 unsigned OperandToUpdate = U-OperandList;
2013 assert(getOperand(OperandToUpdate) == From &&
2014 "ReplaceAllUsesWith broken!");
2015 setOperand(OperandToUpdate, ToC);
2017 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2018 if (getOperand(i) == From)
2025 // Otherwise, I do need to replace this with an existing value.
2026 assert(Replacement != this && "I didn't contain From!");
2028 // Everyone using this now uses the replacement.
2029 uncheckedReplaceAllUsesWith(Replacement);
2031 // Delete the old constant!
2035 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2037 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2038 Constant *ToC = cast<Constant>(To);
2040 unsigned OperandToUpdate = U-OperandList;
2041 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2043 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2044 Lookup.first.first = getType();
2045 Lookup.second = this;
2046 std::vector<Constant*> &Values = Lookup.first.second;
2047 Values.reserve(getNumOperands()); // Build replacement struct.
2050 // Fill values with the modified operands of the constant struct. Also,
2051 // compute whether this turns into an all-zeros struct.
2052 bool isAllZeros = false;
2053 if (!ToC->isNullValue()) {
2054 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2055 Values.push_back(cast<Constant>(O->get()));
2058 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2059 Constant *Val = cast<Constant>(O->get());
2060 Values.push_back(Val);
2061 if (isAllZeros) isAllZeros = Val->isNullValue();
2064 Values[OperandToUpdate] = ToC;
2066 Constant *Replacement = 0;
2068 Replacement = ConstantAggregateZero::get(getType());
2070 // Check to see if we have this array type already.
2072 StructConstantsTy::MapTy::iterator I =
2073 StructConstants->InsertOrGetItem(Lookup, Exists);
2076 Replacement = I->second;
2078 // Okay, the new shape doesn't exist in the system yet. Instead of
2079 // creating a new constant struct, inserting it, replaceallusesof'ing the
2080 // old with the new, then deleting the old... just update the current one
2082 StructConstants->MoveConstantToNewSlot(this, I);
2084 // Update to the new value.
2085 setOperand(OperandToUpdate, ToC);
2090 assert(Replacement != this && "I didn't contain From!");
2092 // Everyone using this now uses the replacement.
2093 uncheckedReplaceAllUsesWith(Replacement);
2095 // Delete the old constant!
2099 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2101 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2103 std::vector<Constant*> Values;
2104 Values.reserve(getNumOperands()); // Build replacement array...
2105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2106 Constant *Val = getOperand(i);
2107 if (Val == From) Val = cast<Constant>(To);
2108 Values.push_back(Val);
2111 Constant *Replacement = ConstantVector::get(getType(), Values);
2112 assert(Replacement != this && "I didn't contain From!");
2114 // Everyone using this now uses the replacement.
2115 uncheckedReplaceAllUsesWith(Replacement);
2117 // Delete the old constant!
2121 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2123 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2124 Constant *To = cast<Constant>(ToV);
2126 Constant *Replacement = 0;
2127 if (getOpcode() == Instruction::GetElementPtr) {
2128 SmallVector<Constant*, 8> Indices;
2129 Constant *Pointer = getOperand(0);
2130 Indices.reserve(getNumOperands()-1);
2131 if (Pointer == From) Pointer = To;
2133 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2134 Constant *Val = getOperand(i);
2135 if (Val == From) Val = To;
2136 Indices.push_back(Val);
2138 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2139 &Indices[0], Indices.size());
2140 } else if (isCast()) {
2141 assert(getOperand(0) == From && "Cast only has one use!");
2142 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2143 } else if (getOpcode() == Instruction::Select) {
2144 Constant *C1 = getOperand(0);
2145 Constant *C2 = getOperand(1);
2146 Constant *C3 = getOperand(2);
2147 if (C1 == From) C1 = To;
2148 if (C2 == From) C2 = To;
2149 if (C3 == From) C3 = To;
2150 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2151 } else if (getOpcode() == Instruction::ExtractElement) {
2152 Constant *C1 = getOperand(0);
2153 Constant *C2 = getOperand(1);
2154 if (C1 == From) C1 = To;
2155 if (C2 == From) C2 = To;
2156 Replacement = ConstantExpr::getExtractElement(C1, C2);
2157 } else if (getOpcode() == Instruction::InsertElement) {
2158 Constant *C1 = getOperand(0);
2159 Constant *C2 = getOperand(1);
2160 Constant *C3 = getOperand(1);
2161 if (C1 == From) C1 = To;
2162 if (C2 == From) C2 = To;
2163 if (C3 == From) C3 = To;
2164 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2165 } else if (getOpcode() == Instruction::ShuffleVector) {
2166 Constant *C1 = getOperand(0);
2167 Constant *C2 = getOperand(1);
2168 Constant *C3 = getOperand(2);
2169 if (C1 == From) C1 = To;
2170 if (C2 == From) C2 = To;
2171 if (C3 == From) C3 = To;
2172 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2173 } else if (isCompare()) {
2174 Constant *C1 = getOperand(0);
2175 Constant *C2 = getOperand(1);
2176 if (C1 == From) C1 = To;
2177 if (C2 == From) C2 = To;
2178 if (getOpcode() == Instruction::ICmp)
2179 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2181 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2182 } else if (getNumOperands() == 2) {
2183 Constant *C1 = getOperand(0);
2184 Constant *C2 = getOperand(1);
2185 if (C1 == From) C1 = To;
2186 if (C2 == From) C2 = To;
2187 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2189 assert(0 && "Unknown ConstantExpr type!");
2193 assert(Replacement != this && "I didn't contain From!");
2195 // Everyone using this now uses the replacement.
2196 uncheckedReplaceAllUsesWith(Replacement);
2198 // Delete the old constant!
2203 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2204 /// global into a string value. Return an empty string if we can't do it.
2205 /// Parameter Chop determines if the result is chopped at the first null
2208 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2209 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2210 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2211 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2212 if (Init->isString()) {
2213 std::string Result = Init->getAsString();
2214 if (Offset < Result.size()) {
2215 // If we are pointing INTO The string, erase the beginning...
2216 Result.erase(Result.begin(), Result.begin()+Offset);
2218 // Take off the null terminator, and any string fragments after it.
2220 std::string::size_type NullPos = Result.find_first_of((char)0);
2221 if (NullPos != std::string::npos)
2222 Result.erase(Result.begin()+NullPos, Result.end());
2228 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2229 if (CE->getOpcode() == Instruction::GetElementPtr) {
2230 // Turn a gep into the specified offset.
2231 if (CE->getNumOperands() == 3 &&
2232 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2233 isa<ConstantInt>(CE->getOperand(2))) {
2234 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2235 return CE->getOperand(0)->getStringValue(Chop, Offset);