1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45 void Constant::destroyConstantImpl() {
46 // When a Constant is destroyed, there may be lingering
47 // references to the constant by other constants in the constant pool. These
48 // constants are implicitly dependent on the module that is being deleted,
49 // but they don't know that. Because we only find out when the CPV is
50 // deleted, we must now notify all of our users (that should only be
51 // Constants) that they are, in fact, invalid now and should be deleted.
53 while (!use_empty()) {
54 Value *V = use_back();
55 #ifndef NDEBUG // Only in -g mode...
56 if (!isa<Constant>(V))
57 DOUT << "While deleting: " << *this
58 << "\n\nUse still stuck around after Def is destroyed: "
61 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62 Constant *CV = cast<Constant>(V);
63 CV->destroyConstant();
65 // The constant should remove itself from our use list...
66 assert((use_empty() || use_back() != V) && "Constant not removed!");
69 // Value has no outstanding references it is safe to delete it now...
73 /// canTrap - Return true if evaluation of this constant could trap. This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77 // The only thing that could possibly trap are constant exprs.
78 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79 if (!CE) return false;
81 // ConstantExpr traps if any operands can trap.
82 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83 if (getOperand(i)->canTrap())
86 // Otherwise, only specific operations can trap.
87 switch (CE->getOpcode()) {
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 // Div and rem can trap if the RHS is not known to be non-zero.
97 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108 bool isLocal = GV->hasLocalLinkage();
109 if ((Kind & Reloc::Local) && isLocal) {
110 // Global has local linkage and 'local' kind of relocations are
115 if ((Kind & Reloc::Global) && !isLocal) {
116 // Global has non-local linkage and 'global' kind of relocations are
124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125 if (getOperand(i)->ContainsRelocations(Kind))
131 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc. For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136 SmallVectorImpl<Constant*> &Elts) const {
137 assert(isa<VectorType>(getType()) && "Not a vector constant!");
139 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141 Elts.push_back(CV->getOperand(i));
145 const VectorType *VT = cast<VectorType>(getType());
146 if (isa<ConstantAggregateZero>(this)) {
147 Elts.assign(VT->getNumElements(),
148 Context.getNullValue(VT->getElementType()));
152 if (isa<UndefValue>(this)) {
153 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
157 // Unknown type, must be constant expr etc.
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
175 void CleanupTrueFalse(void *) {
176 ConstantInt::ResetTrueFalse();
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183 assert(TheTrueVal == 0 && TheFalseVal == 0);
184 TheTrueVal = getGlobalContext().getConstantInt(Type::Int1Ty, 1);
185 TheFalseVal = getGlobalContext().getConstantInt(Type::Int1Ty, 0);
187 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188 TrueFalseCleanup.Register();
190 return WhichOne ? TheTrueVal : TheFalseVal;
193 //===----------------------------------------------------------------------===//
195 //===----------------------------------------------------------------------===//
197 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
198 if (Ty == Type::FloatTy)
199 return &APFloat::IEEEsingle;
200 if (Ty == Type::DoubleTy)
201 return &APFloat::IEEEdouble;
202 if (Ty == Type::X86_FP80Ty)
203 return &APFloat::x87DoubleExtended;
204 else if (Ty == Type::FP128Ty)
205 return &APFloat::IEEEquad;
207 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
208 return &APFloat::PPCDoubleDouble;
211 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
212 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
213 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
217 bool ConstantFP::isNullValue() const {
218 return Val.isZero() && !Val.isNegative();
221 bool ConstantFP::isExactlyValue(const APFloat& V) const {
222 return Val.bitwiseIsEqual(V);
226 struct DenseMapAPFloatKeyInfo {
229 KeyTy(const APFloat& V) : val(V){}
230 KeyTy(const KeyTy& that) : val(that.val) {}
231 bool operator==(const KeyTy& that) const {
232 return this->val.bitwiseIsEqual(that.val);
234 bool operator!=(const KeyTy& that) const {
235 return !this->operator==(that);
238 static inline KeyTy getEmptyKey() {
239 return KeyTy(APFloat(APFloat::Bogus,1));
241 static inline KeyTy getTombstoneKey() {
242 return KeyTy(APFloat(APFloat::Bogus,2));
244 static unsigned getHashValue(const KeyTy &Key) {
245 return Key.val.getHashValue();
247 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
250 static bool isPod() { return false; }
254 //---- ConstantFP::get() implementation...
256 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
257 DenseMapAPFloatKeyInfo> FPMapTy;
259 static ManagedStatic<FPMapTy> FPConstants;
261 ConstantFP *ConstantFP::get(const APFloat &V) {
262 DenseMapAPFloatKeyInfo::KeyTy Key(V);
264 ConstantsLock->reader_acquire();
265 ConstantFP *&Slot = (*FPConstants)[Key];
266 ConstantsLock->reader_release();
269 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
270 ConstantFP *&NewSlot = (*FPConstants)[Key];
273 if (&V.getSemantics() == &APFloat::IEEEsingle)
275 else if (&V.getSemantics() == &APFloat::IEEEdouble)
277 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
278 Ty = Type::X86_FP80Ty;
279 else if (&V.getSemantics() == &APFloat::IEEEquad)
282 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
283 "Unknown FP format");
284 Ty = Type::PPC_FP128Ty;
286 NewSlot = new ConstantFP(Ty, V);
295 //===----------------------------------------------------------------------===//
296 // ConstantXXX Classes
297 //===----------------------------------------------------------------------===//
300 ConstantArray::ConstantArray(const ArrayType *T,
301 const std::vector<Constant*> &V)
302 : Constant(T, ConstantArrayVal,
303 OperandTraits<ConstantArray>::op_end(this) - V.size(),
305 assert(V.size() == T->getNumElements() &&
306 "Invalid initializer vector for constant array");
307 Use *OL = OperandList;
308 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
311 assert((C->getType() == T->getElementType() ||
313 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
314 "Initializer for array element doesn't match array element type!");
320 ConstantStruct::ConstantStruct(const StructType *T,
321 const std::vector<Constant*> &V)
322 : Constant(T, ConstantStructVal,
323 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
325 assert(V.size() == T->getNumElements() &&
326 "Invalid initializer vector for constant structure");
327 Use *OL = OperandList;
328 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
331 assert((C->getType() == T->getElementType(I-V.begin()) ||
332 ((T->getElementType(I-V.begin())->isAbstract() ||
333 C->getType()->isAbstract()) &&
334 T->getElementType(I-V.begin())->getTypeID() ==
335 C->getType()->getTypeID())) &&
336 "Initializer for struct element doesn't match struct element type!");
342 ConstantVector::ConstantVector(const VectorType *T,
343 const std::vector<Constant*> &V)
344 : Constant(T, ConstantVectorVal,
345 OperandTraits<ConstantVector>::op_end(this) - V.size(),
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 vector element doesn't match vector element type!");
361 // We declare several classes private to this file, so use an anonymous
365 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
366 /// behind the scenes to implement unary constant exprs.
367 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
368 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
370 // allocate space for exactly one operand
371 void *operator new(size_t s) {
372 return User::operator new(s, 1);
374 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
375 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
378 /// Transparently provide more efficient getOperand methods.
379 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
382 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
383 /// behind the scenes to implement binary constant exprs.
384 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
385 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
387 // allocate space for exactly two operands
388 void *operator new(size_t s) {
389 return User::operator new(s, 2);
391 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
392 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
396 /// Transparently provide more efficient getOperand methods.
397 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
400 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
401 /// behind the scenes to implement select constant exprs.
402 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
403 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
405 // allocate space for exactly three operands
406 void *operator new(size_t s) {
407 return User::operator new(s, 3);
409 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
410 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
415 /// Transparently provide more efficient getOperand methods.
416 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
419 /// ExtractElementConstantExpr - This class is private to
420 /// Constants.cpp, and is used behind the scenes to implement
421 /// extractelement constant exprs.
422 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
425 // allocate space for exactly two operands
426 void *operator new(size_t s) {
427 return User::operator new(s, 2);
429 ExtractElementConstantExpr(Constant *C1, Constant *C2)
430 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
431 Instruction::ExtractElement, &Op<0>(), 2) {
435 /// Transparently provide more efficient getOperand methods.
436 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
439 /// InsertElementConstantExpr - This class is private to
440 /// Constants.cpp, and is used behind the scenes to implement
441 /// insertelement constant exprs.
442 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
443 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
445 // allocate space for exactly three operands
446 void *operator new(size_t s) {
447 return User::operator new(s, 3);
449 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
450 : ConstantExpr(C1->getType(), Instruction::InsertElement,
456 /// Transparently provide more efficient getOperand methods.
457 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
460 /// ShuffleVectorConstantExpr - This class is private to
461 /// Constants.cpp, and is used behind the scenes to implement
462 /// shufflevector constant exprs.
463 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
464 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
466 // allocate space for exactly three operands
467 void *operator new(size_t s) {
468 return User::operator new(s, 3);
470 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
471 : ConstantExpr(VectorType::get(
472 cast<VectorType>(C1->getType())->getElementType(),
473 cast<VectorType>(C3->getType())->getNumElements()),
474 Instruction::ShuffleVector,
480 /// Transparently provide more efficient getOperand methods.
481 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
484 /// ExtractValueConstantExpr - This class is private to
485 /// Constants.cpp, and is used behind the scenes to implement
486 /// extractvalue constant exprs.
487 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
488 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
490 // allocate space for exactly one operand
491 void *operator new(size_t s) {
492 return User::operator new(s, 1);
494 ExtractValueConstantExpr(Constant *Agg,
495 const SmallVector<unsigned, 4> &IdxList,
497 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
502 /// Indices - These identify which value to extract.
503 const SmallVector<unsigned, 4> Indices;
505 /// Transparently provide more efficient getOperand methods.
506 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
509 /// InsertValueConstantExpr - This class is private to
510 /// Constants.cpp, and is used behind the scenes to implement
511 /// insertvalue constant exprs.
512 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
513 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
515 // allocate space for exactly one operand
516 void *operator new(size_t s) {
517 return User::operator new(s, 2);
519 InsertValueConstantExpr(Constant *Agg, Constant *Val,
520 const SmallVector<unsigned, 4> &IdxList,
522 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
528 /// Indices - These identify the position for the insertion.
529 const SmallVector<unsigned, 4> Indices;
531 /// Transparently provide more efficient getOperand methods.
532 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
536 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
537 /// used behind the scenes to implement getelementpr constant exprs.
538 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
539 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
542 static GetElementPtrConstantExpr *Create(Constant *C,
543 const std::vector<Constant*>&IdxList,
544 const Type *DestTy) {
545 return new(IdxList.size() + 1)
546 GetElementPtrConstantExpr(C, IdxList, DestTy);
548 /// Transparently provide more efficient getOperand methods.
549 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
552 // CompareConstantExpr - This class is private to Constants.cpp, and is used
553 // behind the scenes to implement ICmp and FCmp constant expressions. This is
554 // needed in order to store the predicate value for these instructions.
555 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
556 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
557 // allocate space for exactly two operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 2);
561 unsigned short predicate;
562 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
563 unsigned short pred, Constant* LHS, Constant* RHS)
564 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
568 /// Transparently provide more efficient getOperand methods.
569 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
572 } // end anonymous namespace
575 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
577 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
580 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
582 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
585 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
587 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
590 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
592 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
595 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
597 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
600 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
602 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
605 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
607 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
610 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
612 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
615 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
618 GetElementPtrConstantExpr::GetElementPtrConstantExpr
620 const std::vector<Constant*> &IdxList,
622 : ConstantExpr(DestTy, Instruction::GetElementPtr,
623 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
624 - (IdxList.size()+1),
627 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
628 OperandList[i+1] = IdxList[i];
631 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
635 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
637 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
640 } // End llvm namespace
643 // Utility function for determining if a ConstantExpr is a CastOp or not. This
644 // can't be inline because we don't want to #include Instruction.h into
646 bool ConstantExpr::isCast() const {
647 return Instruction::isCast(getOpcode());
650 bool ConstantExpr::isCompare() const {
651 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
654 bool ConstantExpr::hasIndices() const {
655 return getOpcode() == Instruction::ExtractValue ||
656 getOpcode() == Instruction::InsertValue;
659 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
660 if (const ExtractValueConstantExpr *EVCE =
661 dyn_cast<ExtractValueConstantExpr>(this))
662 return EVCE->Indices;
664 return cast<InsertValueConstantExpr>(this)->Indices;
667 unsigned ConstantExpr::getPredicate() const {
668 assert(getOpcode() == Instruction::FCmp ||
669 getOpcode() == Instruction::ICmp);
670 return ((const CompareConstantExpr*)this)->predicate;
673 /// getWithOperandReplaced - Return a constant expression identical to this
674 /// one, but with the specified operand set to the specified value.
676 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
677 assert(OpNo < getNumOperands() && "Operand num is out of range!");
678 assert(Op->getType() == getOperand(OpNo)->getType() &&
679 "Replacing operand with value of different type!");
680 if (getOperand(OpNo) == Op)
681 return const_cast<ConstantExpr*>(this);
683 Constant *Op0, *Op1, *Op2;
684 switch (getOpcode()) {
685 case Instruction::Trunc:
686 case Instruction::ZExt:
687 case Instruction::SExt:
688 case Instruction::FPTrunc:
689 case Instruction::FPExt:
690 case Instruction::UIToFP:
691 case Instruction::SIToFP:
692 case Instruction::FPToUI:
693 case Instruction::FPToSI:
694 case Instruction::PtrToInt:
695 case Instruction::IntToPtr:
696 case Instruction::BitCast:
697 return ConstantExpr::getCast(getOpcode(), Op, getType());
698 case Instruction::Select:
699 Op0 = (OpNo == 0) ? Op : getOperand(0);
700 Op1 = (OpNo == 1) ? Op : getOperand(1);
701 Op2 = (OpNo == 2) ? Op : getOperand(2);
702 return ConstantExpr::getSelect(Op0, Op1, Op2);
703 case Instruction::InsertElement:
704 Op0 = (OpNo == 0) ? Op : getOperand(0);
705 Op1 = (OpNo == 1) ? Op : getOperand(1);
706 Op2 = (OpNo == 2) ? Op : getOperand(2);
707 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
708 case Instruction::ExtractElement:
709 Op0 = (OpNo == 0) ? Op : getOperand(0);
710 Op1 = (OpNo == 1) ? Op : getOperand(1);
711 return ConstantExpr::getExtractElement(Op0, Op1);
712 case Instruction::ShuffleVector:
713 Op0 = (OpNo == 0) ? Op : getOperand(0);
714 Op1 = (OpNo == 1) ? Op : getOperand(1);
715 Op2 = (OpNo == 2) ? Op : getOperand(2);
716 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
717 case Instruction::GetElementPtr: {
718 SmallVector<Constant*, 8> Ops;
719 Ops.resize(getNumOperands()-1);
720 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
721 Ops[i-1] = getOperand(i);
723 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
725 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
728 assert(getNumOperands() == 2 && "Must be binary operator?");
729 Op0 = (OpNo == 0) ? Op : getOperand(0);
730 Op1 = (OpNo == 1) ? Op : getOperand(1);
731 return ConstantExpr::get(getOpcode(), Op0, Op1);
735 /// getWithOperands - This returns the current constant expression with the
736 /// operands replaced with the specified values. The specified operands must
737 /// match count and type with the existing ones.
738 Constant *ConstantExpr::
739 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
740 assert(NumOps == getNumOperands() && "Operand count mismatch!");
741 bool AnyChange = false;
742 for (unsigned i = 0; i != NumOps; ++i) {
743 assert(Ops[i]->getType() == getOperand(i)->getType() &&
744 "Operand type mismatch!");
745 AnyChange |= Ops[i] != getOperand(i);
747 if (!AnyChange) // No operands changed, return self.
748 return const_cast<ConstantExpr*>(this);
750 switch (getOpcode()) {
751 case Instruction::Trunc:
752 case Instruction::ZExt:
753 case Instruction::SExt:
754 case Instruction::FPTrunc:
755 case Instruction::FPExt:
756 case Instruction::UIToFP:
757 case Instruction::SIToFP:
758 case Instruction::FPToUI:
759 case Instruction::FPToSI:
760 case Instruction::PtrToInt:
761 case Instruction::IntToPtr:
762 case Instruction::BitCast:
763 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
764 case Instruction::Select:
765 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
766 case Instruction::InsertElement:
767 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
768 case Instruction::ExtractElement:
769 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
770 case Instruction::ShuffleVector:
771 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
772 case Instruction::GetElementPtr:
773 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
774 case Instruction::ICmp:
775 case Instruction::FCmp:
776 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
778 assert(getNumOperands() == 2 && "Must be binary operator?");
779 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
784 //===----------------------------------------------------------------------===//
785 // isValueValidForType implementations
787 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
788 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
789 if (Ty == Type::Int1Ty)
790 return Val == 0 || Val == 1;
792 return true; // always true, has to fit in largest type
793 uint64_t Max = (1ll << NumBits) - 1;
797 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
798 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
799 if (Ty == Type::Int1Ty)
800 return Val == 0 || Val == 1 || Val == -1;
802 return true; // always true, has to fit in largest type
803 int64_t Min = -(1ll << (NumBits-1));
804 int64_t Max = (1ll << (NumBits-1)) - 1;
805 return (Val >= Min && Val <= Max);
808 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
809 // convert modifies in place, so make a copy.
810 APFloat Val2 = APFloat(Val);
812 switch (Ty->getTypeID()) {
814 return false; // These can't be represented as floating point!
816 // FIXME rounding mode needs to be more flexible
817 case Type::FloatTyID: {
818 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
820 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
823 case Type::DoubleTyID: {
824 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
825 &Val2.getSemantics() == &APFloat::IEEEdouble)
827 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
830 case Type::X86_FP80TyID:
831 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
832 &Val2.getSemantics() == &APFloat::IEEEdouble ||
833 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
834 case Type::FP128TyID:
835 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
836 &Val2.getSemantics() == &APFloat::IEEEdouble ||
837 &Val2.getSemantics() == &APFloat::IEEEquad;
838 case Type::PPC_FP128TyID:
839 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
840 &Val2.getSemantics() == &APFloat::IEEEdouble ||
841 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
845 //===----------------------------------------------------------------------===//
846 // Factory Function Implementation
849 // The number of operands for each ConstantCreator::create method is
850 // determined by the ConstantTraits template.
851 // ConstantCreator - A class that is used to create constants by
852 // ValueMap*. This class should be partially specialized if there is
853 // something strange that needs to be done to interface to the ctor for the
857 template<class ValType>
858 struct ConstantTraits;
860 template<typename T, typename Alloc>
861 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
862 static unsigned uses(const std::vector<T, Alloc>& v) {
867 template<class ConstantClass, class TypeClass, class ValType>
868 struct VISIBILITY_HIDDEN ConstantCreator {
869 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
870 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
874 template<class ConstantClass, class TypeClass>
875 struct VISIBILITY_HIDDEN ConvertConstantType {
876 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
877 llvm_unreachable("This type cannot be converted!");
881 template<class ValType, class TypeClass, class ConstantClass,
882 bool HasLargeKey = false /*true for arrays and structs*/ >
883 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
885 typedef std::pair<const Type*, ValType> MapKey;
886 typedef std::map<MapKey, Constant *> MapTy;
887 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
888 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
890 /// Map - This is the main map from the element descriptor to the Constants.
891 /// This is the primary way we avoid creating two of the same shape
895 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
896 /// from the constants to their element in Map. This is important for
897 /// removal of constants from the array, which would otherwise have to scan
898 /// through the map with very large keys.
899 InverseMapTy InverseMap;
901 /// AbstractTypeMap - Map for abstract type constants.
903 AbstractTypeMapTy AbstractTypeMap;
905 /// ValueMapLock - Mutex for this map.
906 sys::SmartMutex<true> ValueMapLock;
909 // NOTE: This function is not locked. It is the caller's responsibility
910 // to enforce proper synchronization.
911 typename MapTy::iterator map_end() { return Map.end(); }
913 /// InsertOrGetItem - Return an iterator for the specified element.
914 /// If the element exists in the map, the returned iterator points to the
915 /// entry and Exists=true. If not, the iterator points to the newly
916 /// inserted entry and returns Exists=false. Newly inserted entries have
917 /// I->second == 0, and should be filled in.
918 /// NOTE: This function is not locked. It is the caller's responsibility
919 // to enforce proper synchronization.
920 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
923 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
929 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
931 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
932 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
933 IMI->second->second == CP &&
934 "InverseMap corrupt!");
938 typename MapTy::iterator I =
939 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
941 if (I == Map.end() || I->second != CP) {
942 // FIXME: This should not use a linear scan. If this gets to be a
943 // performance problem, someone should look at this.
944 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
950 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
951 typename MapTy::iterator I) {
952 ConstantClass* Result =
953 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
955 assert(Result->getType() == Ty && "Type specified is not correct!");
956 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
958 if (HasLargeKey) // Remember the reverse mapping if needed.
959 InverseMap.insert(std::make_pair(Result, I));
961 // If the type of the constant is abstract, make sure that an entry
962 // exists for it in the AbstractTypeMap.
963 if (Ty->isAbstract()) {
964 typename AbstractTypeMapTy::iterator TI =
965 AbstractTypeMap.find(Ty);
967 if (TI == AbstractTypeMap.end()) {
968 // Add ourselves to the ATU list of the type.
969 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
971 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
979 /// getOrCreate - Return the specified constant from the map, creating it if
981 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
982 sys::SmartScopedLock<true> Lock(ValueMapLock);
983 MapKey Lookup(Ty, V);
984 ConstantClass* Result = 0;
986 typename MapTy::iterator I = Map.find(Lookup);
989 Result = static_cast<ConstantClass *>(I->second);
992 // If no preexisting value, create one now...
993 Result = Create(Ty, V, I);
999 void remove(ConstantClass *CP) {
1000 sys::SmartScopedLock<true> Lock(ValueMapLock);
1001 typename MapTy::iterator I = FindExistingElement(CP);
1002 assert(I != Map.end() && "Constant not found in constant table!");
1003 assert(I->second == CP && "Didn't find correct element?");
1005 if (HasLargeKey) // Remember the reverse mapping if needed.
1006 InverseMap.erase(CP);
1008 // Now that we found the entry, make sure this isn't the entry that
1009 // the AbstractTypeMap points to.
1010 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1011 if (Ty->isAbstract()) {
1012 assert(AbstractTypeMap.count(Ty) &&
1013 "Abstract type not in AbstractTypeMap?");
1014 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1015 if (ATMEntryIt == I) {
1016 // Yes, we are removing the representative entry for this type.
1017 // See if there are any other entries of the same type.
1018 typename MapTy::iterator TmpIt = ATMEntryIt;
1020 // First check the entry before this one...
1021 if (TmpIt != Map.begin()) {
1023 if (TmpIt->first.first != Ty) // Not the same type, move back...
1027 // If we didn't find the same type, try to move forward...
1028 if (TmpIt == ATMEntryIt) {
1030 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1031 --TmpIt; // No entry afterwards with the same type
1034 // If there is another entry in the map of the same abstract type,
1035 // update the AbstractTypeMap entry now.
1036 if (TmpIt != ATMEntryIt) {
1039 // Otherwise, we are removing the last instance of this type
1040 // from the table. Remove from the ATM, and from user list.
1041 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1042 AbstractTypeMap.erase(Ty);
1051 /// MoveConstantToNewSlot - If we are about to change C to be the element
1052 /// specified by I, update our internal data structures to reflect this
1054 /// NOTE: This function is not locked. It is the responsibility of the
1055 /// caller to enforce proper synchronization if using this method.
1056 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1057 // First, remove the old location of the specified constant in the map.
1058 typename MapTy::iterator OldI = FindExistingElement(C);
1059 assert(OldI != Map.end() && "Constant not found in constant table!");
1060 assert(OldI->second == C && "Didn't find correct element?");
1062 // If this constant is the representative element for its abstract type,
1063 // update the AbstractTypeMap so that the representative element is I.
1064 if (C->getType()->isAbstract()) {
1065 typename AbstractTypeMapTy::iterator ATI =
1066 AbstractTypeMap.find(C->getType());
1067 assert(ATI != AbstractTypeMap.end() &&
1068 "Abstract type not in AbstractTypeMap?");
1069 if (ATI->second == OldI)
1073 // Remove the old entry from the map.
1076 // Update the inverse map so that we know that this constant is now
1077 // located at descriptor I.
1079 assert(I->second == C && "Bad inversemap entry!");
1084 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1085 sys::SmartScopedLock<true> Lock(ValueMapLock);
1086 typename AbstractTypeMapTy::iterator I =
1087 AbstractTypeMap.find(cast<Type>(OldTy));
1089 assert(I != AbstractTypeMap.end() &&
1090 "Abstract type not in AbstractTypeMap?");
1092 // Convert a constant at a time until the last one is gone. The last one
1093 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1094 // eliminated eventually.
1096 ConvertConstantType<ConstantClass,
1097 TypeClass>::convert(
1098 static_cast<ConstantClass *>(I->second->second),
1099 cast<TypeClass>(NewTy));
1101 I = AbstractTypeMap.find(cast<Type>(OldTy));
1102 } while (I != AbstractTypeMap.end());
1105 // If the type became concrete without being refined to any other existing
1106 // type, we just remove ourselves from the ATU list.
1107 void typeBecameConcrete(const DerivedType *AbsTy) {
1108 AbsTy->removeAbstractTypeUser(this);
1112 DOUT << "Constant.cpp: ValueMap\n";
1119 //---- ConstantAggregateZero::get() implementation...
1122 // ConstantAggregateZero does not take extra "value" argument...
1123 template<class ValType>
1124 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1125 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1126 return new ConstantAggregateZero(Ty);
1131 struct ConvertConstantType<ConstantAggregateZero, Type> {
1132 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1133 // Make everyone now use a constant of the new type...
1134 Constant *New = ConstantAggregateZero::get(NewTy);
1135 assert(New != OldC && "Didn't replace constant??");
1136 OldC->uncheckedReplaceAllUsesWith(New);
1137 OldC->destroyConstant(); // This constant is now dead, destroy it.
1142 static ManagedStatic<ValueMap<char, Type,
1143 ConstantAggregateZero> > AggZeroConstants;
1145 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1147 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1148 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1149 "Cannot create an aggregate zero of non-aggregate type!");
1151 // Implicitly locked.
1152 return AggZeroConstants->getOrCreate(Ty, 0);
1155 /// destroyConstant - Remove the constant from the constant table...
1157 void ConstantAggregateZero::destroyConstant() {
1158 // Implicitly locked.
1159 AggZeroConstants->remove(this);
1160 destroyConstantImpl();
1163 //---- ConstantArray::get() implementation...
1167 struct ConvertConstantType<ConstantArray, ArrayType> {
1168 static void convert(ConstantArray *OldC, const ArrayType *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 = ConstantArray::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(ConstantArray *CA) {
1182 std::vector<Constant*> Elements;
1183 Elements.reserve(CA->getNumOperands());
1184 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1185 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1189 typedef ValueMap<std::vector<Constant*>, ArrayType,
1190 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1191 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1193 Constant *ConstantArray::get(const ArrayType *Ty,
1194 const std::vector<Constant*> &V) {
1195 // If this is an all-zero array, return a ConstantAggregateZero object
1198 if (!C->isNullValue()) {
1199 // Implicitly locked.
1200 return ArrayConstants->getOrCreate(Ty, V);
1202 for (unsigned i = 1, e = V.size(); i != e; ++i)
1204 // Implicitly locked.
1205 return ArrayConstants->getOrCreate(Ty, V);
1209 return ConstantAggregateZero::get(Ty);
1212 /// destroyConstant - Remove the constant from the constant table...
1214 void ConstantArray::destroyConstant() {
1215 // Implicitly locked.
1216 ArrayConstants->remove(this);
1217 destroyConstantImpl();
1220 /// isString - This method returns true if the array is an array of i8, and
1221 /// if the elements of the array are all ConstantInt's.
1222 bool ConstantArray::isString() const {
1223 // Check the element type for i8...
1224 if (getType()->getElementType() != Type::Int8Ty)
1226 // Check the elements to make sure they are all integers, not constant
1228 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1229 if (!isa<ConstantInt>(getOperand(i)))
1234 /// isCString - This method returns true if the array is a string (see
1235 /// isString) and it ends in a null byte \\0 and does not contains any other
1236 /// null bytes except its terminator.
1237 bool ConstantArray::isCString() const {
1238 // Check the element type for i8...
1239 if (getType()->getElementType() != Type::Int8Ty)
1242 // Last element must be a null.
1243 if (!getOperand(getNumOperands()-1)->isNullValue())
1245 // Other elements must be non-null integers.
1246 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1247 if (!isa<ConstantInt>(getOperand(i)))
1249 if (getOperand(i)->isNullValue())
1256 /// getAsString - If the sub-element type of this array is i8
1257 /// then this method converts the array to an std::string and returns it.
1258 /// Otherwise, it asserts out.
1260 std::string ConstantArray::getAsString() const {
1261 assert(isString() && "Not a string!");
1263 Result.reserve(getNumOperands());
1264 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1265 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1270 //---- ConstantStruct::get() implementation...
1275 struct ConvertConstantType<ConstantStruct, StructType> {
1276 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1277 // Make everyone now use a constant of the new type...
1278 std::vector<Constant*> C;
1279 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1280 C.push_back(cast<Constant>(OldC->getOperand(i)));
1281 Constant *New = ConstantStruct::get(NewTy, C);
1282 assert(New != OldC && "Didn't replace constant??");
1284 OldC->uncheckedReplaceAllUsesWith(New);
1285 OldC->destroyConstant(); // This constant is now dead, destroy it.
1290 typedef ValueMap<std::vector<Constant*>, StructType,
1291 ConstantStruct, true /*largekey*/> StructConstantsTy;
1292 static ManagedStatic<StructConstantsTy> StructConstants;
1294 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1295 std::vector<Constant*> Elements;
1296 Elements.reserve(CS->getNumOperands());
1297 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1298 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1302 Constant *ConstantStruct::get(const StructType *Ty,
1303 const std::vector<Constant*> &V) {
1304 // Create a ConstantAggregateZero value if all elements are zeros...
1305 for (unsigned i = 0, e = V.size(); i != e; ++i)
1306 if (!V[i]->isNullValue())
1307 // Implicitly locked.
1308 return StructConstants->getOrCreate(Ty, V);
1310 return ConstantAggregateZero::get(Ty);
1313 // destroyConstant - Remove the constant from the constant table...
1315 void ConstantStruct::destroyConstant() {
1316 // Implicitly locked.
1317 StructConstants->remove(this);
1318 destroyConstantImpl();
1321 //---- ConstantVector::get() implementation...
1325 struct ConvertConstantType<ConstantVector, VectorType> {
1326 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1327 // Make everyone now use a constant of the new type...
1328 std::vector<Constant*> C;
1329 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1330 C.push_back(cast<Constant>(OldC->getOperand(i)));
1331 Constant *New = ConstantVector::get(NewTy, C);
1332 assert(New != OldC && "Didn't replace constant??");
1333 OldC->uncheckedReplaceAllUsesWith(New);
1334 OldC->destroyConstant(); // This constant is now dead, destroy it.
1339 static std::vector<Constant*> getValType(ConstantVector *CP) {
1340 std::vector<Constant*> Elements;
1341 Elements.reserve(CP->getNumOperands());
1342 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1343 Elements.push_back(CP->getOperand(i));
1347 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1348 ConstantVector> > VectorConstants;
1350 Constant *ConstantVector::get(const VectorType *Ty,
1351 const std::vector<Constant*> &V) {
1352 assert(!V.empty() && "Vectors can't be empty");
1353 // If this is an all-undef or alll-zero vector, return a
1354 // ConstantAggregateZero or UndefValue.
1356 bool isZero = C->isNullValue();
1357 bool isUndef = isa<UndefValue>(C);
1359 if (isZero || isUndef) {
1360 for (unsigned i = 1, e = V.size(); i != e; ++i)
1362 isZero = isUndef = false;
1368 return ConstantAggregateZero::get(Ty);
1370 return UndefValue::get(Ty);
1372 // Implicitly locked.
1373 return VectorConstants->getOrCreate(Ty, V);
1376 // destroyConstant - Remove the constant from the constant table...
1378 void ConstantVector::destroyConstant() {
1379 // Implicitly locked.
1380 VectorConstants->remove(this);
1381 destroyConstantImpl();
1384 /// This function will return true iff every element in this vector constant
1385 /// is set to all ones.
1386 /// @returns true iff this constant's emements are all set to all ones.
1387 /// @brief Determine if the value is all ones.
1388 bool ConstantVector::isAllOnesValue() const {
1389 // Check out first element.
1390 const Constant *Elt = getOperand(0);
1391 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1392 if (!CI || !CI->isAllOnesValue()) return false;
1393 // Then make sure all remaining elements point to the same value.
1394 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1395 if (getOperand(I) != Elt) return false;
1400 /// getSplatValue - If this is a splat constant, where all of the
1401 /// elements have the same value, return that value. Otherwise return null.
1402 Constant *ConstantVector::getSplatValue() {
1403 // Check out first element.
1404 Constant *Elt = getOperand(0);
1405 // Then make sure all remaining elements point to the same value.
1406 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1407 if (getOperand(I) != Elt) return 0;
1411 //---- ConstantPointerNull::get() implementation...
1415 // ConstantPointerNull does not take extra "value" argument...
1416 template<class ValType>
1417 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1418 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1419 return new ConstantPointerNull(Ty);
1424 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1425 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1426 // Make everyone now use a constant of the new type...
1427 Constant *New = ConstantPointerNull::get(NewTy);
1428 assert(New != OldC && "Didn't replace constant??");
1429 OldC->uncheckedReplaceAllUsesWith(New);
1430 OldC->destroyConstant(); // This constant is now dead, destroy it.
1435 static ManagedStatic<ValueMap<char, PointerType,
1436 ConstantPointerNull> > NullPtrConstants;
1438 static char getValType(ConstantPointerNull *) {
1443 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1444 // Implicitly locked.
1445 return NullPtrConstants->getOrCreate(Ty, 0);
1448 // destroyConstant - Remove the constant from the constant table...
1450 void ConstantPointerNull::destroyConstant() {
1451 // Implicitly locked.
1452 NullPtrConstants->remove(this);
1453 destroyConstantImpl();
1457 //---- UndefValue::get() implementation...
1461 // UndefValue does not take extra "value" argument...
1462 template<class ValType>
1463 struct ConstantCreator<UndefValue, Type, ValType> {
1464 static UndefValue *create(const Type *Ty, const ValType &V) {
1465 return new UndefValue(Ty);
1470 struct ConvertConstantType<UndefValue, Type> {
1471 static void convert(UndefValue *OldC, const Type *NewTy) {
1472 // Make everyone now use a constant of the new type.
1473 Constant *New = UndefValue::get(NewTy);
1474 assert(New != OldC && "Didn't replace constant??");
1475 OldC->uncheckedReplaceAllUsesWith(New);
1476 OldC->destroyConstant(); // This constant is now dead, destroy it.
1481 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1483 static char getValType(UndefValue *) {
1488 UndefValue *UndefValue::get(const Type *Ty) {
1489 // Implicitly locked.
1490 return UndefValueConstants->getOrCreate(Ty, 0);
1493 // destroyConstant - Remove the constant from the constant table.
1495 void UndefValue::destroyConstant() {
1496 // Implicitly locked.
1497 UndefValueConstants->remove(this);
1498 destroyConstantImpl();
1501 //---- MDString::get() implementation
1504 MDString::MDString(const char *begin, const char *end)
1505 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1506 StrBegin(begin), StrEnd(end) {}
1508 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1510 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1511 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1512 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1514 MDString *&S = Entry.getValue();
1515 if (!S) S = new MDString(Entry.getKeyData(),
1516 Entry.getKeyData() + Entry.getKeyLength());
1521 MDString *MDString::get(const std::string &Str) {
1522 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1523 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1524 Str.data(), Str.data() + Str.size());
1525 MDString *&S = Entry.getValue();
1526 if (!S) S = new MDString(Entry.getKeyData(),
1527 Entry.getKeyData() + Entry.getKeyLength());
1532 void MDString::destroyConstant() {
1533 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1534 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1535 destroyConstantImpl();
1538 //---- MDNode::get() implementation
1541 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1543 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1544 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1545 for (unsigned i = 0; i != NumVals; ++i)
1546 Node.push_back(ElementVH(Vals[i], this));
1549 void MDNode::Profile(FoldingSetNodeID &ID) const {
1550 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1554 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1555 FoldingSetNodeID ID;
1556 for (unsigned i = 0; i != NumVals; ++i)
1557 ID.AddPointer(Vals[i]);
1559 ConstantsLock->reader_acquire();
1561 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1562 ConstantsLock->reader_release();
1565 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1566 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1568 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1569 N = new(0) MDNode(Vals, NumVals);
1570 MDNodeSet->InsertNode(N, InsertPoint);
1576 void MDNode::destroyConstant() {
1577 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1578 MDNodeSet->RemoveNode(this);
1580 destroyConstantImpl();
1583 //---- ConstantExpr::get() implementations...
1588 struct ExprMapKeyType {
1589 typedef SmallVector<unsigned, 4> IndexList;
1591 ExprMapKeyType(unsigned opc,
1592 const std::vector<Constant*> &ops,
1593 unsigned short pred = 0,
1594 const IndexList &inds = IndexList())
1595 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1598 std::vector<Constant*> operands;
1600 bool operator==(const ExprMapKeyType& that) const {
1601 return this->opcode == that.opcode &&
1602 this->predicate == that.predicate &&
1603 this->operands == that.operands &&
1604 this->indices == that.indices;
1606 bool operator<(const ExprMapKeyType & that) const {
1607 return this->opcode < that.opcode ||
1608 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1609 (this->opcode == that.opcode && this->predicate == that.predicate &&
1610 this->operands < that.operands) ||
1611 (this->opcode == that.opcode && this->predicate == that.predicate &&
1612 this->operands == that.operands && this->indices < that.indices);
1615 bool operator!=(const ExprMapKeyType& that) const {
1616 return !(*this == that);
1624 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1625 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1626 unsigned short pred = 0) {
1627 if (Instruction::isCast(V.opcode))
1628 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1629 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1630 V.opcode < Instruction::BinaryOpsEnd))
1631 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1632 if (V.opcode == Instruction::Select)
1633 return new SelectConstantExpr(V.operands[0], V.operands[1],
1635 if (V.opcode == Instruction::ExtractElement)
1636 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1637 if (V.opcode == Instruction::InsertElement)
1638 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1640 if (V.opcode == Instruction::ShuffleVector)
1641 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1643 if (V.opcode == Instruction::InsertValue)
1644 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1646 if (V.opcode == Instruction::ExtractValue)
1647 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1648 if (V.opcode == Instruction::GetElementPtr) {
1649 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1650 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1653 // The compare instructions are weird. We have to encode the predicate
1654 // value and it is combined with the instruction opcode by multiplying
1655 // the opcode by one hundred. We must decode this to get the predicate.
1656 if (V.opcode == Instruction::ICmp)
1657 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1658 V.operands[0], V.operands[1]);
1659 if (V.opcode == Instruction::FCmp)
1660 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1661 V.operands[0], V.operands[1]);
1662 llvm_unreachable("Invalid ConstantExpr!");
1668 struct ConvertConstantType<ConstantExpr, Type> {
1669 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1671 switch (OldC->getOpcode()) {
1672 case Instruction::Trunc:
1673 case Instruction::ZExt:
1674 case Instruction::SExt:
1675 case Instruction::FPTrunc:
1676 case Instruction::FPExt:
1677 case Instruction::UIToFP:
1678 case Instruction::SIToFP:
1679 case Instruction::FPToUI:
1680 case Instruction::FPToSI:
1681 case Instruction::PtrToInt:
1682 case Instruction::IntToPtr:
1683 case Instruction::BitCast:
1684 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1687 case Instruction::Select:
1688 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1689 OldC->getOperand(1),
1690 OldC->getOperand(2));
1693 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1694 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1695 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1696 OldC->getOperand(1));
1698 case Instruction::GetElementPtr:
1699 // Make everyone now use a constant of the new type...
1700 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1701 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1702 &Idx[0], Idx.size());
1706 assert(New != OldC && "Didn't replace constant??");
1707 OldC->uncheckedReplaceAllUsesWith(New);
1708 OldC->destroyConstant(); // This constant is now dead, destroy it.
1711 } // end namespace llvm
1714 static ExprMapKeyType getValType(ConstantExpr *CE) {
1715 std::vector<Constant*> Operands;
1716 Operands.reserve(CE->getNumOperands());
1717 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1718 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1719 return ExprMapKeyType(CE->getOpcode(), Operands,
1720 CE->isCompare() ? CE->getPredicate() : 0,
1722 CE->getIndices() : SmallVector<unsigned, 4>());
1725 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1726 ConstantExpr> > ExprConstants;
1728 /// This is a utility function to handle folding of casts and lookup of the
1729 /// cast in the ExprConstants map. It is used by the various get* methods below.
1730 static inline Constant *getFoldedCast(
1731 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1732 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1733 // Fold a few common cases
1735 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1738 // Look up the constant in the table first to ensure uniqueness
1739 std::vector<Constant*> argVec(1, C);
1740 ExprMapKeyType Key(opc, argVec);
1742 // Implicitly locked.
1743 return ExprConstants->getOrCreate(Ty, Key);
1746 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1747 Instruction::CastOps opc = Instruction::CastOps(oc);
1748 assert(Instruction::isCast(opc) && "opcode out of range");
1749 assert(C && Ty && "Null arguments to getCast");
1750 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1754 llvm_unreachable("Invalid cast opcode");
1756 case Instruction::Trunc: return getTrunc(C, Ty);
1757 case Instruction::ZExt: return getZExt(C, Ty);
1758 case Instruction::SExt: return getSExt(C, Ty);
1759 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1760 case Instruction::FPExt: return getFPExtend(C, Ty);
1761 case Instruction::UIToFP: return getUIToFP(C, Ty);
1762 case Instruction::SIToFP: return getSIToFP(C, Ty);
1763 case Instruction::FPToUI: return getFPToUI(C, Ty);
1764 case Instruction::FPToSI: return getFPToSI(C, Ty);
1765 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1766 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1767 case Instruction::BitCast: return getBitCast(C, Ty);
1772 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1773 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1774 return getCast(Instruction::BitCast, C, Ty);
1775 return getCast(Instruction::ZExt, C, Ty);
1778 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1779 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1780 return getCast(Instruction::BitCast, C, Ty);
1781 return getCast(Instruction::SExt, C, Ty);
1784 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1785 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1786 return getCast(Instruction::BitCast, C, Ty);
1787 return getCast(Instruction::Trunc, C, Ty);
1790 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1791 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1792 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1794 if (Ty->isInteger())
1795 return getCast(Instruction::PtrToInt, S, Ty);
1796 return getCast(Instruction::BitCast, S, Ty);
1799 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1801 assert(C->getType()->isIntOrIntVector() &&
1802 Ty->isIntOrIntVector() && "Invalid cast");
1803 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1804 unsigned DstBits = Ty->getScalarSizeInBits();
1805 Instruction::CastOps opcode =
1806 (SrcBits == DstBits ? Instruction::BitCast :
1807 (SrcBits > DstBits ? Instruction::Trunc :
1808 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1809 return getCast(opcode, C, Ty);
1812 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1813 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1815 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1816 unsigned DstBits = Ty->getScalarSizeInBits();
1817 if (SrcBits == DstBits)
1818 return C; // Avoid a useless cast
1819 Instruction::CastOps opcode =
1820 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1821 return getCast(opcode, C, Ty);
1824 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1826 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1827 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1829 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1830 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1831 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1832 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1833 "SrcTy must be larger than DestTy for Trunc!");
1835 return getFoldedCast(Instruction::Trunc, C, Ty);
1838 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1840 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1841 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1843 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1844 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1845 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1846 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1847 "SrcTy must be smaller than DestTy for SExt!");
1849 return getFoldedCast(Instruction::SExt, C, Ty);
1852 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1854 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1855 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1857 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1858 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1859 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1860 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1861 "SrcTy must be smaller than DestTy for ZExt!");
1863 return getFoldedCast(Instruction::ZExt, C, Ty);
1866 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1868 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1869 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1871 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1872 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1873 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1874 "This is an illegal floating point truncation!");
1875 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1878 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1880 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1881 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1883 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1884 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1885 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1886 "This is an illegal floating point extension!");
1887 return getFoldedCast(Instruction::FPExt, C, Ty);
1890 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1892 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1893 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1895 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1896 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1897 "This is an illegal uint to floating point cast!");
1898 return getFoldedCast(Instruction::UIToFP, C, Ty);
1901 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1903 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1904 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1906 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1907 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1908 "This is an illegal sint to floating point cast!");
1909 return getFoldedCast(Instruction::SIToFP, C, Ty);
1912 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1914 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1915 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1917 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1918 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1919 "This is an illegal floating point to uint cast!");
1920 return getFoldedCast(Instruction::FPToUI, C, Ty);
1923 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1925 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1926 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1928 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1929 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1930 "This is an illegal floating point to sint cast!");
1931 return getFoldedCast(Instruction::FPToSI, C, Ty);
1934 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1935 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1936 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1937 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1940 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1941 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1942 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1943 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1946 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1947 // BitCast implies a no-op cast of type only. No bits change. However, you
1948 // can't cast pointers to anything but pointers.
1950 const Type *SrcTy = C->getType();
1951 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1952 "BitCast cannot cast pointer to non-pointer and vice versa");
1954 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1955 // or nonptr->ptr). For all the other types, the cast is okay if source and
1956 // destination bit widths are identical.
1957 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1958 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1960 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1962 // It is common to ask for a bitcast of a value to its own type, handle this
1964 if (C->getType() == DstTy) return C;
1966 return getFoldedCast(Instruction::BitCast, C, DstTy);
1969 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1970 Constant *C1, Constant *C2) {
1971 // Check the operands for consistency first
1972 assert(Opcode >= Instruction::BinaryOpsBegin &&
1973 Opcode < Instruction::BinaryOpsEnd &&
1974 "Invalid opcode in binary constant expression");
1975 assert(C1->getType() == C2->getType() &&
1976 "Operand types in binary constant expression should match");
1978 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1979 if (Constant *FC = ConstantFoldBinaryInstruction(
1980 getGlobalContext(), Opcode, C1, C2))
1981 return FC; // Fold a few common cases...
1983 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1984 ExprMapKeyType Key(Opcode, argVec);
1986 // Implicitly locked.
1987 return ExprConstants->getOrCreate(ReqTy, Key);
1990 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1991 Constant *C1, Constant *C2) {
1992 switch (predicate) {
1993 default: llvm_unreachable("Invalid CmpInst predicate");
1994 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1995 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1996 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1997 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1998 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1999 case CmpInst::FCMP_TRUE:
2000 return getFCmp(predicate, C1, C2);
2002 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2003 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2004 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2005 case CmpInst::ICMP_SLE:
2006 return getICmp(predicate, C1, C2);
2010 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2011 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2012 if (C1->getType()->isFPOrFPVector()) {
2013 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2014 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2015 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2019 case Instruction::Add:
2020 case Instruction::Sub:
2021 case Instruction::Mul:
2022 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2023 assert(C1->getType()->isIntOrIntVector() &&
2024 "Tried to create an integer operation on a non-integer type!");
2026 case Instruction::FAdd:
2027 case Instruction::FSub:
2028 case Instruction::FMul:
2029 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2030 assert(C1->getType()->isFPOrFPVector() &&
2031 "Tried to create a floating-point operation on a "
2032 "non-floating-point type!");
2034 case Instruction::UDiv:
2035 case Instruction::SDiv:
2036 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2037 assert(C1->getType()->isIntOrIntVector() &&
2038 "Tried to create an arithmetic operation on a non-arithmetic type!");
2040 case Instruction::FDiv:
2041 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2042 assert(C1->getType()->isFPOrFPVector() &&
2043 "Tried to create an arithmetic operation on a non-arithmetic type!");
2045 case Instruction::URem:
2046 case Instruction::SRem:
2047 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2048 assert(C1->getType()->isIntOrIntVector() &&
2049 "Tried to create an arithmetic operation on a non-arithmetic type!");
2051 case Instruction::FRem:
2052 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2053 assert(C1->getType()->isFPOrFPVector() &&
2054 "Tried to create an arithmetic operation on a non-arithmetic type!");
2056 case Instruction::And:
2057 case Instruction::Or:
2058 case Instruction::Xor:
2059 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2060 assert(C1->getType()->isIntOrIntVector() &&
2061 "Tried to create a logical operation on a non-integral type!");
2063 case Instruction::Shl:
2064 case Instruction::LShr:
2065 case Instruction::AShr:
2066 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2067 assert(C1->getType()->isIntOrIntVector() &&
2068 "Tried to create a shift operation on a non-integer type!");
2075 return getTy(C1->getType(), Opcode, C1, C2);
2078 Constant *ConstantExpr::getCompare(unsigned short pred,
2079 Constant *C1, Constant *C2) {
2080 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2081 return getCompareTy(pred, C1, C2);
2084 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2085 Constant *V1, Constant *V2) {
2086 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2088 if (ReqTy == V1->getType())
2089 if (Constant *SC = ConstantFoldSelectInstruction(
2090 getGlobalContext(), C, V1, V2))
2091 return SC; // Fold common cases
2093 std::vector<Constant*> argVec(3, C);
2096 ExprMapKeyType Key(Instruction::Select, argVec);
2098 // Implicitly locked.
2099 return ExprConstants->getOrCreate(ReqTy, Key);
2102 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2105 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2107 cast<PointerType>(ReqTy)->getElementType() &&
2108 "GEP indices invalid!");
2110 if (Constant *FC = ConstantFoldGetElementPtr(
2111 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2112 return FC; // Fold a few common cases...
2114 assert(isa<PointerType>(C->getType()) &&
2115 "Non-pointer type for constant GetElementPtr expression");
2116 // Look up the constant in the table first to ensure uniqueness
2117 std::vector<Constant*> ArgVec;
2118 ArgVec.reserve(NumIdx+1);
2119 ArgVec.push_back(C);
2120 for (unsigned i = 0; i != NumIdx; ++i)
2121 ArgVec.push_back(cast<Constant>(Idxs[i]));
2122 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2124 // Implicitly locked.
2125 return ExprConstants->getOrCreate(ReqTy, Key);
2128 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2130 // Get the result type of the getelementptr!
2132 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2133 assert(Ty && "GEP indices invalid!");
2134 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2135 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2138 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2140 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2145 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2146 assert(LHS->getType() == RHS->getType());
2147 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2148 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2150 if (Constant *FC = ConstantFoldCompareInstruction(
2151 getGlobalContext(),pred, LHS, RHS))
2152 return FC; // Fold a few common cases...
2154 // Look up the constant in the table first to ensure uniqueness
2155 std::vector<Constant*> ArgVec;
2156 ArgVec.push_back(LHS);
2157 ArgVec.push_back(RHS);
2158 // Get the key type with both the opcode and predicate
2159 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2161 // Implicitly locked.
2162 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2166 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2167 assert(LHS->getType() == RHS->getType());
2168 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2170 if (Constant *FC = ConstantFoldCompareInstruction(
2171 getGlobalContext(), pred, LHS, RHS))
2172 return FC; // Fold a few common cases...
2174 // Look up the constant in the table first to ensure uniqueness
2175 std::vector<Constant*> ArgVec;
2176 ArgVec.push_back(LHS);
2177 ArgVec.push_back(RHS);
2178 // Get the key type with both the opcode and predicate
2179 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2181 // Implicitly locked.
2182 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2185 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2187 if (Constant *FC = ConstantFoldExtractElementInstruction(
2188 getGlobalContext(), Val, Idx))
2189 return FC; // Fold a few common cases...
2190 // Look up the constant in the table first to ensure uniqueness
2191 std::vector<Constant*> ArgVec(1, Val);
2192 ArgVec.push_back(Idx);
2193 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2195 // Implicitly locked.
2196 return ExprConstants->getOrCreate(ReqTy, Key);
2199 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2200 assert(isa<VectorType>(Val->getType()) &&
2201 "Tried to create extractelement operation on non-vector type!");
2202 assert(Idx->getType() == Type::Int32Ty &&
2203 "Extractelement index must be i32 type!");
2204 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2208 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2209 Constant *Elt, Constant *Idx) {
2210 if (Constant *FC = ConstantFoldInsertElementInstruction(
2211 getGlobalContext(), Val, Elt, Idx))
2212 return FC; // Fold a few common cases...
2213 // Look up the constant in the table first to ensure uniqueness
2214 std::vector<Constant*> ArgVec(1, Val);
2215 ArgVec.push_back(Elt);
2216 ArgVec.push_back(Idx);
2217 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2219 // Implicitly locked.
2220 return ExprConstants->getOrCreate(ReqTy, Key);
2223 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2225 assert(isa<VectorType>(Val->getType()) &&
2226 "Tried to create insertelement operation on non-vector type!");
2227 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2228 && "Insertelement types must match!");
2229 assert(Idx->getType() == Type::Int32Ty &&
2230 "Insertelement index must be i32 type!");
2231 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2234 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2235 Constant *V2, Constant *Mask) {
2236 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2237 getGlobalContext(), V1, V2, Mask))
2238 return FC; // Fold a few common cases...
2239 // Look up the constant in the table first to ensure uniqueness
2240 std::vector<Constant*> ArgVec(1, V1);
2241 ArgVec.push_back(V2);
2242 ArgVec.push_back(Mask);
2243 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2245 // Implicitly locked.
2246 return ExprConstants->getOrCreate(ReqTy, Key);
2249 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2251 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2252 "Invalid shuffle vector constant expr operands!");
2254 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2255 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2256 const Type *ShufTy = VectorType::get(EltTy, NElts);
2257 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2260 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2262 const unsigned *Idxs, unsigned NumIdx) {
2263 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2264 Idxs+NumIdx) == Val->getType() &&
2265 "insertvalue indices invalid!");
2266 assert(Agg->getType() == ReqTy &&
2267 "insertvalue type invalid!");
2268 assert(Agg->getType()->isFirstClassType() &&
2269 "Non-first-class type for constant InsertValue expression");
2270 Constant *FC = ConstantFoldInsertValueInstruction(
2271 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2272 assert(FC && "InsertValue constant expr couldn't be folded!");
2276 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2277 const unsigned *IdxList, unsigned NumIdx) {
2278 assert(Agg->getType()->isFirstClassType() &&
2279 "Tried to create insertelement operation on non-first-class type!");
2281 const Type *ReqTy = Agg->getType();
2284 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2286 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2287 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2290 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2291 const unsigned *Idxs, unsigned NumIdx) {
2292 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2293 Idxs+NumIdx) == ReqTy &&
2294 "extractvalue indices invalid!");
2295 assert(Agg->getType()->isFirstClassType() &&
2296 "Non-first-class type for constant extractvalue expression");
2297 Constant *FC = ConstantFoldExtractValueInstruction(
2298 getGlobalContext(), Agg, Idxs, NumIdx);
2299 assert(FC && "ExtractValue constant expr couldn't be folded!");
2303 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2304 const unsigned *IdxList, unsigned NumIdx) {
2305 assert(Agg->getType()->isFirstClassType() &&
2306 "Tried to create extractelement operation on non-first-class type!");
2309 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2310 assert(ReqTy && "extractvalue indices invalid!");
2311 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2314 // destroyConstant - Remove the constant from the constant table...
2316 void ConstantExpr::destroyConstant() {
2317 // Implicitly locked.
2318 ExprConstants->remove(this);
2319 destroyConstantImpl();
2322 const char *ConstantExpr::getOpcodeName() const {
2323 return Instruction::getOpcodeName(getOpcode());
2326 //===----------------------------------------------------------------------===//
2327 // replaceUsesOfWithOnConstant implementations
2329 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2330 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2333 /// Note that we intentionally replace all uses of From with To here. Consider
2334 /// a large array that uses 'From' 1000 times. By handling this case all here,
2335 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2336 /// single invocation handles all 1000 uses. Handling them one at a time would
2337 /// work, but would be really slow because it would have to unique each updated
2339 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2341 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2342 Constant *ToC = cast<Constant>(To);
2344 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2345 Lookup.first.first = getType();
2346 Lookup.second = this;
2348 std::vector<Constant*> &Values = Lookup.first.second;
2349 Values.reserve(getNumOperands()); // Build replacement array.
2351 // Fill values with the modified operands of the constant array. Also,
2352 // compute whether this turns into an all-zeros array.
2353 bool isAllZeros = false;
2354 unsigned NumUpdated = 0;
2355 if (!ToC->isNullValue()) {
2356 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2357 Constant *Val = cast<Constant>(O->get());
2362 Values.push_back(Val);
2366 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2367 Constant *Val = cast<Constant>(O->get());
2372 Values.push_back(Val);
2373 if (isAllZeros) isAllZeros = Val->isNullValue();
2377 Constant *Replacement = 0;
2379 Replacement = ConstantAggregateZero::get(getType());
2381 // Check to see if we have this array type already.
2382 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2384 ArrayConstantsTy::MapTy::iterator I =
2385 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2388 Replacement = I->second;
2390 // Okay, the new shape doesn't exist in the system yet. Instead of
2391 // creating a new constant array, inserting it, replaceallusesof'ing the
2392 // old with the new, then deleting the old... just update the current one
2394 ArrayConstants->MoveConstantToNewSlot(this, I);
2396 // Update to the new value. Optimize for the case when we have a single
2397 // operand that we're changing, but handle bulk updates efficiently.
2398 if (NumUpdated == 1) {
2399 unsigned OperandToUpdate = U-OperandList;
2400 assert(getOperand(OperandToUpdate) == From &&
2401 "ReplaceAllUsesWith broken!");
2402 setOperand(OperandToUpdate, ToC);
2404 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2405 if (getOperand(i) == From)
2412 // Otherwise, I do need to replace this with an existing value.
2413 assert(Replacement != this && "I didn't contain From!");
2415 // Everyone using this now uses the replacement.
2416 uncheckedReplaceAllUsesWith(Replacement);
2418 // Delete the old constant!
2422 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2424 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2425 Constant *ToC = cast<Constant>(To);
2427 unsigned OperandToUpdate = U-OperandList;
2428 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2430 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2431 Lookup.first.first = getType();
2432 Lookup.second = this;
2433 std::vector<Constant*> &Values = Lookup.first.second;
2434 Values.reserve(getNumOperands()); // Build replacement struct.
2437 // Fill values with the modified operands of the constant struct. Also,
2438 // compute whether this turns into an all-zeros struct.
2439 bool isAllZeros = false;
2440 if (!ToC->isNullValue()) {
2441 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2442 Values.push_back(cast<Constant>(O->get()));
2445 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2446 Constant *Val = cast<Constant>(O->get());
2447 Values.push_back(Val);
2448 if (isAllZeros) isAllZeros = Val->isNullValue();
2451 Values[OperandToUpdate] = ToC;
2453 Constant *Replacement = 0;
2455 Replacement = ConstantAggregateZero::get(getType());
2457 // Check to see if we have this array type already.
2458 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2460 StructConstantsTy::MapTy::iterator I =
2461 StructConstants->InsertOrGetItem(Lookup, Exists);
2464 Replacement = I->second;
2466 // Okay, the new shape doesn't exist in the system yet. Instead of
2467 // creating a new constant struct, inserting it, replaceallusesof'ing the
2468 // old with the new, then deleting the old... just update the current one
2470 StructConstants->MoveConstantToNewSlot(this, I);
2472 // Update to the new value.
2473 setOperand(OperandToUpdate, ToC);
2478 assert(Replacement != this && "I didn't contain From!");
2480 // Everyone using this now uses the replacement.
2481 uncheckedReplaceAllUsesWith(Replacement);
2483 // Delete the old constant!
2487 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2489 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2491 std::vector<Constant*> Values;
2492 Values.reserve(getNumOperands()); // Build replacement array...
2493 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2494 Constant *Val = getOperand(i);
2495 if (Val == From) Val = cast<Constant>(To);
2496 Values.push_back(Val);
2499 Constant *Replacement = ConstantVector::get(getType(), Values);
2500 assert(Replacement != this && "I didn't contain From!");
2502 // Everyone using this now uses the replacement.
2503 uncheckedReplaceAllUsesWith(Replacement);
2505 // Delete the old constant!
2509 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2511 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2512 Constant *To = cast<Constant>(ToV);
2514 Constant *Replacement = 0;
2515 if (getOpcode() == Instruction::GetElementPtr) {
2516 SmallVector<Constant*, 8> Indices;
2517 Constant *Pointer = getOperand(0);
2518 Indices.reserve(getNumOperands()-1);
2519 if (Pointer == From) Pointer = To;
2521 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2522 Constant *Val = getOperand(i);
2523 if (Val == From) Val = To;
2524 Indices.push_back(Val);
2526 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2527 &Indices[0], Indices.size());
2528 } else if (getOpcode() == Instruction::ExtractValue) {
2529 Constant *Agg = getOperand(0);
2530 if (Agg == From) Agg = To;
2532 const SmallVector<unsigned, 4> &Indices = getIndices();
2533 Replacement = ConstantExpr::getExtractValue(Agg,
2534 &Indices[0], Indices.size());
2535 } else if (getOpcode() == Instruction::InsertValue) {
2536 Constant *Agg = getOperand(0);
2537 Constant *Val = getOperand(1);
2538 if (Agg == From) Agg = To;
2539 if (Val == From) Val = To;
2541 const SmallVector<unsigned, 4> &Indices = getIndices();
2542 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2543 &Indices[0], Indices.size());
2544 } else if (isCast()) {
2545 assert(getOperand(0) == From && "Cast only has one use!");
2546 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2547 } else if (getOpcode() == Instruction::Select) {
2548 Constant *C1 = getOperand(0);
2549 Constant *C2 = getOperand(1);
2550 Constant *C3 = getOperand(2);
2551 if (C1 == From) C1 = To;
2552 if (C2 == From) C2 = To;
2553 if (C3 == From) C3 = To;
2554 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2555 } else if (getOpcode() == Instruction::ExtractElement) {
2556 Constant *C1 = getOperand(0);
2557 Constant *C2 = getOperand(1);
2558 if (C1 == From) C1 = To;
2559 if (C2 == From) C2 = To;
2560 Replacement = ConstantExpr::getExtractElement(C1, C2);
2561 } else if (getOpcode() == Instruction::InsertElement) {
2562 Constant *C1 = getOperand(0);
2563 Constant *C2 = getOperand(1);
2564 Constant *C3 = getOperand(1);
2565 if (C1 == From) C1 = To;
2566 if (C2 == From) C2 = To;
2567 if (C3 == From) C3 = To;
2568 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2569 } else if (getOpcode() == Instruction::ShuffleVector) {
2570 Constant *C1 = getOperand(0);
2571 Constant *C2 = getOperand(1);
2572 Constant *C3 = getOperand(2);
2573 if (C1 == From) C1 = To;
2574 if (C2 == From) C2 = To;
2575 if (C3 == From) C3 = To;
2576 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2577 } else if (isCompare()) {
2578 Constant *C1 = getOperand(0);
2579 Constant *C2 = getOperand(1);
2580 if (C1 == From) C1 = To;
2581 if (C2 == From) C2 = To;
2582 if (getOpcode() == Instruction::ICmp)
2583 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2585 assert(getOpcode() == Instruction::FCmp);
2586 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2588 } else if (getNumOperands() == 2) {
2589 Constant *C1 = getOperand(0);
2590 Constant *C2 = getOperand(1);
2591 if (C1 == From) C1 = To;
2592 if (C2 == From) C2 = To;
2593 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2595 llvm_unreachable("Unknown ConstantExpr type!");
2599 assert(Replacement != this && "I didn't contain From!");
2601 // Everyone using this now uses the replacement.
2602 uncheckedReplaceAllUsesWith(Replacement);
2604 // Delete the old constant!
2608 void MDNode::replaceElement(Value *From, Value *To) {
2609 SmallVector<Value*, 4> Values;
2610 Values.reserve(getNumElements()); // Build replacement array...
2611 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2612 Value *Val = getElement(i);
2613 if (Val == From) Val = To;
2614 Values.push_back(Val);
2617 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2618 assert(Replacement != this && "I didn't contain From!");
2620 uncheckedReplaceAllUsesWith(Replacement);