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())
104 /// ContainsRelocations - Return true if the constant value contains relocations
105 /// which cannot be resolved at compile time. Kind argument is used to filter
106 /// only 'interesting' sorts of relocations.
107 bool Constant::ContainsRelocations(unsigned Kind) const {
108 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
109 bool isLocal = GV->hasLocalLinkage();
110 if ((Kind & Reloc::Local) && isLocal) {
111 // Global has local linkage and 'local' kind of relocations are
116 if ((Kind & Reloc::Global) && !isLocal) {
117 // Global has non-local linkage and 'global' kind of relocations are
125 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
126 if (getOperand(i)->ContainsRelocations(Kind))
132 /// getVectorElements - This method, which is only valid on constant of vector
133 /// type, returns the elements of the vector in the specified smallvector.
134 /// This handles breaking down a vector undef into undef elements, etc. For
135 /// constant exprs and other cases we can't handle, we return an empty vector.
136 void Constant::getVectorElements(LLVMContext &Context,
137 SmallVectorImpl<Constant*> &Elts) const {
138 assert(isa<VectorType>(getType()) && "Not a vector constant!");
140 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
141 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
142 Elts.push_back(CV->getOperand(i));
146 const VectorType *VT = cast<VectorType>(getType());
147 if (isa<ConstantAggregateZero>(this)) {
148 Elts.assign(VT->getNumElements(),
149 Context.getNullValue(VT->getElementType()));
153 if (isa<UndefValue>(this)) {
154 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
158 // Unknown type, must be constant expr etc.
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
167 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
168 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
169 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
172 ConstantInt *ConstantInt::TheTrueVal = 0;
173 ConstantInt *ConstantInt::TheFalseVal = 0;
176 void CleanupTrueFalse(void *) {
177 ConstantInt::ResetTrueFalse();
181 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
183 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
184 assert(TheTrueVal == 0 && TheFalseVal == 0);
185 TheTrueVal = getGlobalContext().getConstantInt(Type::Int1Ty, 1);
186 TheFalseVal = getGlobalContext().getConstantInt(Type::Int1Ty, 0);
188 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
189 TrueFalseCleanup.Register();
191 return WhichOne ? TheTrueVal : TheFalseVal;
194 //===----------------------------------------------------------------------===//
196 //===----------------------------------------------------------------------===//
199 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
200 if (Ty == Type::FloatTy)
201 return &APFloat::IEEEsingle;
202 if (Ty == Type::DoubleTy)
203 return &APFloat::IEEEdouble;
204 if (Ty == Type::X86_FP80Ty)
205 return &APFloat::x87DoubleExtended;
206 else if (Ty == Type::FP128Ty)
207 return &APFloat::IEEEquad;
209 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
210 return &APFloat::PPCDoubleDouble;
214 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
215 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
216 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
220 bool ConstantFP::isNullValue() const {
221 return Val.isZero() && !Val.isNegative();
224 bool ConstantFP::isExactlyValue(const APFloat& V) const {
225 return Val.bitwiseIsEqual(V);
228 //===----------------------------------------------------------------------===//
229 // ConstantXXX Classes
230 //===----------------------------------------------------------------------===//
233 ConstantArray::ConstantArray(const ArrayType *T,
234 const std::vector<Constant*> &V)
235 : Constant(T, ConstantArrayVal,
236 OperandTraits<ConstantArray>::op_end(this) - V.size(),
238 assert(V.size() == T->getNumElements() &&
239 "Invalid initializer vector for constant array");
240 Use *OL = OperandList;
241 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
244 assert((C->getType() == T->getElementType() ||
246 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
247 "Initializer for array element doesn't match array element type!");
253 ConstantStruct::ConstantStruct(const StructType *T,
254 const std::vector<Constant*> &V)
255 : Constant(T, ConstantStructVal,
256 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
258 assert(V.size() == T->getNumElements() &&
259 "Invalid initializer vector for constant structure");
260 Use *OL = OperandList;
261 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
264 assert((C->getType() == T->getElementType(I-V.begin()) ||
265 ((T->getElementType(I-V.begin())->isAbstract() ||
266 C->getType()->isAbstract()) &&
267 T->getElementType(I-V.begin())->getTypeID() ==
268 C->getType()->getTypeID())) &&
269 "Initializer for struct element doesn't match struct element type!");
275 ConstantVector::ConstantVector(const VectorType *T,
276 const std::vector<Constant*> &V)
277 : Constant(T, ConstantVectorVal,
278 OperandTraits<ConstantVector>::op_end(this) - V.size(),
280 Use *OL = OperandList;
281 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
284 assert((C->getType() == T->getElementType() ||
286 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
287 "Initializer for vector element doesn't match vector element type!");
294 // We declare several classes private to this file, so use an anonymous
298 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
299 /// behind the scenes to implement unary constant exprs.
300 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
301 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
303 // allocate space for exactly one operand
304 void *operator new(size_t s) {
305 return User::operator new(s, 1);
307 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
308 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
311 /// Transparently provide more efficient getOperand methods.
312 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
315 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
316 /// behind the scenes to implement binary constant exprs.
317 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
318 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
320 // allocate space for exactly two operands
321 void *operator new(size_t s) {
322 return User::operator new(s, 2);
324 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
325 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
329 /// Transparently provide more efficient getOperand methods.
330 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
333 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
334 /// behind the scenes to implement select constant exprs.
335 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
336 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
338 // allocate space for exactly three operands
339 void *operator new(size_t s) {
340 return User::operator new(s, 3);
342 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
343 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
348 /// Transparently provide more efficient getOperand methods.
349 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
352 /// ExtractElementConstantExpr - This class is private to
353 /// Constants.cpp, and is used behind the scenes to implement
354 /// extractelement constant exprs.
355 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
356 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
358 // allocate space for exactly two operands
359 void *operator new(size_t s) {
360 return User::operator new(s, 2);
362 ExtractElementConstantExpr(Constant *C1, Constant *C2)
363 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
364 Instruction::ExtractElement, &Op<0>(), 2) {
368 /// Transparently provide more efficient getOperand methods.
369 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
372 /// InsertElementConstantExpr - This class is private to
373 /// Constants.cpp, and is used behind the scenes to implement
374 /// insertelement constant exprs.
375 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
376 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
378 // allocate space for exactly three operands
379 void *operator new(size_t s) {
380 return User::operator new(s, 3);
382 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
383 : ConstantExpr(C1->getType(), Instruction::InsertElement,
389 /// Transparently provide more efficient getOperand methods.
390 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
393 /// ShuffleVectorConstantExpr - This class is private to
394 /// Constants.cpp, and is used behind the scenes to implement
395 /// shufflevector constant exprs.
396 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
397 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
399 // allocate space for exactly three operands
400 void *operator new(size_t s) {
401 return User::operator new(s, 3);
403 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
404 : ConstantExpr(VectorType::get(
405 cast<VectorType>(C1->getType())->getElementType(),
406 cast<VectorType>(C3->getType())->getNumElements()),
407 Instruction::ShuffleVector,
413 /// Transparently provide more efficient getOperand methods.
414 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
417 /// ExtractValueConstantExpr - This class is private to
418 /// Constants.cpp, and is used behind the scenes to implement
419 /// extractvalue constant exprs.
420 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
421 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
423 // allocate space for exactly one operand
424 void *operator new(size_t s) {
425 return User::operator new(s, 1);
427 ExtractValueConstantExpr(Constant *Agg,
428 const SmallVector<unsigned, 4> &IdxList,
430 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
435 /// Indices - These identify which value to extract.
436 const SmallVector<unsigned, 4> Indices;
438 /// Transparently provide more efficient getOperand methods.
439 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
442 /// InsertValueConstantExpr - This class is private to
443 /// Constants.cpp, and is used behind the scenes to implement
444 /// insertvalue constant exprs.
445 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
446 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
448 // allocate space for exactly one operand
449 void *operator new(size_t s) {
450 return User::operator new(s, 2);
452 InsertValueConstantExpr(Constant *Agg, Constant *Val,
453 const SmallVector<unsigned, 4> &IdxList,
455 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
461 /// Indices - These identify the position for the insertion.
462 const SmallVector<unsigned, 4> Indices;
464 /// Transparently provide more efficient getOperand methods.
465 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
469 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
470 /// used behind the scenes to implement getelementpr constant exprs.
471 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
472 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
475 static GetElementPtrConstantExpr *Create(Constant *C,
476 const std::vector<Constant*>&IdxList,
477 const Type *DestTy) {
479 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
481 /// Transparently provide more efficient getOperand methods.
482 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
485 // CompareConstantExpr - This class is private to Constants.cpp, and is used
486 // behind the scenes to implement ICmp and FCmp constant expressions. This is
487 // needed in order to store the predicate value for these instructions.
488 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
489 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
490 // allocate space for exactly two operands
491 void *operator new(size_t s) {
492 return User::operator new(s, 2);
494 unsigned short predicate;
495 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
496 unsigned short pred, Constant* LHS, Constant* RHS)
497 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
501 /// Transparently provide more efficient getOperand methods.
502 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
505 } // end anonymous namespace
508 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
510 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
513 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
515 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
518 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
520 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
523 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
525 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
528 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
530 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
533 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
535 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
538 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
540 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
543 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
545 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
548 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
551 GetElementPtrConstantExpr::GetElementPtrConstantExpr
553 const std::vector<Constant*> &IdxList,
555 : ConstantExpr(DestTy, Instruction::GetElementPtr,
556 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
557 - (IdxList.size()+1),
560 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
561 OperandList[i+1] = IdxList[i];
564 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
568 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
570 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
573 } // End llvm namespace
576 // Utility function for determining if a ConstantExpr is a CastOp or not. This
577 // can't be inline because we don't want to #include Instruction.h into
579 bool ConstantExpr::isCast() const {
580 return Instruction::isCast(getOpcode());
583 bool ConstantExpr::isCompare() const {
584 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
587 bool ConstantExpr::hasIndices() const {
588 return getOpcode() == Instruction::ExtractValue ||
589 getOpcode() == Instruction::InsertValue;
592 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
593 if (const ExtractValueConstantExpr *EVCE =
594 dyn_cast<ExtractValueConstantExpr>(this))
595 return EVCE->Indices;
597 return cast<InsertValueConstantExpr>(this)->Indices;
600 unsigned ConstantExpr::getPredicate() const {
601 assert(getOpcode() == Instruction::FCmp ||
602 getOpcode() == Instruction::ICmp);
603 return ((const CompareConstantExpr*)this)->predicate;
606 /// getWithOperandReplaced - Return a constant expression identical to this
607 /// one, but with the specified operand set to the specified value.
609 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
610 assert(OpNo < getNumOperands() && "Operand num is out of range!");
611 assert(Op->getType() == getOperand(OpNo)->getType() &&
612 "Replacing operand with value of different type!");
613 if (getOperand(OpNo) == Op)
614 return const_cast<ConstantExpr*>(this);
616 Constant *Op0, *Op1, *Op2;
617 switch (getOpcode()) {
618 case Instruction::Trunc:
619 case Instruction::ZExt:
620 case Instruction::SExt:
621 case Instruction::FPTrunc:
622 case Instruction::FPExt:
623 case Instruction::UIToFP:
624 case Instruction::SIToFP:
625 case Instruction::FPToUI:
626 case Instruction::FPToSI:
627 case Instruction::PtrToInt:
628 case Instruction::IntToPtr:
629 case Instruction::BitCast:
630 return ConstantExpr::getCast(getOpcode(), Op, getType());
631 case Instruction::Select:
632 Op0 = (OpNo == 0) ? Op : getOperand(0);
633 Op1 = (OpNo == 1) ? Op : getOperand(1);
634 Op2 = (OpNo == 2) ? Op : getOperand(2);
635 return ConstantExpr::getSelect(Op0, Op1, Op2);
636 case Instruction::InsertElement:
637 Op0 = (OpNo == 0) ? Op : getOperand(0);
638 Op1 = (OpNo == 1) ? Op : getOperand(1);
639 Op2 = (OpNo == 2) ? Op : getOperand(2);
640 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
641 case Instruction::ExtractElement:
642 Op0 = (OpNo == 0) ? Op : getOperand(0);
643 Op1 = (OpNo == 1) ? Op : getOperand(1);
644 return ConstantExpr::getExtractElement(Op0, Op1);
645 case Instruction::ShuffleVector:
646 Op0 = (OpNo == 0) ? Op : getOperand(0);
647 Op1 = (OpNo == 1) ? Op : getOperand(1);
648 Op2 = (OpNo == 2) ? Op : getOperand(2);
649 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
650 case Instruction::GetElementPtr: {
651 SmallVector<Constant*, 8> Ops;
652 Ops.resize(getNumOperands()-1);
653 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
654 Ops[i-1] = getOperand(i);
656 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
658 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
661 assert(getNumOperands() == 2 && "Must be binary operator?");
662 Op0 = (OpNo == 0) ? Op : getOperand(0);
663 Op1 = (OpNo == 1) ? Op : getOperand(1);
664 return ConstantExpr::get(getOpcode(), Op0, Op1);
668 /// getWithOperands - This returns the current constant expression with the
669 /// operands replaced with the specified values. The specified operands must
670 /// match count and type with the existing ones.
671 Constant *ConstantExpr::
672 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
673 assert(NumOps == getNumOperands() && "Operand count mismatch!");
674 bool AnyChange = false;
675 for (unsigned i = 0; i != NumOps; ++i) {
676 assert(Ops[i]->getType() == getOperand(i)->getType() &&
677 "Operand type mismatch!");
678 AnyChange |= Ops[i] != getOperand(i);
680 if (!AnyChange) // No operands changed, return self.
681 return const_cast<ConstantExpr*>(this);
683 switch (getOpcode()) {
684 case Instruction::Trunc:
685 case Instruction::ZExt:
686 case Instruction::SExt:
687 case Instruction::FPTrunc:
688 case Instruction::FPExt:
689 case Instruction::UIToFP:
690 case Instruction::SIToFP:
691 case Instruction::FPToUI:
692 case Instruction::FPToSI:
693 case Instruction::PtrToInt:
694 case Instruction::IntToPtr:
695 case Instruction::BitCast:
696 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
697 case Instruction::Select:
698 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
699 case Instruction::InsertElement:
700 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
701 case Instruction::ExtractElement:
702 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
703 case Instruction::ShuffleVector:
704 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
705 case Instruction::GetElementPtr:
706 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
707 case Instruction::ICmp:
708 case Instruction::FCmp:
709 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
711 assert(getNumOperands() == 2 && "Must be binary operator?");
712 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
717 //===----------------------------------------------------------------------===//
718 // isValueValidForType implementations
720 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
721 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
722 if (Ty == Type::Int1Ty)
723 return Val == 0 || Val == 1;
725 return true; // always true, has to fit in largest type
726 uint64_t Max = (1ll << NumBits) - 1;
730 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
731 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
732 if (Ty == Type::Int1Ty)
733 return Val == 0 || Val == 1 || Val == -1;
735 return true; // always true, has to fit in largest type
736 int64_t Min = -(1ll << (NumBits-1));
737 int64_t Max = (1ll << (NumBits-1)) - 1;
738 return (Val >= Min && Val <= Max);
741 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
742 // convert modifies in place, so make a copy.
743 APFloat Val2 = APFloat(Val);
745 switch (Ty->getTypeID()) {
747 return false; // These can't be represented as floating point!
749 // FIXME rounding mode needs to be more flexible
750 case Type::FloatTyID: {
751 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
753 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
756 case Type::DoubleTyID: {
757 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
758 &Val2.getSemantics() == &APFloat::IEEEdouble)
760 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
763 case Type::X86_FP80TyID:
764 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
765 &Val2.getSemantics() == &APFloat::IEEEdouble ||
766 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
767 case Type::FP128TyID:
768 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
769 &Val2.getSemantics() == &APFloat::IEEEdouble ||
770 &Val2.getSemantics() == &APFloat::IEEEquad;
771 case Type::PPC_FP128TyID:
772 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
773 &Val2.getSemantics() == &APFloat::IEEEdouble ||
774 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
778 //===----------------------------------------------------------------------===//
779 // Factory Function Implementation
782 // The number of operands for each ConstantCreator::create method is
783 // determined by the ConstantTraits template.
784 // ConstantCreator - A class that is used to create constants by
785 // ValueMap*. This class should be partially specialized if there is
786 // something strange that needs to be done to interface to the ctor for the
790 template<class ValType>
791 struct ConstantTraits;
793 template<typename T, typename Alloc>
794 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
795 static unsigned uses(const std::vector<T, Alloc>& v) {
800 template<class ConstantClass, class TypeClass, class ValType>
801 struct VISIBILITY_HIDDEN ConstantCreator {
802 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
803 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
807 template<class ConstantClass, class TypeClass>
808 struct VISIBILITY_HIDDEN ConvertConstantType {
809 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
810 llvm_unreachable("This type cannot be converted!");
814 template<class ValType, class TypeClass, class ConstantClass,
815 bool HasLargeKey = false /*true for arrays and structs*/ >
816 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
818 typedef std::pair<const Type*, ValType> MapKey;
819 typedef std::map<MapKey, Constant *> MapTy;
820 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
821 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
823 /// Map - This is the main map from the element descriptor to the Constants.
824 /// This is the primary way we avoid creating two of the same shape
828 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
829 /// from the constants to their element in Map. This is important for
830 /// removal of constants from the array, which would otherwise have to scan
831 /// through the map with very large keys.
832 InverseMapTy InverseMap;
834 /// AbstractTypeMap - Map for abstract type constants.
836 AbstractTypeMapTy AbstractTypeMap;
838 /// ValueMapLock - Mutex for this map.
839 sys::SmartMutex<true> ValueMapLock;
842 // NOTE: This function is not locked. It is the caller's responsibility
843 // to enforce proper synchronization.
844 typename MapTy::iterator map_end() { return Map.end(); }
846 /// InsertOrGetItem - Return an iterator for the specified element.
847 /// If the element exists in the map, the returned iterator points to the
848 /// entry and Exists=true. If not, the iterator points to the newly
849 /// inserted entry and returns Exists=false. Newly inserted entries have
850 /// I->second == 0, and should be filled in.
851 /// NOTE: This function is not locked. It is the caller's responsibility
852 // to enforce proper synchronization.
853 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
856 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
862 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
864 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
865 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
866 IMI->second->second == CP &&
867 "InverseMap corrupt!");
871 typename MapTy::iterator I =
872 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
874 if (I == Map.end() || I->second != CP) {
875 // FIXME: This should not use a linear scan. If this gets to be a
876 // performance problem, someone should look at this.
877 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
883 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
884 typename MapTy::iterator I) {
885 ConstantClass* Result =
886 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
888 assert(Result->getType() == Ty && "Type specified is not correct!");
889 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
891 if (HasLargeKey) // Remember the reverse mapping if needed.
892 InverseMap.insert(std::make_pair(Result, I));
894 // If the type of the constant is abstract, make sure that an entry
895 // exists for it in the AbstractTypeMap.
896 if (Ty->isAbstract()) {
897 typename AbstractTypeMapTy::iterator TI =
898 AbstractTypeMap.find(Ty);
900 if (TI == AbstractTypeMap.end()) {
901 // Add ourselves to the ATU list of the type.
902 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
904 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
912 /// getOrCreate - Return the specified constant from the map, creating it if
914 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
915 sys::SmartScopedLock<true> Lock(ValueMapLock);
916 MapKey Lookup(Ty, V);
917 ConstantClass* Result = 0;
919 typename MapTy::iterator I = Map.find(Lookup);
922 Result = static_cast<ConstantClass *>(I->second);
925 // If no preexisting value, create one now...
926 Result = Create(Ty, V, I);
932 void remove(ConstantClass *CP) {
933 sys::SmartScopedLock<true> Lock(ValueMapLock);
934 typename MapTy::iterator I = FindExistingElement(CP);
935 assert(I != Map.end() && "Constant not found in constant table!");
936 assert(I->second == CP && "Didn't find correct element?");
938 if (HasLargeKey) // Remember the reverse mapping if needed.
939 InverseMap.erase(CP);
941 // Now that we found the entry, make sure this isn't the entry that
942 // the AbstractTypeMap points to.
943 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
944 if (Ty->isAbstract()) {
945 assert(AbstractTypeMap.count(Ty) &&
946 "Abstract type not in AbstractTypeMap?");
947 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
948 if (ATMEntryIt == I) {
949 // Yes, we are removing the representative entry for this type.
950 // See if there are any other entries of the same type.
951 typename MapTy::iterator TmpIt = ATMEntryIt;
953 // First check the entry before this one...
954 if (TmpIt != Map.begin()) {
956 if (TmpIt->first.first != Ty) // Not the same type, move back...
960 // If we didn't find the same type, try to move forward...
961 if (TmpIt == ATMEntryIt) {
963 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
964 --TmpIt; // No entry afterwards with the same type
967 // If there is another entry in the map of the same abstract type,
968 // update the AbstractTypeMap entry now.
969 if (TmpIt != ATMEntryIt) {
972 // Otherwise, we are removing the last instance of this type
973 // from the table. Remove from the ATM, and from user list.
974 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
975 AbstractTypeMap.erase(Ty);
984 /// MoveConstantToNewSlot - If we are about to change C to be the element
985 /// specified by I, update our internal data structures to reflect this
987 /// NOTE: This function is not locked. It is the responsibility of the
988 /// caller to enforce proper synchronization if using this method.
989 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
990 // First, remove the old location of the specified constant in the map.
991 typename MapTy::iterator OldI = FindExistingElement(C);
992 assert(OldI != Map.end() && "Constant not found in constant table!");
993 assert(OldI->second == C && "Didn't find correct element?");
995 // If this constant is the representative element for its abstract type,
996 // update the AbstractTypeMap so that the representative element is I.
997 if (C->getType()->isAbstract()) {
998 typename AbstractTypeMapTy::iterator ATI =
999 AbstractTypeMap.find(C->getType());
1000 assert(ATI != AbstractTypeMap.end() &&
1001 "Abstract type not in AbstractTypeMap?");
1002 if (ATI->second == OldI)
1006 // Remove the old entry from the map.
1009 // Update the inverse map so that we know that this constant is now
1010 // located at descriptor I.
1012 assert(I->second == C && "Bad inversemap entry!");
1017 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1018 sys::SmartScopedLock<true> Lock(ValueMapLock);
1019 typename AbstractTypeMapTy::iterator I =
1020 AbstractTypeMap.find(cast<Type>(OldTy));
1022 assert(I != AbstractTypeMap.end() &&
1023 "Abstract type not in AbstractTypeMap?");
1025 // Convert a constant at a time until the last one is gone. The last one
1026 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1027 // eliminated eventually.
1029 ConvertConstantType<ConstantClass,
1030 TypeClass>::convert(
1031 static_cast<ConstantClass *>(I->second->second),
1032 cast<TypeClass>(NewTy));
1034 I = AbstractTypeMap.find(cast<Type>(OldTy));
1035 } while (I != AbstractTypeMap.end());
1038 // If the type became concrete without being refined to any other existing
1039 // type, we just remove ourselves from the ATU list.
1040 void typeBecameConcrete(const DerivedType *AbsTy) {
1041 AbsTy->removeAbstractTypeUser(this);
1045 DOUT << "Constant.cpp: ValueMap\n";
1052 //---- ConstantAggregateZero::get() implementation...
1055 // ConstantAggregateZero does not take extra "value" argument...
1056 template<class ValType>
1057 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1058 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1059 return new ConstantAggregateZero(Ty);
1064 struct ConvertConstantType<ConstantAggregateZero, Type> {
1065 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1066 // Make everyone now use a constant of the new type...
1067 Constant *New = ConstantAggregateZero::get(NewTy);
1068 assert(New != OldC && "Didn't replace constant??");
1069 OldC->uncheckedReplaceAllUsesWith(New);
1070 OldC->destroyConstant(); // This constant is now dead, destroy it.
1075 static ManagedStatic<ValueMap<char, Type,
1076 ConstantAggregateZero> > AggZeroConstants;
1078 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1080 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1081 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1082 "Cannot create an aggregate zero of non-aggregate type!");
1084 // Implicitly locked.
1085 return AggZeroConstants->getOrCreate(Ty, 0);
1088 /// destroyConstant - Remove the constant from the constant table...
1090 void ConstantAggregateZero::destroyConstant() {
1091 // Implicitly locked.
1092 AggZeroConstants->remove(this);
1093 destroyConstantImpl();
1096 //---- ConstantArray::get() implementation...
1100 struct ConvertConstantType<ConstantArray, ArrayType> {
1101 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1102 // Make everyone now use a constant of the new type...
1103 std::vector<Constant*> C;
1104 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1105 C.push_back(cast<Constant>(OldC->getOperand(i)));
1106 Constant *New = ConstantArray::get(NewTy, C);
1107 assert(New != OldC && "Didn't replace constant??");
1108 OldC->uncheckedReplaceAllUsesWith(New);
1109 OldC->destroyConstant(); // This constant is now dead, destroy it.
1114 static std::vector<Constant*> getValType(ConstantArray *CA) {
1115 std::vector<Constant*> Elements;
1116 Elements.reserve(CA->getNumOperands());
1117 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1118 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1122 typedef ValueMap<std::vector<Constant*>, ArrayType,
1123 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1124 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1126 Constant *ConstantArray::get(const ArrayType *Ty,
1127 const std::vector<Constant*> &V) {
1128 // If this is an all-zero array, return a ConstantAggregateZero object
1131 if (!C->isNullValue()) {
1132 // Implicitly locked.
1133 return ArrayConstants->getOrCreate(Ty, V);
1135 for (unsigned i = 1, e = V.size(); i != e; ++i)
1137 // Implicitly locked.
1138 return ArrayConstants->getOrCreate(Ty, V);
1142 return ConstantAggregateZero::get(Ty);
1145 /// destroyConstant - Remove the constant from the constant table...
1147 void ConstantArray::destroyConstant() {
1148 // Implicitly locked.
1149 ArrayConstants->remove(this);
1150 destroyConstantImpl();
1153 /// isString - This method returns true if the array is an array of i8, and
1154 /// if the elements of the array are all ConstantInt's.
1155 bool ConstantArray::isString() const {
1156 // Check the element type for i8...
1157 if (getType()->getElementType() != Type::Int8Ty)
1159 // Check the elements to make sure they are all integers, not constant
1161 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1162 if (!isa<ConstantInt>(getOperand(i)))
1167 /// isCString - This method returns true if the array is a string (see
1168 /// isString) and it ends in a null byte \\0 and does not contains any other
1169 /// null bytes except its terminator.
1170 bool ConstantArray::isCString() const {
1171 // Check the element type for i8...
1172 if (getType()->getElementType() != Type::Int8Ty)
1175 // Last element must be a null.
1176 if (!getOperand(getNumOperands()-1)->isNullValue())
1178 // Other elements must be non-null integers.
1179 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1180 if (!isa<ConstantInt>(getOperand(i)))
1182 if (getOperand(i)->isNullValue())
1189 /// getAsString - If the sub-element type of this array is i8
1190 /// then this method converts the array to an std::string and returns it.
1191 /// Otherwise, it asserts out.
1193 std::string ConstantArray::getAsString() const {
1194 assert(isString() && "Not a string!");
1196 Result.reserve(getNumOperands());
1197 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1198 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1203 //---- ConstantStruct::get() implementation...
1208 struct ConvertConstantType<ConstantStruct, StructType> {
1209 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1210 // Make everyone now use a constant of the new type...
1211 std::vector<Constant*> C;
1212 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1213 C.push_back(cast<Constant>(OldC->getOperand(i)));
1214 Constant *New = ConstantStruct::get(NewTy, C);
1215 assert(New != OldC && "Didn't replace constant??");
1217 OldC->uncheckedReplaceAllUsesWith(New);
1218 OldC->destroyConstant(); // This constant is now dead, destroy it.
1223 typedef ValueMap<std::vector<Constant*>, StructType,
1224 ConstantStruct, true /*largekey*/> StructConstantsTy;
1225 static ManagedStatic<StructConstantsTy> StructConstants;
1227 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1228 std::vector<Constant*> Elements;
1229 Elements.reserve(CS->getNumOperands());
1230 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1231 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1235 Constant *ConstantStruct::get(const StructType *Ty,
1236 const std::vector<Constant*> &V) {
1237 // Create a ConstantAggregateZero value if all elements are zeros...
1238 for (unsigned i = 0, e = V.size(); i != e; ++i)
1239 if (!V[i]->isNullValue())
1240 // Implicitly locked.
1241 return StructConstants->getOrCreate(Ty, V);
1243 return ConstantAggregateZero::get(Ty);
1246 // destroyConstant - Remove the constant from the constant table...
1248 void ConstantStruct::destroyConstant() {
1249 // Implicitly locked.
1250 StructConstants->remove(this);
1251 destroyConstantImpl();
1254 //---- ConstantVector::get() implementation...
1258 struct ConvertConstantType<ConstantVector, VectorType> {
1259 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1260 // Make everyone now use a constant of the new type...
1261 std::vector<Constant*> C;
1262 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1263 C.push_back(cast<Constant>(OldC->getOperand(i)));
1264 Constant *New = ConstantVector::get(NewTy, C);
1265 assert(New != OldC && "Didn't replace constant??");
1266 OldC->uncheckedReplaceAllUsesWith(New);
1267 OldC->destroyConstant(); // This constant is now dead, destroy it.
1272 static std::vector<Constant*> getValType(ConstantVector *CP) {
1273 std::vector<Constant*> Elements;
1274 Elements.reserve(CP->getNumOperands());
1275 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1276 Elements.push_back(CP->getOperand(i));
1280 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1281 ConstantVector> > VectorConstants;
1283 Constant *ConstantVector::get(const VectorType *Ty,
1284 const std::vector<Constant*> &V) {
1285 assert(!V.empty() && "Vectors can't be empty");
1286 // If this is an all-undef or alll-zero vector, return a
1287 // ConstantAggregateZero or UndefValue.
1289 bool isZero = C->isNullValue();
1290 bool isUndef = isa<UndefValue>(C);
1292 if (isZero || isUndef) {
1293 for (unsigned i = 1, e = V.size(); i != e; ++i)
1295 isZero = isUndef = false;
1301 return ConstantAggregateZero::get(Ty);
1303 return UndefValue::get(Ty);
1305 // Implicitly locked.
1306 return VectorConstants->getOrCreate(Ty, V);
1309 // destroyConstant - Remove the constant from the constant table...
1311 void ConstantVector::destroyConstant() {
1312 // Implicitly locked.
1313 VectorConstants->remove(this);
1314 destroyConstantImpl();
1317 /// This function will return true iff every element in this vector constant
1318 /// is set to all ones.
1319 /// @returns true iff this constant's emements are all set to all ones.
1320 /// @brief Determine if the value is all ones.
1321 bool ConstantVector::isAllOnesValue() const {
1322 // Check out first element.
1323 const Constant *Elt = getOperand(0);
1324 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1325 if (!CI || !CI->isAllOnesValue()) return false;
1326 // Then make sure all remaining elements point to the same value.
1327 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1328 if (getOperand(I) != Elt) return false;
1333 /// getSplatValue - If this is a splat constant, where all of the
1334 /// elements have the same value, return that value. Otherwise return null.
1335 Constant *ConstantVector::getSplatValue() {
1336 // Check out first element.
1337 Constant *Elt = getOperand(0);
1338 // Then make sure all remaining elements point to the same value.
1339 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1340 if (getOperand(I) != Elt) return 0;
1344 //---- ConstantPointerNull::get() implementation...
1348 // ConstantPointerNull does not take extra "value" argument...
1349 template<class ValType>
1350 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1351 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1352 return new ConstantPointerNull(Ty);
1357 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1358 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1359 // Make everyone now use a constant of the new type...
1360 Constant *New = ConstantPointerNull::get(NewTy);
1361 assert(New != OldC && "Didn't replace constant??");
1362 OldC->uncheckedReplaceAllUsesWith(New);
1363 OldC->destroyConstant(); // This constant is now dead, destroy it.
1368 static ManagedStatic<ValueMap<char, PointerType,
1369 ConstantPointerNull> > NullPtrConstants;
1371 static char getValType(ConstantPointerNull *) {
1376 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1377 // Implicitly locked.
1378 return NullPtrConstants->getOrCreate(Ty, 0);
1381 // destroyConstant - Remove the constant from the constant table...
1383 void ConstantPointerNull::destroyConstant() {
1384 // Implicitly locked.
1385 NullPtrConstants->remove(this);
1386 destroyConstantImpl();
1390 //---- UndefValue::get() implementation...
1394 // UndefValue does not take extra "value" argument...
1395 template<class ValType>
1396 struct ConstantCreator<UndefValue, Type, ValType> {
1397 static UndefValue *create(const Type *Ty, const ValType &V) {
1398 return new UndefValue(Ty);
1403 struct ConvertConstantType<UndefValue, Type> {
1404 static void convert(UndefValue *OldC, const Type *NewTy) {
1405 // Make everyone now use a constant of the new type.
1406 Constant *New = UndefValue::get(NewTy);
1407 assert(New != OldC && "Didn't replace constant??");
1408 OldC->uncheckedReplaceAllUsesWith(New);
1409 OldC->destroyConstant(); // This constant is now dead, destroy it.
1414 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1416 static char getValType(UndefValue *) {
1421 UndefValue *UndefValue::get(const Type *Ty) {
1422 // Implicitly locked.
1423 return UndefValueConstants->getOrCreate(Ty, 0);
1426 // destroyConstant - Remove the constant from the constant table.
1428 void UndefValue::destroyConstant() {
1429 // Implicitly locked.
1430 UndefValueConstants->remove(this);
1431 destroyConstantImpl();
1434 //---- MDString::get() implementation
1437 MDString::MDString(const char *begin, const char *end)
1438 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1439 StrBegin(begin), StrEnd(end) {}
1441 void MDString::destroyConstant() {
1442 getType()->getContext().erase(this);
1443 destroyConstantImpl();
1446 //---- MDNode::get() implementation
1449 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1450 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1451 for (unsigned i = 0; i != NumVals; ++i)
1452 Node.push_back(ElementVH(Vals[i], this));
1455 void MDNode::Profile(FoldingSetNodeID &ID) const {
1456 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1460 void MDNode::destroyConstant() {
1461 getType()->getContext().erase(this);
1462 destroyConstantImpl();
1465 //---- ConstantExpr::get() implementations...
1470 struct ExprMapKeyType {
1471 typedef SmallVector<unsigned, 4> IndexList;
1473 ExprMapKeyType(unsigned opc,
1474 const std::vector<Constant*> &ops,
1475 unsigned short pred = 0,
1476 const IndexList &inds = IndexList())
1477 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1480 std::vector<Constant*> operands;
1482 bool operator==(const ExprMapKeyType& that) const {
1483 return this->opcode == that.opcode &&
1484 this->predicate == that.predicate &&
1485 this->operands == that.operands &&
1486 this->indices == that.indices;
1488 bool operator<(const ExprMapKeyType & that) const {
1489 return this->opcode < that.opcode ||
1490 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1491 (this->opcode == that.opcode && this->predicate == that.predicate &&
1492 this->operands < that.operands) ||
1493 (this->opcode == that.opcode && this->predicate == that.predicate &&
1494 this->operands == that.operands && this->indices < that.indices);
1497 bool operator!=(const ExprMapKeyType& that) const {
1498 return !(*this == that);
1506 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1507 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1508 unsigned short pred = 0) {
1509 if (Instruction::isCast(V.opcode))
1510 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1511 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1512 V.opcode < Instruction::BinaryOpsEnd))
1513 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1514 if (V.opcode == Instruction::Select)
1515 return new SelectConstantExpr(V.operands[0], V.operands[1],
1517 if (V.opcode == Instruction::ExtractElement)
1518 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1519 if (V.opcode == Instruction::InsertElement)
1520 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1522 if (V.opcode == Instruction::ShuffleVector)
1523 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1525 if (V.opcode == Instruction::InsertValue)
1526 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1528 if (V.opcode == Instruction::ExtractValue)
1529 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1530 if (V.opcode == Instruction::GetElementPtr) {
1531 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1532 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1535 // The compare instructions are weird. We have to encode the predicate
1536 // value and it is combined with the instruction opcode by multiplying
1537 // the opcode by one hundred. We must decode this to get the predicate.
1538 if (V.opcode == Instruction::ICmp)
1539 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1540 V.operands[0], V.operands[1]);
1541 if (V.opcode == Instruction::FCmp)
1542 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1543 V.operands[0], V.operands[1]);
1544 llvm_unreachable("Invalid ConstantExpr!");
1550 struct ConvertConstantType<ConstantExpr, Type> {
1551 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1553 switch (OldC->getOpcode()) {
1554 case Instruction::Trunc:
1555 case Instruction::ZExt:
1556 case Instruction::SExt:
1557 case Instruction::FPTrunc:
1558 case Instruction::FPExt:
1559 case Instruction::UIToFP:
1560 case Instruction::SIToFP:
1561 case Instruction::FPToUI:
1562 case Instruction::FPToSI:
1563 case Instruction::PtrToInt:
1564 case Instruction::IntToPtr:
1565 case Instruction::BitCast:
1566 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1569 case Instruction::Select:
1570 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1571 OldC->getOperand(1),
1572 OldC->getOperand(2));
1575 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1576 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1577 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1578 OldC->getOperand(1));
1580 case Instruction::GetElementPtr:
1581 // Make everyone now use a constant of the new type...
1582 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1583 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1584 &Idx[0], Idx.size());
1588 assert(New != OldC && "Didn't replace constant??");
1589 OldC->uncheckedReplaceAllUsesWith(New);
1590 OldC->destroyConstant(); // This constant is now dead, destroy it.
1593 } // end namespace llvm
1596 static ExprMapKeyType getValType(ConstantExpr *CE) {
1597 std::vector<Constant*> Operands;
1598 Operands.reserve(CE->getNumOperands());
1599 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1600 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1601 return ExprMapKeyType(CE->getOpcode(), Operands,
1602 CE->isCompare() ? CE->getPredicate() : 0,
1604 CE->getIndices() : SmallVector<unsigned, 4>());
1607 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1608 ConstantExpr> > ExprConstants;
1610 /// This is a utility function to handle folding of casts and lookup of the
1611 /// cast in the ExprConstants map. It is used by the various get* methods below.
1612 static inline Constant *getFoldedCast(
1613 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1614 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1615 // Fold a few common cases
1617 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1620 // Look up the constant in the table first to ensure uniqueness
1621 std::vector<Constant*> argVec(1, C);
1622 ExprMapKeyType Key(opc, argVec);
1624 // Implicitly locked.
1625 return ExprConstants->getOrCreate(Ty, Key);
1628 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1629 Instruction::CastOps opc = Instruction::CastOps(oc);
1630 assert(Instruction::isCast(opc) && "opcode out of range");
1631 assert(C && Ty && "Null arguments to getCast");
1632 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1636 llvm_unreachable("Invalid cast opcode");
1638 case Instruction::Trunc: return getTrunc(C, Ty);
1639 case Instruction::ZExt: return getZExt(C, Ty);
1640 case Instruction::SExt: return getSExt(C, Ty);
1641 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1642 case Instruction::FPExt: return getFPExtend(C, Ty);
1643 case Instruction::UIToFP: return getUIToFP(C, Ty);
1644 case Instruction::SIToFP: return getSIToFP(C, Ty);
1645 case Instruction::FPToUI: return getFPToUI(C, Ty);
1646 case Instruction::FPToSI: return getFPToSI(C, Ty);
1647 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1648 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1649 case Instruction::BitCast: return getBitCast(C, Ty);
1654 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1655 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1656 return getCast(Instruction::BitCast, C, Ty);
1657 return getCast(Instruction::ZExt, C, Ty);
1660 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1661 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1662 return getCast(Instruction::BitCast, C, Ty);
1663 return getCast(Instruction::SExt, C, Ty);
1666 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1667 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1668 return getCast(Instruction::BitCast, C, Ty);
1669 return getCast(Instruction::Trunc, C, Ty);
1672 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1673 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1674 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1676 if (Ty->isInteger())
1677 return getCast(Instruction::PtrToInt, S, Ty);
1678 return getCast(Instruction::BitCast, S, Ty);
1681 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1683 assert(C->getType()->isIntOrIntVector() &&
1684 Ty->isIntOrIntVector() && "Invalid cast");
1685 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1686 unsigned DstBits = Ty->getScalarSizeInBits();
1687 Instruction::CastOps opcode =
1688 (SrcBits == DstBits ? Instruction::BitCast :
1689 (SrcBits > DstBits ? Instruction::Trunc :
1690 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1691 return getCast(opcode, C, Ty);
1694 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1695 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1697 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1698 unsigned DstBits = Ty->getScalarSizeInBits();
1699 if (SrcBits == DstBits)
1700 return C; // Avoid a useless cast
1701 Instruction::CastOps opcode =
1702 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1703 return getCast(opcode, C, Ty);
1706 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1708 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1709 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1711 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1712 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1713 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1714 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1715 "SrcTy must be larger than DestTy for Trunc!");
1717 return getFoldedCast(Instruction::Trunc, C, Ty);
1720 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1722 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1723 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1725 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1726 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1727 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1728 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1729 "SrcTy must be smaller than DestTy for SExt!");
1731 return getFoldedCast(Instruction::SExt, C, Ty);
1734 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1736 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1737 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1739 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1740 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1741 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1742 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1743 "SrcTy must be smaller than DestTy for ZExt!");
1745 return getFoldedCast(Instruction::ZExt, C, Ty);
1748 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1750 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1751 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1753 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1754 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1755 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1756 "This is an illegal floating point truncation!");
1757 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1760 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1762 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1763 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1765 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1766 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1767 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1768 "This is an illegal floating point extension!");
1769 return getFoldedCast(Instruction::FPExt, C, Ty);
1772 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1774 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1775 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1777 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1778 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1779 "This is an illegal uint to floating point cast!");
1780 return getFoldedCast(Instruction::UIToFP, C, Ty);
1783 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1785 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1786 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1788 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1789 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1790 "This is an illegal sint to floating point cast!");
1791 return getFoldedCast(Instruction::SIToFP, C, Ty);
1794 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1796 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1797 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1799 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1800 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1801 "This is an illegal floating point to uint cast!");
1802 return getFoldedCast(Instruction::FPToUI, C, Ty);
1805 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1807 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1808 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1810 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1811 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1812 "This is an illegal floating point to sint cast!");
1813 return getFoldedCast(Instruction::FPToSI, C, Ty);
1816 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1817 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1818 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1819 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1822 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1823 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1824 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1825 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1828 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1829 // BitCast implies a no-op cast of type only. No bits change. However, you
1830 // can't cast pointers to anything but pointers.
1832 const Type *SrcTy = C->getType();
1833 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1834 "BitCast cannot cast pointer to non-pointer and vice versa");
1836 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1837 // or nonptr->ptr). For all the other types, the cast is okay if source and
1838 // destination bit widths are identical.
1839 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1840 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1842 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1844 // It is common to ask for a bitcast of a value to its own type, handle this
1846 if (C->getType() == DstTy) return C;
1848 return getFoldedCast(Instruction::BitCast, C, DstTy);
1851 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1852 Constant *C1, Constant *C2) {
1853 // Check the operands for consistency first
1854 assert(Opcode >= Instruction::BinaryOpsBegin &&
1855 Opcode < Instruction::BinaryOpsEnd &&
1856 "Invalid opcode in binary constant expression");
1857 assert(C1->getType() == C2->getType() &&
1858 "Operand types in binary constant expression should match");
1860 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1861 if (Constant *FC = ConstantFoldBinaryInstruction(
1862 getGlobalContext(), Opcode, C1, C2))
1863 return FC; // Fold a few common cases...
1865 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1866 ExprMapKeyType Key(Opcode, argVec);
1868 // Implicitly locked.
1869 return ExprConstants->getOrCreate(ReqTy, Key);
1872 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1873 Constant *C1, Constant *C2) {
1874 switch (predicate) {
1875 default: llvm_unreachable("Invalid CmpInst predicate");
1876 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1877 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1878 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1879 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1880 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1881 case CmpInst::FCMP_TRUE:
1882 return getFCmp(predicate, C1, C2);
1884 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1885 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1886 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1887 case CmpInst::ICMP_SLE:
1888 return getICmp(predicate, C1, C2);
1892 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1893 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1894 if (C1->getType()->isFPOrFPVector()) {
1895 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1896 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1897 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1901 case Instruction::Add:
1902 case Instruction::Sub:
1903 case Instruction::Mul:
1904 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1905 assert(C1->getType()->isIntOrIntVector() &&
1906 "Tried to create an integer operation on a non-integer type!");
1908 case Instruction::FAdd:
1909 case Instruction::FSub:
1910 case Instruction::FMul:
1911 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1912 assert(C1->getType()->isFPOrFPVector() &&
1913 "Tried to create a floating-point operation on a "
1914 "non-floating-point type!");
1916 case Instruction::UDiv:
1917 case Instruction::SDiv:
1918 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1919 assert(C1->getType()->isIntOrIntVector() &&
1920 "Tried to create an arithmetic operation on a non-arithmetic type!");
1922 case Instruction::FDiv:
1923 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1924 assert(C1->getType()->isFPOrFPVector() &&
1925 "Tried to create an arithmetic operation on a non-arithmetic type!");
1927 case Instruction::URem:
1928 case Instruction::SRem:
1929 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1930 assert(C1->getType()->isIntOrIntVector() &&
1931 "Tried to create an arithmetic operation on a non-arithmetic type!");
1933 case Instruction::FRem:
1934 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1935 assert(C1->getType()->isFPOrFPVector() &&
1936 "Tried to create an arithmetic operation on a non-arithmetic type!");
1938 case Instruction::And:
1939 case Instruction::Or:
1940 case Instruction::Xor:
1941 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1942 assert(C1->getType()->isIntOrIntVector() &&
1943 "Tried to create a logical operation on a non-integral type!");
1945 case Instruction::Shl:
1946 case Instruction::LShr:
1947 case Instruction::AShr:
1948 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1949 assert(C1->getType()->isIntOrIntVector() &&
1950 "Tried to create a shift operation on a non-integer type!");
1957 return getTy(C1->getType(), Opcode, C1, C2);
1960 Constant *ConstantExpr::getCompare(unsigned short pred,
1961 Constant *C1, Constant *C2) {
1962 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1963 return getCompareTy(pred, C1, C2);
1966 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1967 Constant *V1, Constant *V2) {
1968 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1970 if (ReqTy == V1->getType())
1971 if (Constant *SC = ConstantFoldSelectInstruction(
1972 getGlobalContext(), C, V1, V2))
1973 return SC; // Fold common cases
1975 std::vector<Constant*> argVec(3, C);
1978 ExprMapKeyType Key(Instruction::Select, argVec);
1980 // Implicitly locked.
1981 return ExprConstants->getOrCreate(ReqTy, Key);
1984 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1987 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1989 cast<PointerType>(ReqTy)->getElementType() &&
1990 "GEP indices invalid!");
1992 if (Constant *FC = ConstantFoldGetElementPtr(
1993 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1994 return FC; // Fold a few common cases...
1996 assert(isa<PointerType>(C->getType()) &&
1997 "Non-pointer type for constant GetElementPtr expression");
1998 // Look up the constant in the table first to ensure uniqueness
1999 std::vector<Constant*> ArgVec;
2000 ArgVec.reserve(NumIdx+1);
2001 ArgVec.push_back(C);
2002 for (unsigned i = 0; i != NumIdx; ++i)
2003 ArgVec.push_back(cast<Constant>(Idxs[i]));
2004 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2006 // Implicitly locked.
2007 return ExprConstants->getOrCreate(ReqTy, Key);
2010 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2012 // Get the result type of the getelementptr!
2014 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2015 assert(Ty && "GEP indices invalid!");
2016 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2017 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2020 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2022 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2027 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2028 assert(LHS->getType() == RHS->getType());
2029 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2030 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2032 if (Constant *FC = ConstantFoldCompareInstruction(
2033 getGlobalContext(),pred, LHS, RHS))
2034 return FC; // Fold a few common cases...
2036 // Look up the constant in the table first to ensure uniqueness
2037 std::vector<Constant*> ArgVec;
2038 ArgVec.push_back(LHS);
2039 ArgVec.push_back(RHS);
2040 // Get the key type with both the opcode and predicate
2041 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2043 // Implicitly locked.
2044 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2048 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2049 assert(LHS->getType() == RHS->getType());
2050 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2052 if (Constant *FC = ConstantFoldCompareInstruction(
2053 getGlobalContext(), pred, LHS, RHS))
2054 return FC; // Fold a few common cases...
2056 // Look up the constant in the table first to ensure uniqueness
2057 std::vector<Constant*> ArgVec;
2058 ArgVec.push_back(LHS);
2059 ArgVec.push_back(RHS);
2060 // Get the key type with both the opcode and predicate
2061 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2063 // Implicitly locked.
2064 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2067 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2069 if (Constant *FC = ConstantFoldExtractElementInstruction(
2070 getGlobalContext(), Val, Idx))
2071 return FC; // Fold a few common cases...
2072 // Look up the constant in the table first to ensure uniqueness
2073 std::vector<Constant*> ArgVec(1, Val);
2074 ArgVec.push_back(Idx);
2075 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2077 // Implicitly locked.
2078 return ExprConstants->getOrCreate(ReqTy, Key);
2081 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2082 assert(isa<VectorType>(Val->getType()) &&
2083 "Tried to create extractelement operation on non-vector type!");
2084 assert(Idx->getType() == Type::Int32Ty &&
2085 "Extractelement index must be i32 type!");
2086 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2090 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2091 Constant *Elt, Constant *Idx) {
2092 if (Constant *FC = ConstantFoldInsertElementInstruction(
2093 getGlobalContext(), Val, Elt, Idx))
2094 return FC; // Fold a few common cases...
2095 // Look up the constant in the table first to ensure uniqueness
2096 std::vector<Constant*> ArgVec(1, Val);
2097 ArgVec.push_back(Elt);
2098 ArgVec.push_back(Idx);
2099 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2101 // Implicitly locked.
2102 return ExprConstants->getOrCreate(ReqTy, Key);
2105 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2107 assert(isa<VectorType>(Val->getType()) &&
2108 "Tried to create insertelement operation on non-vector type!");
2109 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2110 && "Insertelement types must match!");
2111 assert(Idx->getType() == Type::Int32Ty &&
2112 "Insertelement index must be i32 type!");
2113 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2116 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2117 Constant *V2, Constant *Mask) {
2118 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2119 getGlobalContext(), V1, V2, Mask))
2120 return FC; // Fold a few common cases...
2121 // Look up the constant in the table first to ensure uniqueness
2122 std::vector<Constant*> ArgVec(1, V1);
2123 ArgVec.push_back(V2);
2124 ArgVec.push_back(Mask);
2125 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2127 // Implicitly locked.
2128 return ExprConstants->getOrCreate(ReqTy, Key);
2131 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2133 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2134 "Invalid shuffle vector constant expr operands!");
2136 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2137 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2138 const Type *ShufTy = VectorType::get(EltTy, NElts);
2139 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2142 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2144 const unsigned *Idxs, unsigned NumIdx) {
2145 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2146 Idxs+NumIdx) == Val->getType() &&
2147 "insertvalue indices invalid!");
2148 assert(Agg->getType() == ReqTy &&
2149 "insertvalue type invalid!");
2150 assert(Agg->getType()->isFirstClassType() &&
2151 "Non-first-class type for constant InsertValue expression");
2152 Constant *FC = ConstantFoldInsertValueInstruction(
2153 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2154 assert(FC && "InsertValue constant expr couldn't be folded!");
2158 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2159 const unsigned *IdxList, unsigned NumIdx) {
2160 assert(Agg->getType()->isFirstClassType() &&
2161 "Tried to create insertelement operation on non-first-class type!");
2163 const Type *ReqTy = Agg->getType();
2166 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2168 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2169 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2172 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2173 const unsigned *Idxs, unsigned NumIdx) {
2174 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2175 Idxs+NumIdx) == ReqTy &&
2176 "extractvalue indices invalid!");
2177 assert(Agg->getType()->isFirstClassType() &&
2178 "Non-first-class type for constant extractvalue expression");
2179 Constant *FC = ConstantFoldExtractValueInstruction(
2180 getGlobalContext(), Agg, Idxs, NumIdx);
2181 assert(FC && "ExtractValue constant expr couldn't be folded!");
2185 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2186 const unsigned *IdxList, unsigned NumIdx) {
2187 assert(Agg->getType()->isFirstClassType() &&
2188 "Tried to create extractelement operation on non-first-class type!");
2191 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2192 assert(ReqTy && "extractvalue indices invalid!");
2193 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2196 // destroyConstant - Remove the constant from the constant table...
2198 void ConstantExpr::destroyConstant() {
2199 // Implicitly locked.
2200 ExprConstants->remove(this);
2201 destroyConstantImpl();
2204 const char *ConstantExpr::getOpcodeName() const {
2205 return Instruction::getOpcodeName(getOpcode());
2208 //===----------------------------------------------------------------------===//
2209 // replaceUsesOfWithOnConstant implementations
2211 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2212 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2215 /// Note that we intentionally replace all uses of From with To here. Consider
2216 /// a large array that uses 'From' 1000 times. By handling this case all here,
2217 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2218 /// single invocation handles all 1000 uses. Handling them one at a time would
2219 /// work, but would be really slow because it would have to unique each updated
2221 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2223 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2224 Constant *ToC = cast<Constant>(To);
2226 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2227 Lookup.first.first = getType();
2228 Lookup.second = this;
2230 std::vector<Constant*> &Values = Lookup.first.second;
2231 Values.reserve(getNumOperands()); // Build replacement array.
2233 // Fill values with the modified operands of the constant array. Also,
2234 // compute whether this turns into an all-zeros array.
2235 bool isAllZeros = false;
2236 unsigned NumUpdated = 0;
2237 if (!ToC->isNullValue()) {
2238 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2239 Constant *Val = cast<Constant>(O->get());
2244 Values.push_back(Val);
2248 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2249 Constant *Val = cast<Constant>(O->get());
2254 Values.push_back(Val);
2255 if (isAllZeros) isAllZeros = Val->isNullValue();
2259 Constant *Replacement = 0;
2261 Replacement = ConstantAggregateZero::get(getType());
2263 // Check to see if we have this array type already.
2264 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2266 ArrayConstantsTy::MapTy::iterator I =
2267 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2270 Replacement = I->second;
2272 // Okay, the new shape doesn't exist in the system yet. Instead of
2273 // creating a new constant array, inserting it, replaceallusesof'ing the
2274 // old with the new, then deleting the old... just update the current one
2276 ArrayConstants->MoveConstantToNewSlot(this, I);
2278 // Update to the new value. Optimize for the case when we have a single
2279 // operand that we're changing, but handle bulk updates efficiently.
2280 if (NumUpdated == 1) {
2281 unsigned OperandToUpdate = U-OperandList;
2282 assert(getOperand(OperandToUpdate) == From &&
2283 "ReplaceAllUsesWith broken!");
2284 setOperand(OperandToUpdate, ToC);
2286 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2287 if (getOperand(i) == From)
2294 // Otherwise, I do need to replace this with an existing value.
2295 assert(Replacement != this && "I didn't contain From!");
2297 // Everyone using this now uses the replacement.
2298 uncheckedReplaceAllUsesWith(Replacement);
2300 // Delete the old constant!
2304 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2306 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2307 Constant *ToC = cast<Constant>(To);
2309 unsigned OperandToUpdate = U-OperandList;
2310 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2312 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2313 Lookup.first.first = getType();
2314 Lookup.second = this;
2315 std::vector<Constant*> &Values = Lookup.first.second;
2316 Values.reserve(getNumOperands()); // Build replacement struct.
2319 // Fill values with the modified operands of the constant struct. Also,
2320 // compute whether this turns into an all-zeros struct.
2321 bool isAllZeros = false;
2322 if (!ToC->isNullValue()) {
2323 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2324 Values.push_back(cast<Constant>(O->get()));
2327 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2328 Constant *Val = cast<Constant>(O->get());
2329 Values.push_back(Val);
2330 if (isAllZeros) isAllZeros = Val->isNullValue();
2333 Values[OperandToUpdate] = ToC;
2335 Constant *Replacement = 0;
2337 Replacement = ConstantAggregateZero::get(getType());
2339 // Check to see if we have this array type already.
2340 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2342 StructConstantsTy::MapTy::iterator I =
2343 StructConstants->InsertOrGetItem(Lookup, Exists);
2346 Replacement = I->second;
2348 // Okay, the new shape doesn't exist in the system yet. Instead of
2349 // creating a new constant struct, inserting it, replaceallusesof'ing the
2350 // old with the new, then deleting the old... just update the current one
2352 StructConstants->MoveConstantToNewSlot(this, I);
2354 // Update to the new value.
2355 setOperand(OperandToUpdate, ToC);
2360 assert(Replacement != this && "I didn't contain From!");
2362 // Everyone using this now uses the replacement.
2363 uncheckedReplaceAllUsesWith(Replacement);
2365 // Delete the old constant!
2369 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2371 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2373 std::vector<Constant*> Values;
2374 Values.reserve(getNumOperands()); // Build replacement array...
2375 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2376 Constant *Val = getOperand(i);
2377 if (Val == From) Val = cast<Constant>(To);
2378 Values.push_back(Val);
2381 Constant *Replacement = ConstantVector::get(getType(), Values);
2382 assert(Replacement != this && "I didn't contain From!");
2384 // Everyone using this now uses the replacement.
2385 uncheckedReplaceAllUsesWith(Replacement);
2387 // Delete the old constant!
2391 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2393 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2394 Constant *To = cast<Constant>(ToV);
2396 Constant *Replacement = 0;
2397 if (getOpcode() == Instruction::GetElementPtr) {
2398 SmallVector<Constant*, 8> Indices;
2399 Constant *Pointer = getOperand(0);
2400 Indices.reserve(getNumOperands()-1);
2401 if (Pointer == From) Pointer = To;
2403 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2404 Constant *Val = getOperand(i);
2405 if (Val == From) Val = To;
2406 Indices.push_back(Val);
2408 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2409 &Indices[0], Indices.size());
2410 } else if (getOpcode() == Instruction::ExtractValue) {
2411 Constant *Agg = getOperand(0);
2412 if (Agg == From) Agg = To;
2414 const SmallVector<unsigned, 4> &Indices = getIndices();
2415 Replacement = ConstantExpr::getExtractValue(Agg,
2416 &Indices[0], Indices.size());
2417 } else if (getOpcode() == Instruction::InsertValue) {
2418 Constant *Agg = getOperand(0);
2419 Constant *Val = getOperand(1);
2420 if (Agg == From) Agg = To;
2421 if (Val == From) Val = To;
2423 const SmallVector<unsigned, 4> &Indices = getIndices();
2424 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2425 &Indices[0], Indices.size());
2426 } else if (isCast()) {
2427 assert(getOperand(0) == From && "Cast only has one use!");
2428 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2429 } else if (getOpcode() == Instruction::Select) {
2430 Constant *C1 = getOperand(0);
2431 Constant *C2 = getOperand(1);
2432 Constant *C3 = getOperand(2);
2433 if (C1 == From) C1 = To;
2434 if (C2 == From) C2 = To;
2435 if (C3 == From) C3 = To;
2436 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2437 } else if (getOpcode() == Instruction::ExtractElement) {
2438 Constant *C1 = getOperand(0);
2439 Constant *C2 = getOperand(1);
2440 if (C1 == From) C1 = To;
2441 if (C2 == From) C2 = To;
2442 Replacement = ConstantExpr::getExtractElement(C1, C2);
2443 } else if (getOpcode() == Instruction::InsertElement) {
2444 Constant *C1 = getOperand(0);
2445 Constant *C2 = getOperand(1);
2446 Constant *C3 = getOperand(1);
2447 if (C1 == From) C1 = To;
2448 if (C2 == From) C2 = To;
2449 if (C3 == From) C3 = To;
2450 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2451 } else if (getOpcode() == Instruction::ShuffleVector) {
2452 Constant *C1 = getOperand(0);
2453 Constant *C2 = getOperand(1);
2454 Constant *C3 = getOperand(2);
2455 if (C1 == From) C1 = To;
2456 if (C2 == From) C2 = To;
2457 if (C3 == From) C3 = To;
2458 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2459 } else if (isCompare()) {
2460 Constant *C1 = getOperand(0);
2461 Constant *C2 = getOperand(1);
2462 if (C1 == From) C1 = To;
2463 if (C2 == From) C2 = To;
2464 if (getOpcode() == Instruction::ICmp)
2465 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2467 assert(getOpcode() == Instruction::FCmp);
2468 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2470 } else if (getNumOperands() == 2) {
2471 Constant *C1 = getOperand(0);
2472 Constant *C2 = getOperand(1);
2473 if (C1 == From) C1 = To;
2474 if (C2 == From) C2 = To;
2475 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2477 llvm_unreachable("Unknown ConstantExpr type!");
2481 assert(Replacement != this && "I didn't contain From!");
2483 // Everyone using this now uses the replacement.
2484 uncheckedReplaceAllUsesWith(Replacement);
2486 // Delete the old constant!
2490 void MDNode::replaceElement(Value *From, Value *To) {
2491 SmallVector<Value*, 4> Values;
2492 Values.reserve(getNumElements()); // Build replacement array...
2493 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2494 Value *Val = getElement(i);
2495 if (Val == From) Val = To;
2496 Values.push_back(Val);
2499 MDNode *Replacement =
2500 getType()->getContext().getMDNode(&Values[0], Values.size());
2501 assert(Replacement != this && "I didn't contain From!");
2503 uncheckedReplaceAllUsesWith(Replacement);