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/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Becomes a no-op when multithreading is disabled.
44 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
46 void Constant::destroyConstantImpl() {
47 // When a Constant is destroyed, there may be lingering
48 // references to the constant by other constants in the constant pool. These
49 // constants are implicitly dependent on the module that is being deleted,
50 // but they don't know that. Because we only find out when the CPV is
51 // deleted, we must now notify all of our users (that should only be
52 // Constants) that they are, in fact, invalid now and should be deleted.
54 while (!use_empty()) {
55 Value *V = use_back();
56 #ifndef NDEBUG // Only in -g mode...
57 if (!isa<Constant>(V))
58 DOUT << "While deleting: " << *this
59 << "\n\nUse still stuck around after Def is destroyed: "
62 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
63 Constant *CV = cast<Constant>(V);
64 CV->destroyConstant();
66 // The constant should remove itself from our use list...
67 assert((use_empty() || use_back() != V) && "Constant not removed!");
70 // Value has no outstanding references it is safe to delete it now...
74 /// canTrap - Return true if evaluation of this constant could trap. This is
75 /// true for things like constant expressions that could divide by zero.
76 bool Constant::canTrap() const {
77 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
78 // The only thing that could possibly trap are constant exprs.
79 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
80 if (!CE) return false;
82 // ConstantExpr traps if any operands can trap.
83 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
84 if (getOperand(i)->canTrap())
87 // Otherwise, only specific operations can trap.
88 switch (CE->getOpcode()) {
91 case Instruction::UDiv:
92 case Instruction::SDiv:
93 case Instruction::FDiv:
94 case Instruction::URem:
95 case Instruction::SRem:
96 case Instruction::FRem:
97 // Div and rem can trap if the RHS is not known to be non-zero.
98 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
105 /// getRelocationInfo - This method classifies the entry according to
106 /// whether or not it may generate a relocation entry. This must be
107 /// conservative, so if it might codegen to a relocatable entry, it should say
108 /// so. The return values are:
110 /// NoRelocation: This constant pool entry is guaranteed to never have a
111 /// relocation applied to it (because it holds a simple constant like
113 /// LocalRelocation: This entry has relocations, but the entries are
114 /// guaranteed to be resolvable by the static linker, so the dynamic
115 /// linker will never see them.
116 /// GlobalRelocations: This entry may have arbitrary relocations.
118 /// FIXME: This really should not be in VMCore.
119 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
120 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
121 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
122 return LocalRelocation; // Local to this file/library.
123 return GlobalRelocations; // Global reference.
126 PossibleRelocationsTy Result = NoRelocation;
127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
128 Result = std::max(Result, getOperand(i)->getRelocationInfo());
134 /// getVectorElements - This method, which is only valid on constant of vector
135 /// type, returns the elements of the vector in the specified smallvector.
136 /// This handles breaking down a vector undef into undef elements, etc. For
137 /// constant exprs and other cases we can't handle, we return an empty vector.
138 void Constant::getVectorElements(LLVMContext &Context,
139 SmallVectorImpl<Constant*> &Elts) const {
140 assert(isa<VectorType>(getType()) && "Not a vector constant!");
142 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
143 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
144 Elts.push_back(CV->getOperand(i));
148 const VectorType *VT = cast<VectorType>(getType());
149 if (isa<ConstantAggregateZero>(this)) {
150 Elts.assign(VT->getNumElements(),
151 Context.getNullValue(VT->getElementType()));
155 if (isa<UndefValue>(this)) {
156 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
160 // Unknown type, must be constant expr etc.
165 //===----------------------------------------------------------------------===//
167 //===----------------------------------------------------------------------===//
169 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
170 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
171 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
174 //===----------------------------------------------------------------------===//
176 //===----------------------------------------------------------------------===//
179 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
180 if (Ty == Type::FloatTy)
181 return &APFloat::IEEEsingle;
182 if (Ty == Type::DoubleTy)
183 return &APFloat::IEEEdouble;
184 if (Ty == Type::X86_FP80Ty)
185 return &APFloat::x87DoubleExtended;
186 else if (Ty == Type::FP128Ty)
187 return &APFloat::IEEEquad;
189 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
190 return &APFloat::PPCDoubleDouble;
194 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
195 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
196 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
200 bool ConstantFP::isNullValue() const {
201 return Val.isZero() && !Val.isNegative();
204 bool ConstantFP::isExactlyValue(const APFloat& V) const {
205 return Val.bitwiseIsEqual(V);
208 //===----------------------------------------------------------------------===//
209 // ConstantXXX Classes
210 //===----------------------------------------------------------------------===//
213 ConstantArray::ConstantArray(const ArrayType *T,
214 const std::vector<Constant*> &V)
215 : Constant(T, ConstantArrayVal,
216 OperandTraits<ConstantArray>::op_end(this) - V.size(),
218 assert(V.size() == T->getNumElements() &&
219 "Invalid initializer vector for constant array");
220 Use *OL = OperandList;
221 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
224 assert((C->getType() == T->getElementType() ||
226 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
227 "Initializer for array element doesn't match array element type!");
233 ConstantStruct::ConstantStruct(const StructType *T,
234 const std::vector<Constant*> &V)
235 : Constant(T, ConstantStructVal,
236 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
238 assert(V.size() == T->getNumElements() &&
239 "Invalid initializer vector for constant structure");
240 Use *OL = OperandList;
241 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
244 assert((C->getType() == T->getElementType(I-V.begin()) ||
245 ((T->getElementType(I-V.begin())->isAbstract() ||
246 C->getType()->isAbstract()) &&
247 T->getElementType(I-V.begin())->getTypeID() ==
248 C->getType()->getTypeID())) &&
249 "Initializer for struct element doesn't match struct element type!");
255 ConstantVector::ConstantVector(const VectorType *T,
256 const std::vector<Constant*> &V)
257 : Constant(T, ConstantVectorVal,
258 OperandTraits<ConstantVector>::op_end(this) - V.size(),
260 Use *OL = OperandList;
261 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
264 assert((C->getType() == T->getElementType() ||
266 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
267 "Initializer for vector element doesn't match vector element type!");
274 // We declare several classes private to this file, so use an anonymous
278 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
279 /// behind the scenes to implement unary constant exprs.
280 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
281 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
283 // allocate space for exactly one operand
284 void *operator new(size_t s) {
285 return User::operator new(s, 1);
287 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
288 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
291 /// Transparently provide more efficient getOperand methods.
292 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
295 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
296 /// behind the scenes to implement binary constant exprs.
297 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
298 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
300 // allocate space for exactly two operands
301 void *operator new(size_t s) {
302 return User::operator new(s, 2);
304 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
305 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
309 /// Transparently provide more efficient getOperand methods.
310 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
313 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
314 /// behind the scenes to implement select constant exprs.
315 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
316 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
318 // allocate space for exactly three operands
319 void *operator new(size_t s) {
320 return User::operator new(s, 3);
322 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
323 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
328 /// Transparently provide more efficient getOperand methods.
329 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
332 /// ExtractElementConstantExpr - This class is private to
333 /// Constants.cpp, and is used behind the scenes to implement
334 /// extractelement constant exprs.
335 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
336 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
338 // allocate space for exactly two operands
339 void *operator new(size_t s) {
340 return User::operator new(s, 2);
342 ExtractElementConstantExpr(Constant *C1, Constant *C2)
343 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
344 Instruction::ExtractElement, &Op<0>(), 2) {
348 /// Transparently provide more efficient getOperand methods.
349 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
352 /// InsertElementConstantExpr - This class is private to
353 /// Constants.cpp, and is used behind the scenes to implement
354 /// insertelement constant exprs.
355 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
356 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
358 // allocate space for exactly three operands
359 void *operator new(size_t s) {
360 return User::operator new(s, 3);
362 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
363 : ConstantExpr(C1->getType(), Instruction::InsertElement,
369 /// Transparently provide more efficient getOperand methods.
370 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
373 /// ShuffleVectorConstantExpr - This class is private to
374 /// Constants.cpp, and is used behind the scenes to implement
375 /// shufflevector constant exprs.
376 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
377 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
379 // allocate space for exactly three operands
380 void *operator new(size_t s) {
381 return User::operator new(s, 3);
383 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
384 : ConstantExpr(VectorType::get(
385 cast<VectorType>(C1->getType())->getElementType(),
386 cast<VectorType>(C3->getType())->getNumElements()),
387 Instruction::ShuffleVector,
393 /// Transparently provide more efficient getOperand methods.
394 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
397 /// ExtractValueConstantExpr - This class is private to
398 /// Constants.cpp, and is used behind the scenes to implement
399 /// extractvalue constant exprs.
400 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
401 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
403 // allocate space for exactly one operand
404 void *operator new(size_t s) {
405 return User::operator new(s, 1);
407 ExtractValueConstantExpr(Constant *Agg,
408 const SmallVector<unsigned, 4> &IdxList,
410 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
415 /// Indices - These identify which value to extract.
416 const SmallVector<unsigned, 4> Indices;
418 /// Transparently provide more efficient getOperand methods.
419 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
422 /// InsertValueConstantExpr - This class is private to
423 /// Constants.cpp, and is used behind the scenes to implement
424 /// insertvalue constant exprs.
425 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
426 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
428 // allocate space for exactly one operand
429 void *operator new(size_t s) {
430 return User::operator new(s, 2);
432 InsertValueConstantExpr(Constant *Agg, Constant *Val,
433 const SmallVector<unsigned, 4> &IdxList,
435 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
441 /// Indices - These identify the position for the insertion.
442 const SmallVector<unsigned, 4> Indices;
444 /// Transparently provide more efficient getOperand methods.
445 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
449 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
450 /// used behind the scenes to implement getelementpr constant exprs.
451 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
452 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
455 static GetElementPtrConstantExpr *Create(Constant *C,
456 const std::vector<Constant*>&IdxList,
457 const Type *DestTy) {
459 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
461 /// Transparently provide more efficient getOperand methods.
462 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
465 // CompareConstantExpr - This class is private to Constants.cpp, and is used
466 // behind the scenes to implement ICmp and FCmp constant expressions. This is
467 // needed in order to store the predicate value for these instructions.
468 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
469 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
470 // allocate space for exactly two operands
471 void *operator new(size_t s) {
472 return User::operator new(s, 2);
474 unsigned short predicate;
475 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
476 unsigned short pred, Constant* LHS, Constant* RHS)
477 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
481 /// Transparently provide more efficient getOperand methods.
482 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
485 } // end anonymous namespace
488 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
490 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
493 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
495 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
498 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
500 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
503 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
505 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
508 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
510 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
513 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
515 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
518 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
520 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
523 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
525 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
528 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
531 GetElementPtrConstantExpr::GetElementPtrConstantExpr
533 const std::vector<Constant*> &IdxList,
535 : ConstantExpr(DestTy, Instruction::GetElementPtr,
536 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
537 - (IdxList.size()+1),
540 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
541 OperandList[i+1] = IdxList[i];
544 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
548 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
550 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
553 } // End llvm namespace
556 // Utility function for determining if a ConstantExpr is a CastOp or not. This
557 // can't be inline because we don't want to #include Instruction.h into
559 bool ConstantExpr::isCast() const {
560 return Instruction::isCast(getOpcode());
563 bool ConstantExpr::isCompare() const {
564 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
567 bool ConstantExpr::hasIndices() const {
568 return getOpcode() == Instruction::ExtractValue ||
569 getOpcode() == Instruction::InsertValue;
572 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
573 if (const ExtractValueConstantExpr *EVCE =
574 dyn_cast<ExtractValueConstantExpr>(this))
575 return EVCE->Indices;
577 return cast<InsertValueConstantExpr>(this)->Indices;
580 unsigned ConstantExpr::getPredicate() const {
581 assert(getOpcode() == Instruction::FCmp ||
582 getOpcode() == Instruction::ICmp);
583 return ((const CompareConstantExpr*)this)->predicate;
586 /// getWithOperandReplaced - Return a constant expression identical to this
587 /// one, but with the specified operand set to the specified value.
589 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
590 assert(OpNo < getNumOperands() && "Operand num is out of range!");
591 assert(Op->getType() == getOperand(OpNo)->getType() &&
592 "Replacing operand with value of different type!");
593 if (getOperand(OpNo) == Op)
594 return const_cast<ConstantExpr*>(this);
596 Constant *Op0, *Op1, *Op2;
597 switch (getOpcode()) {
598 case Instruction::Trunc:
599 case Instruction::ZExt:
600 case Instruction::SExt:
601 case Instruction::FPTrunc:
602 case Instruction::FPExt:
603 case Instruction::UIToFP:
604 case Instruction::SIToFP:
605 case Instruction::FPToUI:
606 case Instruction::FPToSI:
607 case Instruction::PtrToInt:
608 case Instruction::IntToPtr:
609 case Instruction::BitCast:
610 return ConstantExpr::getCast(getOpcode(), Op, getType());
611 case Instruction::Select:
612 Op0 = (OpNo == 0) ? Op : getOperand(0);
613 Op1 = (OpNo == 1) ? Op : getOperand(1);
614 Op2 = (OpNo == 2) ? Op : getOperand(2);
615 return ConstantExpr::getSelect(Op0, Op1, Op2);
616 case Instruction::InsertElement:
617 Op0 = (OpNo == 0) ? Op : getOperand(0);
618 Op1 = (OpNo == 1) ? Op : getOperand(1);
619 Op2 = (OpNo == 2) ? Op : getOperand(2);
620 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
621 case Instruction::ExtractElement:
622 Op0 = (OpNo == 0) ? Op : getOperand(0);
623 Op1 = (OpNo == 1) ? Op : getOperand(1);
624 return ConstantExpr::getExtractElement(Op0, Op1);
625 case Instruction::ShuffleVector:
626 Op0 = (OpNo == 0) ? Op : getOperand(0);
627 Op1 = (OpNo == 1) ? Op : getOperand(1);
628 Op2 = (OpNo == 2) ? Op : getOperand(2);
629 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
630 case Instruction::GetElementPtr: {
631 SmallVector<Constant*, 8> Ops;
632 Ops.resize(getNumOperands()-1);
633 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
634 Ops[i-1] = getOperand(i);
636 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
638 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
641 assert(getNumOperands() == 2 && "Must be binary operator?");
642 Op0 = (OpNo == 0) ? Op : getOperand(0);
643 Op1 = (OpNo == 1) ? Op : getOperand(1);
644 return ConstantExpr::get(getOpcode(), Op0, Op1);
648 /// getWithOperands - This returns the current constant expression with the
649 /// operands replaced with the specified values. The specified operands must
650 /// match count and type with the existing ones.
651 Constant *ConstantExpr::
652 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
653 assert(NumOps == getNumOperands() && "Operand count mismatch!");
654 bool AnyChange = false;
655 for (unsigned i = 0; i != NumOps; ++i) {
656 assert(Ops[i]->getType() == getOperand(i)->getType() &&
657 "Operand type mismatch!");
658 AnyChange |= Ops[i] != getOperand(i);
660 if (!AnyChange) // No operands changed, return self.
661 return const_cast<ConstantExpr*>(this);
663 switch (getOpcode()) {
664 case Instruction::Trunc:
665 case Instruction::ZExt:
666 case Instruction::SExt:
667 case Instruction::FPTrunc:
668 case Instruction::FPExt:
669 case Instruction::UIToFP:
670 case Instruction::SIToFP:
671 case Instruction::FPToUI:
672 case Instruction::FPToSI:
673 case Instruction::PtrToInt:
674 case Instruction::IntToPtr:
675 case Instruction::BitCast:
676 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
677 case Instruction::Select:
678 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
679 case Instruction::InsertElement:
680 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
681 case Instruction::ExtractElement:
682 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
683 case Instruction::ShuffleVector:
684 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
685 case Instruction::GetElementPtr:
686 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
687 case Instruction::ICmp:
688 case Instruction::FCmp:
689 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
691 assert(getNumOperands() == 2 && "Must be binary operator?");
692 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
697 //===----------------------------------------------------------------------===//
698 // isValueValidForType implementations
700 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
701 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
702 if (Ty == Type::Int1Ty)
703 return Val == 0 || Val == 1;
705 return true; // always true, has to fit in largest type
706 uint64_t Max = (1ll << NumBits) - 1;
710 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
711 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
712 if (Ty == Type::Int1Ty)
713 return Val == 0 || Val == 1 || Val == -1;
715 return true; // always true, has to fit in largest type
716 int64_t Min = -(1ll << (NumBits-1));
717 int64_t Max = (1ll << (NumBits-1)) - 1;
718 return (Val >= Min && Val <= Max);
721 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
722 // convert modifies in place, so make a copy.
723 APFloat Val2 = APFloat(Val);
725 switch (Ty->getTypeID()) {
727 return false; // These can't be represented as floating point!
729 // FIXME rounding mode needs to be more flexible
730 case Type::FloatTyID: {
731 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
733 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
736 case Type::DoubleTyID: {
737 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
738 &Val2.getSemantics() == &APFloat::IEEEdouble)
740 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
743 case Type::X86_FP80TyID:
744 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
745 &Val2.getSemantics() == &APFloat::IEEEdouble ||
746 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
747 case Type::FP128TyID:
748 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
749 &Val2.getSemantics() == &APFloat::IEEEdouble ||
750 &Val2.getSemantics() == &APFloat::IEEEquad;
751 case Type::PPC_FP128TyID:
752 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
753 &Val2.getSemantics() == &APFloat::IEEEdouble ||
754 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
758 //===----------------------------------------------------------------------===//
759 // Factory Function Implementation
762 // The number of operands for each ConstantCreator::create method is
763 // determined by the ConstantTraits template.
764 // ConstantCreator - A class that is used to create constants by
765 // ValueMap*. This class should be partially specialized if there is
766 // something strange that needs to be done to interface to the ctor for the
770 template<class ValType>
771 struct ConstantTraits;
773 template<typename T, typename Alloc>
774 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
775 static unsigned uses(const std::vector<T, Alloc>& v) {
780 template<class ConstantClass, class TypeClass, class ValType>
781 struct VISIBILITY_HIDDEN ConstantCreator {
782 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
783 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
787 template<class ConstantClass, class TypeClass>
788 struct VISIBILITY_HIDDEN ConvertConstantType {
789 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
790 llvm_unreachable("This type cannot be converted!");
794 template<class ValType, class TypeClass, class ConstantClass,
795 bool HasLargeKey = false /*true for arrays and structs*/ >
796 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
798 typedef std::pair<const Type*, ValType> MapKey;
799 typedef std::map<MapKey, Constant *> MapTy;
800 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
801 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
803 /// Map - This is the main map from the element descriptor to the Constants.
804 /// This is the primary way we avoid creating two of the same shape
808 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
809 /// from the constants to their element in Map. This is important for
810 /// removal of constants from the array, which would otherwise have to scan
811 /// through the map with very large keys.
812 InverseMapTy InverseMap;
814 /// AbstractTypeMap - Map for abstract type constants.
816 AbstractTypeMapTy AbstractTypeMap;
818 /// ValueMapLock - Mutex for this map.
819 sys::SmartMutex<true> ValueMapLock;
822 // NOTE: This function is not locked. It is the caller's responsibility
823 // to enforce proper synchronization.
824 typename MapTy::iterator map_end() { return Map.end(); }
826 /// InsertOrGetItem - Return an iterator for the specified element.
827 /// If the element exists in the map, the returned iterator points to the
828 /// entry and Exists=true. If not, the iterator points to the newly
829 /// inserted entry and returns Exists=false. Newly inserted entries have
830 /// I->second == 0, and should be filled in.
831 /// NOTE: This function is not locked. It is the caller's responsibility
832 // to enforce proper synchronization.
833 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
836 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
842 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
844 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
845 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
846 IMI->second->second == CP &&
847 "InverseMap corrupt!");
851 typename MapTy::iterator I =
852 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
854 if (I == Map.end() || I->second != CP) {
855 // FIXME: This should not use a linear scan. If this gets to be a
856 // performance problem, someone should look at this.
857 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
863 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
864 typename MapTy::iterator I) {
865 ConstantClass* Result =
866 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
868 assert(Result->getType() == Ty && "Type specified is not correct!");
869 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
871 if (HasLargeKey) // Remember the reverse mapping if needed.
872 InverseMap.insert(std::make_pair(Result, I));
874 // If the type of the constant is abstract, make sure that an entry
875 // exists for it in the AbstractTypeMap.
876 if (Ty->isAbstract()) {
877 typename AbstractTypeMapTy::iterator TI =
878 AbstractTypeMap.find(Ty);
880 if (TI == AbstractTypeMap.end()) {
881 // Add ourselves to the ATU list of the type.
882 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
884 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
892 /// getOrCreate - Return the specified constant from the map, creating it if
894 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
895 sys::SmartScopedLock<true> Lock(ValueMapLock);
896 MapKey Lookup(Ty, V);
897 ConstantClass* Result = 0;
899 typename MapTy::iterator I = Map.find(Lookup);
902 Result = static_cast<ConstantClass *>(I->second);
905 // If no preexisting value, create one now...
906 Result = Create(Ty, V, I);
912 void remove(ConstantClass *CP) {
913 sys::SmartScopedLock<true> Lock(ValueMapLock);
914 typename MapTy::iterator I = FindExistingElement(CP);
915 assert(I != Map.end() && "Constant not found in constant table!");
916 assert(I->second == CP && "Didn't find correct element?");
918 if (HasLargeKey) // Remember the reverse mapping if needed.
919 InverseMap.erase(CP);
921 // Now that we found the entry, make sure this isn't the entry that
922 // the AbstractTypeMap points to.
923 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
924 if (Ty->isAbstract()) {
925 assert(AbstractTypeMap.count(Ty) &&
926 "Abstract type not in AbstractTypeMap?");
927 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
928 if (ATMEntryIt == I) {
929 // Yes, we are removing the representative entry for this type.
930 // See if there are any other entries of the same type.
931 typename MapTy::iterator TmpIt = ATMEntryIt;
933 // First check the entry before this one...
934 if (TmpIt != Map.begin()) {
936 if (TmpIt->first.first != Ty) // Not the same type, move back...
940 // If we didn't find the same type, try to move forward...
941 if (TmpIt == ATMEntryIt) {
943 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
944 --TmpIt; // No entry afterwards with the same type
947 // If there is another entry in the map of the same abstract type,
948 // update the AbstractTypeMap entry now.
949 if (TmpIt != ATMEntryIt) {
952 // Otherwise, we are removing the last instance of this type
953 // from the table. Remove from the ATM, and from user list.
954 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
955 AbstractTypeMap.erase(Ty);
964 /// MoveConstantToNewSlot - If we are about to change C to be the element
965 /// specified by I, update our internal data structures to reflect this
967 /// NOTE: This function is not locked. It is the responsibility of the
968 /// caller to enforce proper synchronization if using this method.
969 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
970 // First, remove the old location of the specified constant in the map.
971 typename MapTy::iterator OldI = FindExistingElement(C);
972 assert(OldI != Map.end() && "Constant not found in constant table!");
973 assert(OldI->second == C && "Didn't find correct element?");
975 // If this constant is the representative element for its abstract type,
976 // update the AbstractTypeMap so that the representative element is I.
977 if (C->getType()->isAbstract()) {
978 typename AbstractTypeMapTy::iterator ATI =
979 AbstractTypeMap.find(C->getType());
980 assert(ATI != AbstractTypeMap.end() &&
981 "Abstract type not in AbstractTypeMap?");
982 if (ATI->second == OldI)
986 // Remove the old entry from the map.
989 // Update the inverse map so that we know that this constant is now
990 // located at descriptor I.
992 assert(I->second == C && "Bad inversemap entry!");
997 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
998 sys::SmartScopedLock<true> Lock(ValueMapLock);
999 typename AbstractTypeMapTy::iterator I =
1000 AbstractTypeMap.find(cast<Type>(OldTy));
1002 assert(I != AbstractTypeMap.end() &&
1003 "Abstract type not in AbstractTypeMap?");
1005 // Convert a constant at a time until the last one is gone. The last one
1006 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1007 // eliminated eventually.
1009 ConvertConstantType<ConstantClass,
1010 TypeClass>::convert(
1011 static_cast<ConstantClass *>(I->second->second),
1012 cast<TypeClass>(NewTy));
1014 I = AbstractTypeMap.find(cast<Type>(OldTy));
1015 } while (I != AbstractTypeMap.end());
1018 // If the type became concrete without being refined to any other existing
1019 // type, we just remove ourselves from the ATU list.
1020 void typeBecameConcrete(const DerivedType *AbsTy) {
1021 AbsTy->removeAbstractTypeUser(this);
1025 DOUT << "Constant.cpp: ValueMap\n";
1030 /// destroyConstant - Remove the constant from the constant table...
1032 void ConstantAggregateZero::destroyConstant() {
1033 // Implicitly locked.
1034 getType()->getContext().erase(this);
1035 destroyConstantImpl();
1038 /// destroyConstant - Remove the constant from the constant table...
1040 void ConstantArray::destroyConstant() {
1041 // Implicitly locked.
1042 getType()->getContext().erase(this);
1043 destroyConstantImpl();
1046 /// isString - This method returns true if the array is an array of i8, and
1047 /// if the elements of the array are all ConstantInt's.
1048 bool ConstantArray::isString() const {
1049 // Check the element type for i8...
1050 if (getType()->getElementType() != Type::Int8Ty)
1052 // Check the elements to make sure they are all integers, not constant
1054 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1055 if (!isa<ConstantInt>(getOperand(i)))
1060 /// isCString - This method returns true if the array is a string (see
1061 /// isString) and it ends in a null byte \\0 and does not contains any other
1062 /// null bytes except its terminator.
1063 bool ConstantArray::isCString() const {
1064 // Check the element type for i8...
1065 if (getType()->getElementType() != Type::Int8Ty)
1068 // Last element must be a null.
1069 if (!getOperand(getNumOperands()-1)->isNullValue())
1071 // Other elements must be non-null integers.
1072 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1073 if (!isa<ConstantInt>(getOperand(i)))
1075 if (getOperand(i)->isNullValue())
1082 /// getAsString - If the sub-element type of this array is i8
1083 /// then this method converts the array to an std::string and returns it.
1084 /// Otherwise, it asserts out.
1086 std::string ConstantArray::getAsString() const {
1087 assert(isString() && "Not a string!");
1089 Result.reserve(getNumOperands());
1090 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1091 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1096 //---- ConstantStruct::get() implementation...
1103 // destroyConstant - Remove the constant from the constant table...
1105 void ConstantStruct::destroyConstant() {
1106 // Implicitly locked.
1107 getType()->getContext().erase(this);
1108 destroyConstantImpl();
1111 // destroyConstant - Remove the constant from the constant table...
1113 void ConstantVector::destroyConstant() {
1114 // Implicitly locked.
1115 getType()->getContext().erase(this);
1116 destroyConstantImpl();
1119 /// This function will return true iff every element in this vector constant
1120 /// is set to all ones.
1121 /// @returns true iff this constant's emements are all set to all ones.
1122 /// @brief Determine if the value is all ones.
1123 bool ConstantVector::isAllOnesValue() const {
1124 // Check out first element.
1125 const Constant *Elt = getOperand(0);
1126 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1127 if (!CI || !CI->isAllOnesValue()) return false;
1128 // Then make sure all remaining elements point to the same value.
1129 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1130 if (getOperand(I) != Elt) return false;
1135 /// getSplatValue - If this is a splat constant, where all of the
1136 /// elements have the same value, return that value. Otherwise return null.
1137 Constant *ConstantVector::getSplatValue() {
1138 // Check out first element.
1139 Constant *Elt = getOperand(0);
1140 // Then make sure all remaining elements point to the same value.
1141 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1142 if (getOperand(I) != Elt) return 0;
1146 //---- ConstantPointerNull::get() implementation...
1150 // ConstantPointerNull does not take extra "value" argument...
1151 template<class ValType>
1152 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1153 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1154 return new ConstantPointerNull(Ty);
1159 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1160 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1161 // Make everyone now use a constant of the new type...
1162 Constant *New = ConstantPointerNull::get(NewTy);
1163 assert(New != OldC && "Didn't replace constant??");
1164 OldC->uncheckedReplaceAllUsesWith(New);
1165 OldC->destroyConstant(); // This constant is now dead, destroy it.
1170 static ManagedStatic<ValueMap<char, PointerType,
1171 ConstantPointerNull> > NullPtrConstants;
1173 static char getValType(ConstantPointerNull *) {
1178 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1179 // Implicitly locked.
1180 return NullPtrConstants->getOrCreate(Ty, 0);
1183 // destroyConstant - Remove the constant from the constant table...
1185 void ConstantPointerNull::destroyConstant() {
1186 // Implicitly locked.
1187 NullPtrConstants->remove(this);
1188 destroyConstantImpl();
1192 //---- UndefValue::get() implementation...
1196 // UndefValue does not take extra "value" argument...
1197 template<class ValType>
1198 struct ConstantCreator<UndefValue, Type, ValType> {
1199 static UndefValue *create(const Type *Ty, const ValType &V) {
1200 return new UndefValue(Ty);
1205 struct ConvertConstantType<UndefValue, Type> {
1206 static void convert(UndefValue *OldC, const Type *NewTy) {
1207 // Make everyone now use a constant of the new type.
1208 Constant *New = UndefValue::get(NewTy);
1209 assert(New != OldC && "Didn't replace constant??");
1210 OldC->uncheckedReplaceAllUsesWith(New);
1211 OldC->destroyConstant(); // This constant is now dead, destroy it.
1216 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1218 static char getValType(UndefValue *) {
1223 UndefValue *UndefValue::get(const Type *Ty) {
1224 // Implicitly locked.
1225 return UndefValueConstants->getOrCreate(Ty, 0);
1228 // destroyConstant - Remove the constant from the constant table.
1230 void UndefValue::destroyConstant() {
1231 // Implicitly locked.
1232 UndefValueConstants->remove(this);
1233 destroyConstantImpl();
1236 //---- MDNode::get() implementation
1239 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1240 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1241 for (unsigned i = 0; i != NumVals; ++i)
1242 Node.push_back(WeakVH(Vals[i]));
1245 void MDNode::Profile(FoldingSetNodeID &ID) const {
1246 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1250 //---- ConstantExpr::get() implementations...
1255 struct ExprMapKeyType {
1256 typedef SmallVector<unsigned, 4> IndexList;
1258 ExprMapKeyType(unsigned opc,
1259 const std::vector<Constant*> &ops,
1260 unsigned short pred = 0,
1261 const IndexList &inds = IndexList())
1262 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1265 std::vector<Constant*> operands;
1267 bool operator==(const ExprMapKeyType& that) const {
1268 return this->opcode == that.opcode &&
1269 this->predicate == that.predicate &&
1270 this->operands == that.operands &&
1271 this->indices == that.indices;
1273 bool operator<(const ExprMapKeyType & that) const {
1274 return this->opcode < that.opcode ||
1275 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1276 (this->opcode == that.opcode && this->predicate == that.predicate &&
1277 this->operands < that.operands) ||
1278 (this->opcode == that.opcode && this->predicate == that.predicate &&
1279 this->operands == that.operands && this->indices < that.indices);
1282 bool operator!=(const ExprMapKeyType& that) const {
1283 return !(*this == that);
1291 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1292 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1293 unsigned short pred = 0) {
1294 if (Instruction::isCast(V.opcode))
1295 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1296 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1297 V.opcode < Instruction::BinaryOpsEnd))
1298 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1299 if (V.opcode == Instruction::Select)
1300 return new SelectConstantExpr(V.operands[0], V.operands[1],
1302 if (V.opcode == Instruction::ExtractElement)
1303 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1304 if (V.opcode == Instruction::InsertElement)
1305 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1307 if (V.opcode == Instruction::ShuffleVector)
1308 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1310 if (V.opcode == Instruction::InsertValue)
1311 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1313 if (V.opcode == Instruction::ExtractValue)
1314 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1315 if (V.opcode == Instruction::GetElementPtr) {
1316 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1317 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1320 // The compare instructions are weird. We have to encode the predicate
1321 // value and it is combined with the instruction opcode by multiplying
1322 // the opcode by one hundred. We must decode this to get the predicate.
1323 if (V.opcode == Instruction::ICmp)
1324 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1325 V.operands[0], V.operands[1]);
1326 if (V.opcode == Instruction::FCmp)
1327 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1328 V.operands[0], V.operands[1]);
1329 llvm_unreachable("Invalid ConstantExpr!");
1335 struct ConvertConstantType<ConstantExpr, Type> {
1336 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1338 switch (OldC->getOpcode()) {
1339 case Instruction::Trunc:
1340 case Instruction::ZExt:
1341 case Instruction::SExt:
1342 case Instruction::FPTrunc:
1343 case Instruction::FPExt:
1344 case Instruction::UIToFP:
1345 case Instruction::SIToFP:
1346 case Instruction::FPToUI:
1347 case Instruction::FPToSI:
1348 case Instruction::PtrToInt:
1349 case Instruction::IntToPtr:
1350 case Instruction::BitCast:
1351 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1354 case Instruction::Select:
1355 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1356 OldC->getOperand(1),
1357 OldC->getOperand(2));
1360 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1361 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1362 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1363 OldC->getOperand(1));
1365 case Instruction::GetElementPtr:
1366 // Make everyone now use a constant of the new type...
1367 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1368 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1369 &Idx[0], Idx.size());
1373 assert(New != OldC && "Didn't replace constant??");
1374 OldC->uncheckedReplaceAllUsesWith(New);
1375 OldC->destroyConstant(); // This constant is now dead, destroy it.
1378 } // end namespace llvm
1381 static ExprMapKeyType getValType(ConstantExpr *CE) {
1382 std::vector<Constant*> Operands;
1383 Operands.reserve(CE->getNumOperands());
1384 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1385 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1386 return ExprMapKeyType(CE->getOpcode(), Operands,
1387 CE->isCompare() ? CE->getPredicate() : 0,
1389 CE->getIndices() : SmallVector<unsigned, 4>());
1392 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1393 ConstantExpr> > ExprConstants;
1395 /// This is a utility function to handle folding of casts and lookup of the
1396 /// cast in the ExprConstants map. It is used by the various get* methods below.
1397 static inline Constant *getFoldedCast(
1398 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1399 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1400 // Fold a few common cases
1402 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1405 // Look up the constant in the table first to ensure uniqueness
1406 std::vector<Constant*> argVec(1, C);
1407 ExprMapKeyType Key(opc, argVec);
1409 // Implicitly locked.
1410 return ExprConstants->getOrCreate(Ty, Key);
1413 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1414 Instruction::CastOps opc = Instruction::CastOps(oc);
1415 assert(Instruction::isCast(opc) && "opcode out of range");
1416 assert(C && Ty && "Null arguments to getCast");
1417 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1421 llvm_unreachable("Invalid cast opcode");
1423 case Instruction::Trunc: return getTrunc(C, Ty);
1424 case Instruction::ZExt: return getZExt(C, Ty);
1425 case Instruction::SExt: return getSExt(C, Ty);
1426 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1427 case Instruction::FPExt: return getFPExtend(C, Ty);
1428 case Instruction::UIToFP: return getUIToFP(C, Ty);
1429 case Instruction::SIToFP: return getSIToFP(C, Ty);
1430 case Instruction::FPToUI: return getFPToUI(C, Ty);
1431 case Instruction::FPToSI: return getFPToSI(C, Ty);
1432 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1433 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1434 case Instruction::BitCast: return getBitCast(C, Ty);
1439 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1440 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1441 return getCast(Instruction::BitCast, C, Ty);
1442 return getCast(Instruction::ZExt, C, Ty);
1445 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1446 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1447 return getCast(Instruction::BitCast, C, Ty);
1448 return getCast(Instruction::SExt, C, Ty);
1451 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1452 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1453 return getCast(Instruction::BitCast, C, Ty);
1454 return getCast(Instruction::Trunc, C, Ty);
1457 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1458 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1459 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1461 if (Ty->isInteger())
1462 return getCast(Instruction::PtrToInt, S, Ty);
1463 return getCast(Instruction::BitCast, S, Ty);
1466 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1468 assert(C->getType()->isIntOrIntVector() &&
1469 Ty->isIntOrIntVector() && "Invalid cast");
1470 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1471 unsigned DstBits = Ty->getScalarSizeInBits();
1472 Instruction::CastOps opcode =
1473 (SrcBits == DstBits ? Instruction::BitCast :
1474 (SrcBits > DstBits ? Instruction::Trunc :
1475 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1476 return getCast(opcode, C, Ty);
1479 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1480 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1482 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1483 unsigned DstBits = Ty->getScalarSizeInBits();
1484 if (SrcBits == DstBits)
1485 return C; // Avoid a useless cast
1486 Instruction::CastOps opcode =
1487 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1488 return getCast(opcode, C, Ty);
1491 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1493 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1494 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1496 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1497 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1498 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1499 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1500 "SrcTy must be larger than DestTy for Trunc!");
1502 return getFoldedCast(Instruction::Trunc, C, Ty);
1505 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1507 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1508 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1510 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1511 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1512 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1513 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1514 "SrcTy must be smaller than DestTy for SExt!");
1516 return getFoldedCast(Instruction::SExt, C, Ty);
1519 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1521 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1522 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1524 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1525 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1526 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1527 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1528 "SrcTy must be smaller than DestTy for ZExt!");
1530 return getFoldedCast(Instruction::ZExt, C, Ty);
1533 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1535 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1536 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1538 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1539 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1540 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1541 "This is an illegal floating point truncation!");
1542 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1545 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1547 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1548 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1550 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1551 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1552 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1553 "This is an illegal floating point extension!");
1554 return getFoldedCast(Instruction::FPExt, C, Ty);
1557 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1559 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1560 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1562 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1563 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1564 "This is an illegal uint to floating point cast!");
1565 return getFoldedCast(Instruction::UIToFP, C, Ty);
1568 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1570 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1571 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1573 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1574 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1575 "This is an illegal sint to floating point cast!");
1576 return getFoldedCast(Instruction::SIToFP, C, Ty);
1579 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1581 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1582 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1584 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1585 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1586 "This is an illegal floating point to uint cast!");
1587 return getFoldedCast(Instruction::FPToUI, C, Ty);
1590 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1592 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1593 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1595 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1596 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1597 "This is an illegal floating point to sint cast!");
1598 return getFoldedCast(Instruction::FPToSI, C, Ty);
1601 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1602 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1603 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1604 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1607 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1608 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1609 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1610 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1613 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1614 // BitCast implies a no-op cast of type only. No bits change. However, you
1615 // can't cast pointers to anything but pointers.
1617 const Type *SrcTy = C->getType();
1618 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1619 "BitCast cannot cast pointer to non-pointer and vice versa");
1621 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1622 // or nonptr->ptr). For all the other types, the cast is okay if source and
1623 // destination bit widths are identical.
1624 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1625 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1627 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1629 // It is common to ask for a bitcast of a value to its own type, handle this
1631 if (C->getType() == DstTy) return C;
1633 return getFoldedCast(Instruction::BitCast, C, DstTy);
1636 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1637 Constant *C1, Constant *C2) {
1638 // Check the operands for consistency first
1639 assert(Opcode >= Instruction::BinaryOpsBegin &&
1640 Opcode < Instruction::BinaryOpsEnd &&
1641 "Invalid opcode in binary constant expression");
1642 assert(C1->getType() == C2->getType() &&
1643 "Operand types in binary constant expression should match");
1645 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1646 if (Constant *FC = ConstantFoldBinaryInstruction(
1647 getGlobalContext(), Opcode, C1, C2))
1648 return FC; // Fold a few common cases...
1650 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1651 ExprMapKeyType Key(Opcode, argVec);
1653 // Implicitly locked.
1654 return ExprConstants->getOrCreate(ReqTy, Key);
1657 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1658 Constant *C1, Constant *C2) {
1659 switch (predicate) {
1660 default: llvm_unreachable("Invalid CmpInst predicate");
1661 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1662 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1663 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1664 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1665 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1666 case CmpInst::FCMP_TRUE:
1667 return getFCmp(predicate, C1, C2);
1669 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1670 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1671 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1672 case CmpInst::ICMP_SLE:
1673 return getICmp(predicate, C1, C2);
1677 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1678 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1679 if (C1->getType()->isFPOrFPVector()) {
1680 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1681 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1682 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1686 case Instruction::Add:
1687 case Instruction::Sub:
1688 case Instruction::Mul:
1689 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1690 assert(C1->getType()->isIntOrIntVector() &&
1691 "Tried to create an integer operation on a non-integer type!");
1693 case Instruction::FAdd:
1694 case Instruction::FSub:
1695 case Instruction::FMul:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert(C1->getType()->isFPOrFPVector() &&
1698 "Tried to create a floating-point operation on a "
1699 "non-floating-point type!");
1701 case Instruction::UDiv:
1702 case Instruction::SDiv:
1703 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1704 assert(C1->getType()->isIntOrIntVector() &&
1705 "Tried to create an arithmetic operation on a non-arithmetic type!");
1707 case Instruction::FDiv:
1708 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1709 assert(C1->getType()->isFPOrFPVector() &&
1710 "Tried to create an arithmetic operation on a non-arithmetic type!");
1712 case Instruction::URem:
1713 case Instruction::SRem:
1714 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1715 assert(C1->getType()->isIntOrIntVector() &&
1716 "Tried to create an arithmetic operation on a non-arithmetic type!");
1718 case Instruction::FRem:
1719 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1720 assert(C1->getType()->isFPOrFPVector() &&
1721 "Tried to create an arithmetic operation on a non-arithmetic type!");
1723 case Instruction::And:
1724 case Instruction::Or:
1725 case Instruction::Xor:
1726 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1727 assert(C1->getType()->isIntOrIntVector() &&
1728 "Tried to create a logical operation on a non-integral type!");
1730 case Instruction::Shl:
1731 case Instruction::LShr:
1732 case Instruction::AShr:
1733 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1734 assert(C1->getType()->isIntOrIntVector() &&
1735 "Tried to create a shift operation on a non-integer type!");
1742 return getTy(C1->getType(), Opcode, C1, C2);
1745 Constant *ConstantExpr::getCompare(unsigned short pred,
1746 Constant *C1, Constant *C2) {
1747 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1748 return getCompareTy(pred, C1, C2);
1751 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1752 Constant *V1, Constant *V2) {
1753 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1755 if (ReqTy == V1->getType())
1756 if (Constant *SC = ConstantFoldSelectInstruction(
1757 getGlobalContext(), C, V1, V2))
1758 return SC; // Fold common cases
1760 std::vector<Constant*> argVec(3, C);
1763 ExprMapKeyType Key(Instruction::Select, argVec);
1765 // Implicitly locked.
1766 return ExprConstants->getOrCreate(ReqTy, Key);
1769 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1772 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1774 cast<PointerType>(ReqTy)->getElementType() &&
1775 "GEP indices invalid!");
1777 if (Constant *FC = ConstantFoldGetElementPtr(
1778 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1779 return FC; // Fold a few common cases...
1781 assert(isa<PointerType>(C->getType()) &&
1782 "Non-pointer type for constant GetElementPtr expression");
1783 // Look up the constant in the table first to ensure uniqueness
1784 std::vector<Constant*> ArgVec;
1785 ArgVec.reserve(NumIdx+1);
1786 ArgVec.push_back(C);
1787 for (unsigned i = 0; i != NumIdx; ++i)
1788 ArgVec.push_back(cast<Constant>(Idxs[i]));
1789 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1791 // Implicitly locked.
1792 return ExprConstants->getOrCreate(ReqTy, Key);
1795 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1797 // Get the result type of the getelementptr!
1799 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1800 assert(Ty && "GEP indices invalid!");
1801 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1802 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1805 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1807 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1812 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1813 assert(LHS->getType() == RHS->getType());
1814 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1815 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1817 if (Constant *FC = ConstantFoldCompareInstruction(
1818 getGlobalContext(),pred, LHS, RHS))
1819 return FC; // Fold a few common cases...
1821 // Look up the constant in the table first to ensure uniqueness
1822 std::vector<Constant*> ArgVec;
1823 ArgVec.push_back(LHS);
1824 ArgVec.push_back(RHS);
1825 // Get the key type with both the opcode and predicate
1826 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1828 // Implicitly locked.
1829 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1833 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1834 assert(LHS->getType() == RHS->getType());
1835 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1837 if (Constant *FC = ConstantFoldCompareInstruction(
1838 getGlobalContext(), pred, LHS, RHS))
1839 return FC; // Fold a few common cases...
1841 // Look up the constant in the table first to ensure uniqueness
1842 std::vector<Constant*> ArgVec;
1843 ArgVec.push_back(LHS);
1844 ArgVec.push_back(RHS);
1845 // Get the key type with both the opcode and predicate
1846 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1848 // Implicitly locked.
1849 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1852 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1854 if (Constant *FC = ConstantFoldExtractElementInstruction(
1855 getGlobalContext(), Val, Idx))
1856 return FC; // Fold a few common cases...
1857 // Look up the constant in the table first to ensure uniqueness
1858 std::vector<Constant*> ArgVec(1, Val);
1859 ArgVec.push_back(Idx);
1860 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1862 // Implicitly locked.
1863 return ExprConstants->getOrCreate(ReqTy, Key);
1866 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1867 assert(isa<VectorType>(Val->getType()) &&
1868 "Tried to create extractelement operation on non-vector type!");
1869 assert(Idx->getType() == Type::Int32Ty &&
1870 "Extractelement index must be i32 type!");
1871 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1875 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1876 Constant *Elt, Constant *Idx) {
1877 if (Constant *FC = ConstantFoldInsertElementInstruction(
1878 getGlobalContext(), Val, Elt, Idx))
1879 return FC; // Fold a few common cases...
1880 // Look up the constant in the table first to ensure uniqueness
1881 std::vector<Constant*> ArgVec(1, Val);
1882 ArgVec.push_back(Elt);
1883 ArgVec.push_back(Idx);
1884 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1886 // Implicitly locked.
1887 return ExprConstants->getOrCreate(ReqTy, Key);
1890 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1892 assert(isa<VectorType>(Val->getType()) &&
1893 "Tried to create insertelement operation on non-vector type!");
1894 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1895 && "Insertelement types must match!");
1896 assert(Idx->getType() == Type::Int32Ty &&
1897 "Insertelement index must be i32 type!");
1898 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1901 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1902 Constant *V2, Constant *Mask) {
1903 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1904 getGlobalContext(), V1, V2, Mask))
1905 return FC; // Fold a few common cases...
1906 // Look up the constant in the table first to ensure uniqueness
1907 std::vector<Constant*> ArgVec(1, V1);
1908 ArgVec.push_back(V2);
1909 ArgVec.push_back(Mask);
1910 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1912 // Implicitly locked.
1913 return ExprConstants->getOrCreate(ReqTy, Key);
1916 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1918 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1919 "Invalid shuffle vector constant expr operands!");
1921 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1922 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1923 const Type *ShufTy = VectorType::get(EltTy, NElts);
1924 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1927 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1929 const unsigned *Idxs, unsigned NumIdx) {
1930 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1931 Idxs+NumIdx) == Val->getType() &&
1932 "insertvalue indices invalid!");
1933 assert(Agg->getType() == ReqTy &&
1934 "insertvalue type invalid!");
1935 assert(Agg->getType()->isFirstClassType() &&
1936 "Non-first-class type for constant InsertValue expression");
1937 Constant *FC = ConstantFoldInsertValueInstruction(
1938 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1939 assert(FC && "InsertValue constant expr couldn't be folded!");
1943 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1944 const unsigned *IdxList, unsigned NumIdx) {
1945 assert(Agg->getType()->isFirstClassType() &&
1946 "Tried to create insertelement operation on non-first-class type!");
1948 const Type *ReqTy = Agg->getType();
1951 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1953 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1954 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1957 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1958 const unsigned *Idxs, unsigned NumIdx) {
1959 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1960 Idxs+NumIdx) == ReqTy &&
1961 "extractvalue indices invalid!");
1962 assert(Agg->getType()->isFirstClassType() &&
1963 "Non-first-class type for constant extractvalue expression");
1964 Constant *FC = ConstantFoldExtractValueInstruction(
1965 getGlobalContext(), Agg, Idxs, NumIdx);
1966 assert(FC && "ExtractValue constant expr couldn't be folded!");
1970 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1971 const unsigned *IdxList, unsigned NumIdx) {
1972 assert(Agg->getType()->isFirstClassType() &&
1973 "Tried to create extractelement operation on non-first-class type!");
1976 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1977 assert(ReqTy && "extractvalue indices invalid!");
1978 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1981 // destroyConstant - Remove the constant from the constant table...
1983 void ConstantExpr::destroyConstant() {
1984 // Implicitly locked.
1985 ExprConstants->remove(this);
1986 destroyConstantImpl();
1989 const char *ConstantExpr::getOpcodeName() const {
1990 return Instruction::getOpcodeName(getOpcode());
1993 //===----------------------------------------------------------------------===//
1994 // replaceUsesOfWithOnConstant implementations
1996 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1997 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2000 /// Note that we intentionally replace all uses of From with To here. Consider
2001 /// a large array that uses 'From' 1000 times. By handling this case all here,
2002 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2003 /// single invocation handles all 1000 uses. Handling them one at a time would
2004 /// work, but would be really slow because it would have to unique each updated
2006 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2008 Constant *Replacement =
2009 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2011 if (!Replacement) return;
2013 // Otherwise, I do need to replace this with an existing value.
2014 assert(Replacement != this && "I didn't contain From!");
2016 // Everyone using this now uses the replacement.
2017 uncheckedReplaceAllUsesWith(Replacement);
2019 // Delete the old constant!
2023 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2025 Constant* Replacement =
2026 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2027 if (!Replacement) return;
2029 // Everyone using this now uses the replacement.
2030 uncheckedReplaceAllUsesWith(Replacement);
2032 // Delete the old constant!
2036 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2038 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2040 std::vector<Constant*> Values;
2041 Values.reserve(getNumOperands()); // Build replacement array...
2042 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2043 Constant *Val = getOperand(i);
2044 if (Val == From) Val = cast<Constant>(To);
2045 Values.push_back(Val);
2048 Constant *Replacement =
2049 getType()->getContext().getConstantVector(getType(), Values);
2050 assert(Replacement != this && "I didn't contain From!");
2052 // Everyone using this now uses the replacement.
2053 uncheckedReplaceAllUsesWith(Replacement);
2055 // Delete the old constant!
2059 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2061 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2062 Constant *To = cast<Constant>(ToV);
2064 Constant *Replacement = 0;
2065 if (getOpcode() == Instruction::GetElementPtr) {
2066 SmallVector<Constant*, 8> Indices;
2067 Constant *Pointer = getOperand(0);
2068 Indices.reserve(getNumOperands()-1);
2069 if (Pointer == From) Pointer = To;
2071 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2072 Constant *Val = getOperand(i);
2073 if (Val == From) Val = To;
2074 Indices.push_back(Val);
2076 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2077 &Indices[0], Indices.size());
2078 } else if (getOpcode() == Instruction::ExtractValue) {
2079 Constant *Agg = getOperand(0);
2080 if (Agg == From) Agg = To;
2082 const SmallVector<unsigned, 4> &Indices = getIndices();
2083 Replacement = ConstantExpr::getExtractValue(Agg,
2084 &Indices[0], Indices.size());
2085 } else if (getOpcode() == Instruction::InsertValue) {
2086 Constant *Agg = getOperand(0);
2087 Constant *Val = getOperand(1);
2088 if (Agg == From) Agg = To;
2089 if (Val == From) Val = To;
2091 const SmallVector<unsigned, 4> &Indices = getIndices();
2092 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2093 &Indices[0], Indices.size());
2094 } else if (isCast()) {
2095 assert(getOperand(0) == From && "Cast only has one use!");
2096 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2097 } else if (getOpcode() == Instruction::Select) {
2098 Constant *C1 = getOperand(0);
2099 Constant *C2 = getOperand(1);
2100 Constant *C3 = getOperand(2);
2101 if (C1 == From) C1 = To;
2102 if (C2 == From) C2 = To;
2103 if (C3 == From) C3 = To;
2104 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2105 } else if (getOpcode() == Instruction::ExtractElement) {
2106 Constant *C1 = getOperand(0);
2107 Constant *C2 = getOperand(1);
2108 if (C1 == From) C1 = To;
2109 if (C2 == From) C2 = To;
2110 Replacement = ConstantExpr::getExtractElement(C1, C2);
2111 } else if (getOpcode() == Instruction::InsertElement) {
2112 Constant *C1 = getOperand(0);
2113 Constant *C2 = getOperand(1);
2114 Constant *C3 = getOperand(1);
2115 if (C1 == From) C1 = To;
2116 if (C2 == From) C2 = To;
2117 if (C3 == From) C3 = To;
2118 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2119 } else if (getOpcode() == Instruction::ShuffleVector) {
2120 Constant *C1 = getOperand(0);
2121 Constant *C2 = getOperand(1);
2122 Constant *C3 = getOperand(2);
2123 if (C1 == From) C1 = To;
2124 if (C2 == From) C2 = To;
2125 if (C3 == From) C3 = To;
2126 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2127 } else if (isCompare()) {
2128 Constant *C1 = getOperand(0);
2129 Constant *C2 = getOperand(1);
2130 if (C1 == From) C1 = To;
2131 if (C2 == From) C2 = To;
2132 if (getOpcode() == Instruction::ICmp)
2133 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2135 assert(getOpcode() == Instruction::FCmp);
2136 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2138 } else if (getNumOperands() == 2) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 if (C1 == From) C1 = To;
2142 if (C2 == From) C2 = To;
2143 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2145 llvm_unreachable("Unknown ConstantExpr type!");
2149 assert(Replacement != this && "I didn't contain From!");
2151 // Everyone using this now uses the replacement.
2152 uncheckedReplaceAllUsesWith(Replacement);
2154 // Delete the old constant!
2158 void MDNode::replaceElement(Value *From, Value *To) {
2159 SmallVector<Value*, 4> Values;
2160 Values.reserve(getNumElements()); // Build replacement array...
2161 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2162 Value *Val = getElement(i);
2163 if (Val == From) Val = To;
2164 Values.push_back(Val);
2167 MDNode *Replacement =
2168 getType()->getContext().getMDNode(&Values[0], Values.size());
2169 assert(Replacement != this && "I didn't contain From!");
2171 uncheckedReplaceAllUsesWith(Replacement);