Change allowsUnalignedMemoryAccesses to take type argument since some targets
[llvm/avr.git] / lib / VMCore / Constants.cpp
blob647bc1225a29016c067b1a5f24880ef552dadce5
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.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"
35 #include <algorithm>
36 #include <map>
37 using namespace llvm;
39 //===----------------------------------------------------------------------===//
40 // Constant Class
41 //===----------------------------------------------------------------------===//
43 // Constructor to create a '0' constant of arbitrary type...
44 static const uint64_t zero[2] = {0, 0};
45 Constant* Constant::getNullValue(const Type* Ty) {
46 switch (Ty->getTypeID()) {
47 case Type::IntegerTyID:
48 return ConstantInt::get(Ty, 0);
49 case Type::FloatTyID:
50 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
51 case Type::DoubleTyID:
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
53 case Type::X86_FP80TyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
55 case Type::FP128TyID:
56 return ConstantFP::get(Ty->getContext(),
57 APFloat(APInt(128, 2, zero), true));
58 case Type::PPC_FP128TyID:
59 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
60 case Type::PointerTyID:
61 return ConstantPointerNull::get(cast<PointerType>(Ty));
62 case Type::StructTyID:
63 case Type::ArrayTyID:
64 case Type::VectorTyID:
65 return ConstantAggregateZero::get(Ty);
66 default:
67 // Function, Label, or Opaque type?
68 assert(!"Cannot create a null constant of that type!");
69 return 0;
73 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
74 const Type *ScalarTy = Ty->getScalarType();
76 // Create the base integer constant.
77 Constant *C = ConstantInt::get(Ty->getContext(), V);
79 // Convert an integer to a pointer, if necessary.
80 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
81 C = ConstantExpr::getIntToPtr(C, PTy);
83 // Broadcast a scalar to a vector, if necessary.
84 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
85 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
87 return C;
90 Constant* Constant::getAllOnesValue(const Type* Ty) {
91 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
92 return ConstantInt::get(Ty->getContext(),
93 APInt::getAllOnesValue(ITy->getBitWidth()));
95 std::vector<Constant*> Elts;
96 const VectorType* VTy = cast<VectorType>(Ty);
97 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
98 assert(Elts[0] && "Not a vector integer type!");
99 return cast<ConstantVector>(ConstantVector::get(Elts));
102 void Constant::destroyConstantImpl() {
103 // When a Constant is destroyed, there may be lingering
104 // references to the constant by other constants in the constant pool. These
105 // constants are implicitly dependent on the module that is being deleted,
106 // but they don't know that. Because we only find out when the CPV is
107 // deleted, we must now notify all of our users (that should only be
108 // Constants) that they are, in fact, invalid now and should be deleted.
110 while (!use_empty()) {
111 Value *V = use_back();
112 #ifndef NDEBUG // Only in -g mode...
113 if (!isa<Constant>(V))
114 DOUT << "While deleting: " << *this
115 << "\n\nUse still stuck around after Def is destroyed: "
116 << *V << "\n\n";
117 #endif
118 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
119 Constant *CV = cast<Constant>(V);
120 CV->destroyConstant();
122 // The constant should remove itself from our use list...
123 assert((use_empty() || use_back() != V) && "Constant not removed!");
126 // Value has no outstanding references it is safe to delete it now...
127 delete this;
130 /// canTrap - Return true if evaluation of this constant could trap. This is
131 /// true for things like constant expressions that could divide by zero.
132 bool Constant::canTrap() const {
133 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
134 // The only thing that could possibly trap are constant exprs.
135 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
136 if (!CE) return false;
138 // ConstantExpr traps if any operands can trap.
139 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
140 if (getOperand(i)->canTrap())
141 return true;
143 // Otherwise, only specific operations can trap.
144 switch (CE->getOpcode()) {
145 default:
146 return false;
147 case Instruction::UDiv:
148 case Instruction::SDiv:
149 case Instruction::FDiv:
150 case Instruction::URem:
151 case Instruction::SRem:
152 case Instruction::FRem:
153 // Div and rem can trap if the RHS is not known to be non-zero.
154 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
155 return true;
156 return false;
161 /// getRelocationInfo - This method classifies the entry according to
162 /// whether or not it may generate a relocation entry. This must be
163 /// conservative, so if it might codegen to a relocatable entry, it should say
164 /// so. The return values are:
165 ///
166 /// NoRelocation: This constant pool entry is guaranteed to never have a
167 /// relocation applied to it (because it holds a simple constant like
168 /// '4').
169 /// LocalRelocation: This entry has relocations, but the entries are
170 /// guaranteed to be resolvable by the static linker, so the dynamic
171 /// linker will never see them.
172 /// GlobalRelocations: This entry may have arbitrary relocations.
174 /// FIXME: This really should not be in VMCore.
175 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
176 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
177 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
178 return LocalRelocation; // Local to this file/library.
179 return GlobalRelocations; // Global reference.
182 PossibleRelocationsTy Result = NoRelocation;
183 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
184 Result = std::max(Result, getOperand(i)->getRelocationInfo());
186 return Result;
190 /// getVectorElements - This method, which is only valid on constant of vector
191 /// type, returns the elements of the vector in the specified smallvector.
192 /// This handles breaking down a vector undef into undef elements, etc. For
193 /// constant exprs and other cases we can't handle, we return an empty vector.
194 void Constant::getVectorElements(LLVMContext &Context,
195 SmallVectorImpl<Constant*> &Elts) const {
196 assert(isa<VectorType>(getType()) && "Not a vector constant!");
198 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
199 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
200 Elts.push_back(CV->getOperand(i));
201 return;
204 const VectorType *VT = cast<VectorType>(getType());
205 if (isa<ConstantAggregateZero>(this)) {
206 Elts.assign(VT->getNumElements(),
207 Constant::getNullValue(VT->getElementType()));
208 return;
211 if (isa<UndefValue>(this)) {
212 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
213 return;
216 // Unknown type, must be constant expr etc.
221 //===----------------------------------------------------------------------===//
222 // ConstantInt
223 //===----------------------------------------------------------------------===//
225 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
226 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
227 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
230 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
231 LLVMContextImpl *pImpl = Context.pImpl;
232 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
233 if (pImpl->TheTrueVal)
234 return pImpl->TheTrueVal;
235 else
236 return (pImpl->TheTrueVal =
237 ConstantInt::get(IntegerType::get(Context, 1), 1));
240 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
241 LLVMContextImpl *pImpl = Context.pImpl;
242 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
243 if (pImpl->TheFalseVal)
244 return pImpl->TheFalseVal;
245 else
246 return (pImpl->TheFalseVal =
247 ConstantInt::get(IntegerType::get(Context, 1), 0));
251 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
252 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
253 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
254 // compare APInt's of different widths, which would violate an APInt class
255 // invariant which generates an assertion.
256 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
257 // Get the corresponding integer type for the bit width of the value.
258 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
259 // get an existing value or the insertion position
260 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
262 Context.pImpl->ConstantsLock.reader_acquire();
263 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
264 Context.pImpl->ConstantsLock.reader_release();
266 if (!Slot) {
267 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
268 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
269 if (!Slot) {
270 NewSlot = new ConstantInt(ITy, V);
273 return NewSlot;
274 } else {
275 return Slot;
279 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
280 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
281 V, isSigned);
283 // For vectors, broadcast the value.
284 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
285 return ConstantVector::get(
286 std::vector<Constant *>(VTy->getNumElements(), C));
288 return C;
291 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
292 bool isSigned) {
293 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
296 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
297 return get(Ty, V, true);
300 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
301 return get(Ty, V, true);
304 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
305 ConstantInt *C = get(Ty->getContext(), V);
306 assert(C->getType() == Ty->getScalarType() &&
307 "ConstantInt type doesn't match the type implied by its value!");
309 // For vectors, broadcast the value.
310 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
311 return ConstantVector::get(
312 std::vector<Constant *>(VTy->getNumElements(), C));
314 return C;
317 //===----------------------------------------------------------------------===//
318 // ConstantFP
319 //===----------------------------------------------------------------------===//
321 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
322 if (Ty == Type::getFloatTy(Ty->getContext()))
323 return &APFloat::IEEEsingle;
324 if (Ty == Type::getDoubleTy(Ty->getContext()))
325 return &APFloat::IEEEdouble;
326 if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
327 return &APFloat::x87DoubleExtended;
328 else if (Ty == Type::getFP128Ty(Ty->getContext()))
329 return &APFloat::IEEEquad;
331 assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
332 return &APFloat::PPCDoubleDouble;
335 /// get() - This returns a constant fp for the specified value in the
336 /// specified type. This should only be used for simple constant values like
337 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
338 Constant* ConstantFP::get(const Type* Ty, double V) {
339 LLVMContext &Context = Ty->getContext();
341 APFloat FV(V);
342 bool ignored;
343 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
344 APFloat::rmNearestTiesToEven, &ignored);
345 Constant *C = get(Context, FV);
347 // For vectors, broadcast the value.
348 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
349 return ConstantVector::get(
350 std::vector<Constant *>(VTy->getNumElements(), C));
352 return C;
355 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
356 LLVMContext &Context = Ty->getContext();
357 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
358 apf.changeSign();
359 return get(Context, apf);
363 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
364 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
365 if (PTy->getElementType()->isFloatingPoint()) {
366 std::vector<Constant*> zeros(PTy->getNumElements(),
367 getNegativeZero(PTy->getElementType()));
368 return ConstantVector::get(PTy, zeros);
371 if (Ty->isFloatingPoint())
372 return getNegativeZero(Ty);
374 return Constant::getNullValue(Ty);
378 // ConstantFP accessors.
379 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
380 DenseMapAPFloatKeyInfo::KeyTy Key(V);
382 LLVMContextImpl* pImpl = Context.pImpl;
384 pImpl->ConstantsLock.reader_acquire();
385 ConstantFP *&Slot = pImpl->FPConstants[Key];
386 pImpl->ConstantsLock.reader_release();
388 if (!Slot) {
389 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
390 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
391 if (!NewSlot) {
392 const Type *Ty;
393 if (&V.getSemantics() == &APFloat::IEEEsingle)
394 Ty = Type::getFloatTy(Context);
395 else if (&V.getSemantics() == &APFloat::IEEEdouble)
396 Ty = Type::getDoubleTy(Context);
397 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
398 Ty = Type::getX86_FP80Ty(Context);
399 else if (&V.getSemantics() == &APFloat::IEEEquad)
400 Ty = Type::getFP128Ty(Context);
401 else {
402 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
403 "Unknown FP format");
404 Ty = Type::getPPC_FP128Ty(Context);
406 NewSlot = new ConstantFP(Ty, V);
409 return NewSlot;
412 return Slot;
415 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
416 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
417 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
418 "FP type Mismatch");
421 bool ConstantFP::isNullValue() const {
422 return Val.isZero() && !Val.isNegative();
425 bool ConstantFP::isExactlyValue(const APFloat& V) const {
426 return Val.bitwiseIsEqual(V);
429 //===----------------------------------------------------------------------===//
430 // ConstantXXX Classes
431 //===----------------------------------------------------------------------===//
434 ConstantArray::ConstantArray(const ArrayType *T,
435 const std::vector<Constant*> &V)
436 : Constant(T, ConstantArrayVal,
437 OperandTraits<ConstantArray>::op_end(this) - V.size(),
438 V.size()) {
439 assert(V.size() == T->getNumElements() &&
440 "Invalid initializer vector for constant array");
441 Use *OL = OperandList;
442 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
443 I != E; ++I, ++OL) {
444 Constant *C = *I;
445 assert((C->getType() == T->getElementType() ||
446 (T->isAbstract() &&
447 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
448 "Initializer for array element doesn't match array element type!");
449 *OL = C;
453 Constant *ConstantArray::get(const ArrayType *Ty,
454 const std::vector<Constant*> &V) {
455 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
456 // If this is an all-zero array, return a ConstantAggregateZero object
457 if (!V.empty()) {
458 Constant *C = V[0];
459 if (!C->isNullValue()) {
460 // Implicitly locked.
461 return pImpl->ArrayConstants.getOrCreate(Ty, V);
463 for (unsigned i = 1, e = V.size(); i != e; ++i)
464 if (V[i] != C) {
465 // Implicitly locked.
466 return pImpl->ArrayConstants.getOrCreate(Ty, V);
470 return ConstantAggregateZero::get(Ty);
474 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
475 unsigned NumVals) {
476 // FIXME: make this the primary ctor method.
477 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
480 /// ConstantArray::get(const string&) - Return an array that is initialized to
481 /// contain the specified string. If length is zero then a null terminator is
482 /// added to the specified string so that it may be used in a natural way.
483 /// Otherwise, the length parameter specifies how much of the string to use
484 /// and it won't be null terminated.
486 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
487 bool AddNull) {
488 std::vector<Constant*> ElementVals;
489 for (unsigned i = 0; i < Str.size(); ++i)
490 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
492 // Add a null terminator to the string...
493 if (AddNull) {
494 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
497 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
498 return get(ATy, ElementVals);
503 ConstantStruct::ConstantStruct(const StructType *T,
504 const std::vector<Constant*> &V)
505 : Constant(T, ConstantStructVal,
506 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
507 V.size()) {
508 assert(V.size() == T->getNumElements() &&
509 "Invalid initializer vector for constant structure");
510 Use *OL = OperandList;
511 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
512 I != E; ++I, ++OL) {
513 Constant *C = *I;
514 assert((C->getType() == T->getElementType(I-V.begin()) ||
515 ((T->getElementType(I-V.begin())->isAbstract() ||
516 C->getType()->isAbstract()) &&
517 T->getElementType(I-V.begin())->getTypeID() ==
518 C->getType()->getTypeID())) &&
519 "Initializer for struct element doesn't match struct element type!");
520 *OL = C;
524 // ConstantStruct accessors.
525 Constant* ConstantStruct::get(const StructType* T,
526 const std::vector<Constant*>& V) {
527 LLVMContextImpl* pImpl = T->getContext().pImpl;
529 // Create a ConstantAggregateZero value if all elements are zeros...
530 for (unsigned i = 0, e = V.size(); i != e; ++i)
531 if (!V[i]->isNullValue())
532 // Implicitly locked.
533 return pImpl->StructConstants.getOrCreate(T, V);
535 return ConstantAggregateZero::get(T);
538 Constant* ConstantStruct::get(LLVMContext &Context,
539 const std::vector<Constant*>& V, bool packed) {
540 std::vector<const Type*> StructEls;
541 StructEls.reserve(V.size());
542 for (unsigned i = 0, e = V.size(); i != e; ++i)
543 StructEls.push_back(V[i]->getType());
544 return get(StructType::get(Context, StructEls, packed), V);
547 Constant* ConstantStruct::get(LLVMContext &Context,
548 Constant* const *Vals, unsigned NumVals,
549 bool Packed) {
550 // FIXME: make this the primary ctor method.
551 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
554 ConstantVector::ConstantVector(const VectorType *T,
555 const std::vector<Constant*> &V)
556 : Constant(T, ConstantVectorVal,
557 OperandTraits<ConstantVector>::op_end(this) - V.size(),
558 V.size()) {
559 Use *OL = OperandList;
560 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
561 I != E; ++I, ++OL) {
562 Constant *C = *I;
563 assert((C->getType() == T->getElementType() ||
564 (T->isAbstract() &&
565 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
566 "Initializer for vector element doesn't match vector element type!");
567 *OL = C;
571 // ConstantVector accessors.
572 Constant* ConstantVector::get(const VectorType* T,
573 const std::vector<Constant*>& V) {
574 assert(!V.empty() && "Vectors can't be empty");
575 LLVMContext &Context = T->getContext();
576 LLVMContextImpl *pImpl = Context.pImpl;
578 // If this is an all-undef or alll-zero vector, return a
579 // ConstantAggregateZero or UndefValue.
580 Constant *C = V[0];
581 bool isZero = C->isNullValue();
582 bool isUndef = isa<UndefValue>(C);
584 if (isZero || isUndef) {
585 for (unsigned i = 1, e = V.size(); i != e; ++i)
586 if (V[i] != C) {
587 isZero = isUndef = false;
588 break;
592 if (isZero)
593 return ConstantAggregateZero::get(T);
594 if (isUndef)
595 return UndefValue::get(T);
597 // Implicitly locked.
598 return pImpl->VectorConstants.getOrCreate(T, V);
601 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
602 assert(!V.empty() && "Cannot infer type if V is empty");
603 return get(VectorType::get(V.front()->getType(),V.size()), V);
606 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
607 // FIXME: make this the primary ctor method.
608 return get(std::vector<Constant*>(Vals, Vals+NumVals));
611 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
612 Constant *C = getAdd(C1, C2);
613 // Set nsw attribute, assuming constant folding didn't eliminate the
614 // Add.
615 if (AddOperator *Add = dyn_cast<AddOperator>(C))
616 Add->setHasNoSignedOverflow(true);
617 return C;
620 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
621 Constant *C = getSDiv(C1, C2);
622 // Set exact attribute, assuming constant folding didn't eliminate the
623 // SDiv.
624 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(C))
625 SDiv->setIsExact(true);
626 return C;
629 // Utility function for determining if a ConstantExpr is a CastOp or not. This
630 // can't be inline because we don't want to #include Instruction.h into
631 // Constant.h
632 bool ConstantExpr::isCast() const {
633 return Instruction::isCast(getOpcode());
636 bool ConstantExpr::isCompare() const {
637 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
640 bool ConstantExpr::hasIndices() const {
641 return getOpcode() == Instruction::ExtractValue ||
642 getOpcode() == Instruction::InsertValue;
645 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
646 if (const ExtractValueConstantExpr *EVCE =
647 dyn_cast<ExtractValueConstantExpr>(this))
648 return EVCE->Indices;
650 return cast<InsertValueConstantExpr>(this)->Indices;
653 unsigned ConstantExpr::getPredicate() const {
654 assert(getOpcode() == Instruction::FCmp ||
655 getOpcode() == Instruction::ICmp);
656 return ((const CompareConstantExpr*)this)->predicate;
659 /// getWithOperandReplaced - Return a constant expression identical to this
660 /// one, but with the specified operand set to the specified value.
661 Constant *
662 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
663 assert(OpNo < getNumOperands() && "Operand num is out of range!");
664 assert(Op->getType() == getOperand(OpNo)->getType() &&
665 "Replacing operand with value of different type!");
666 if (getOperand(OpNo) == Op)
667 return const_cast<ConstantExpr*>(this);
669 Constant *Op0, *Op1, *Op2;
670 switch (getOpcode()) {
671 case Instruction::Trunc:
672 case Instruction::ZExt:
673 case Instruction::SExt:
674 case Instruction::FPTrunc:
675 case Instruction::FPExt:
676 case Instruction::UIToFP:
677 case Instruction::SIToFP:
678 case Instruction::FPToUI:
679 case Instruction::FPToSI:
680 case Instruction::PtrToInt:
681 case Instruction::IntToPtr:
682 case Instruction::BitCast:
683 return ConstantExpr::getCast(getOpcode(), Op, getType());
684 case Instruction::Select:
685 Op0 = (OpNo == 0) ? Op : getOperand(0);
686 Op1 = (OpNo == 1) ? Op : getOperand(1);
687 Op2 = (OpNo == 2) ? Op : getOperand(2);
688 return ConstantExpr::getSelect(Op0, Op1, Op2);
689 case Instruction::InsertElement:
690 Op0 = (OpNo == 0) ? Op : getOperand(0);
691 Op1 = (OpNo == 1) ? Op : getOperand(1);
692 Op2 = (OpNo == 2) ? Op : getOperand(2);
693 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
694 case Instruction::ExtractElement:
695 Op0 = (OpNo == 0) ? Op : getOperand(0);
696 Op1 = (OpNo == 1) ? Op : getOperand(1);
697 return ConstantExpr::getExtractElement(Op0, Op1);
698 case Instruction::ShuffleVector:
699 Op0 = (OpNo == 0) ? Op : getOperand(0);
700 Op1 = (OpNo == 1) ? Op : getOperand(1);
701 Op2 = (OpNo == 2) ? Op : getOperand(2);
702 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
703 case Instruction::GetElementPtr: {
704 SmallVector<Constant*, 8> Ops;
705 Ops.resize(getNumOperands()-1);
706 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
707 Ops[i-1] = getOperand(i);
708 if (OpNo == 0)
709 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
710 Ops[OpNo-1] = Op;
711 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
713 default:
714 assert(getNumOperands() == 2 && "Must be binary operator?");
715 Op0 = (OpNo == 0) ? Op : getOperand(0);
716 Op1 = (OpNo == 1) ? Op : getOperand(1);
717 return ConstantExpr::get(getOpcode(), Op0, Op1);
721 /// getWithOperands - This returns the current constant expression with the
722 /// operands replaced with the specified values. The specified operands must
723 /// match count and type with the existing ones.
724 Constant *ConstantExpr::
725 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
726 assert(NumOps == getNumOperands() && "Operand count mismatch!");
727 bool AnyChange = false;
728 for (unsigned i = 0; i != NumOps; ++i) {
729 assert(Ops[i]->getType() == getOperand(i)->getType() &&
730 "Operand type mismatch!");
731 AnyChange |= Ops[i] != getOperand(i);
733 if (!AnyChange) // No operands changed, return self.
734 return const_cast<ConstantExpr*>(this);
736 switch (getOpcode()) {
737 case Instruction::Trunc:
738 case Instruction::ZExt:
739 case Instruction::SExt:
740 case Instruction::FPTrunc:
741 case Instruction::FPExt:
742 case Instruction::UIToFP:
743 case Instruction::SIToFP:
744 case Instruction::FPToUI:
745 case Instruction::FPToSI:
746 case Instruction::PtrToInt:
747 case Instruction::IntToPtr:
748 case Instruction::BitCast:
749 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
750 case Instruction::Select:
751 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
752 case Instruction::InsertElement:
753 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
754 case Instruction::ExtractElement:
755 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
756 case Instruction::ShuffleVector:
757 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
758 case Instruction::GetElementPtr:
759 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
760 case Instruction::ICmp:
761 case Instruction::FCmp:
762 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
763 default:
764 assert(getNumOperands() == 2 && "Must be binary operator?");
765 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
770 //===----------------------------------------------------------------------===//
771 // isValueValidForType implementations
773 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
774 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
775 if (Ty == Type::getInt1Ty(Ty->getContext()))
776 return Val == 0 || Val == 1;
777 if (NumBits >= 64)
778 return true; // always true, has to fit in largest type
779 uint64_t Max = (1ll << NumBits) - 1;
780 return Val <= Max;
783 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
784 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
785 if (Ty == Type::getInt1Ty(Ty->getContext()))
786 return Val == 0 || Val == 1 || Val == -1;
787 if (NumBits >= 64)
788 return true; // always true, has to fit in largest type
789 int64_t Min = -(1ll << (NumBits-1));
790 int64_t Max = (1ll << (NumBits-1)) - 1;
791 return (Val >= Min && Val <= Max);
794 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
795 // convert modifies in place, so make a copy.
796 APFloat Val2 = APFloat(Val);
797 bool losesInfo;
798 switch (Ty->getTypeID()) {
799 default:
800 return false; // These can't be represented as floating point!
802 // FIXME rounding mode needs to be more flexible
803 case Type::FloatTyID: {
804 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
805 return true;
806 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
807 return !losesInfo;
809 case Type::DoubleTyID: {
810 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
811 &Val2.getSemantics() == &APFloat::IEEEdouble)
812 return true;
813 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
814 return !losesInfo;
816 case Type::X86_FP80TyID:
817 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
818 &Val2.getSemantics() == &APFloat::IEEEdouble ||
819 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
820 case Type::FP128TyID:
821 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
822 &Val2.getSemantics() == &APFloat::IEEEdouble ||
823 &Val2.getSemantics() == &APFloat::IEEEquad;
824 case Type::PPC_FP128TyID:
825 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
826 &Val2.getSemantics() == &APFloat::IEEEdouble ||
827 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
831 //===----------------------------------------------------------------------===//
832 // Factory Function Implementation
834 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
836 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
837 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
838 "Cannot create an aggregate zero of non-aggregate type!");
840 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
841 // Implicitly locked.
842 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
845 /// destroyConstant - Remove the constant from the constant table...
847 void ConstantAggregateZero::destroyConstant() {
848 // Implicitly locked.
849 getType()->getContext().pImpl->AggZeroConstants.remove(this);
850 destroyConstantImpl();
853 /// destroyConstant - Remove the constant from the constant table...
855 void ConstantArray::destroyConstant() {
856 // Implicitly locked.
857 getType()->getContext().pImpl->ArrayConstants.remove(this);
858 destroyConstantImpl();
861 /// isString - This method returns true if the array is an array of i8, and
862 /// if the elements of the array are all ConstantInt's.
863 bool ConstantArray::isString() const {
864 // Check the element type for i8...
865 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
866 return false;
867 // Check the elements to make sure they are all integers, not constant
868 // expressions.
869 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
870 if (!isa<ConstantInt>(getOperand(i)))
871 return false;
872 return true;
875 /// isCString - This method returns true if the array is a string (see
876 /// isString) and it ends in a null byte \\0 and does not contains any other
877 /// null bytes except its terminator.
878 bool ConstantArray::isCString() const {
879 // Check the element type for i8...
880 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
881 return false;
883 // Last element must be a null.
884 if (!getOperand(getNumOperands()-1)->isNullValue())
885 return false;
886 // Other elements must be non-null integers.
887 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
888 if (!isa<ConstantInt>(getOperand(i)))
889 return false;
890 if (getOperand(i)->isNullValue())
891 return false;
893 return true;
897 /// getAsString - If the sub-element type of this array is i8
898 /// then this method converts the array to an std::string and returns it.
899 /// Otherwise, it asserts out.
901 std::string ConstantArray::getAsString() const {
902 assert(isString() && "Not a string!");
903 std::string Result;
904 Result.reserve(getNumOperands());
905 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
906 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
907 return Result;
911 //---- ConstantStruct::get() implementation...
914 namespace llvm {
918 // destroyConstant - Remove the constant from the constant table...
920 void ConstantStruct::destroyConstant() {
921 // Implicitly locked.
922 getType()->getContext().pImpl->StructConstants.remove(this);
923 destroyConstantImpl();
926 // destroyConstant - Remove the constant from the constant table...
928 void ConstantVector::destroyConstant() {
929 // Implicitly locked.
930 getType()->getContext().pImpl->VectorConstants.remove(this);
931 destroyConstantImpl();
934 /// This function will return true iff every element in this vector constant
935 /// is set to all ones.
936 /// @returns true iff this constant's emements are all set to all ones.
937 /// @brief Determine if the value is all ones.
938 bool ConstantVector::isAllOnesValue() const {
939 // Check out first element.
940 const Constant *Elt = getOperand(0);
941 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
942 if (!CI || !CI->isAllOnesValue()) return false;
943 // Then make sure all remaining elements point to the same value.
944 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
945 if (getOperand(I) != Elt) return false;
947 return true;
950 /// getSplatValue - If this is a splat constant, where all of the
951 /// elements have the same value, return that value. Otherwise return null.
952 Constant *ConstantVector::getSplatValue() {
953 // Check out first element.
954 Constant *Elt = getOperand(0);
955 // Then make sure all remaining elements point to the same value.
956 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
957 if (getOperand(I) != Elt) return 0;
958 return Elt;
961 //---- ConstantPointerNull::get() implementation...
964 static char getValType(ConstantPointerNull *) {
965 return 0;
969 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
970 // Implicitly locked.
971 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
974 // destroyConstant - Remove the constant from the constant table...
976 void ConstantPointerNull::destroyConstant() {
977 // Implicitly locked.
978 getType()->getContext().pImpl->NullPtrConstants.remove(this);
979 destroyConstantImpl();
983 //---- UndefValue::get() implementation...
986 static char getValType(UndefValue *) {
987 return 0;
990 UndefValue *UndefValue::get(const Type *Ty) {
991 // Implicitly locked.
992 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
995 // destroyConstant - Remove the constant from the constant table.
997 void UndefValue::destroyConstant() {
998 // Implicitly locked.
999 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1000 destroyConstantImpl();
1003 //---- ConstantExpr::get() implementations...
1006 static ExprMapKeyType getValType(ConstantExpr *CE) {
1007 std::vector<Constant*> Operands;
1008 Operands.reserve(CE->getNumOperands());
1009 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1010 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1011 return ExprMapKeyType(CE->getOpcode(), Operands,
1012 CE->isCompare() ? CE->getPredicate() : 0,
1013 CE->hasIndices() ?
1014 CE->getIndices() : SmallVector<unsigned, 4>());
1017 /// This is a utility function to handle folding of casts and lookup of the
1018 /// cast in the ExprConstants map. It is used by the various get* methods below.
1019 static inline Constant *getFoldedCast(
1020 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1021 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1022 // Fold a few common cases
1023 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1024 return FC;
1026 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1028 // Look up the constant in the table first to ensure uniqueness
1029 std::vector<Constant*> argVec(1, C);
1030 ExprMapKeyType Key(opc, argVec);
1032 // Implicitly locked.
1033 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1036 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1037 Instruction::CastOps opc = Instruction::CastOps(oc);
1038 assert(Instruction::isCast(opc) && "opcode out of range");
1039 assert(C && Ty && "Null arguments to getCast");
1040 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1042 switch (opc) {
1043 default:
1044 llvm_unreachable("Invalid cast opcode");
1045 break;
1046 case Instruction::Trunc: return getTrunc(C, Ty);
1047 case Instruction::ZExt: return getZExt(C, Ty);
1048 case Instruction::SExt: return getSExt(C, Ty);
1049 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1050 case Instruction::FPExt: return getFPExtend(C, Ty);
1051 case Instruction::UIToFP: return getUIToFP(C, Ty);
1052 case Instruction::SIToFP: return getSIToFP(C, Ty);
1053 case Instruction::FPToUI: return getFPToUI(C, Ty);
1054 case Instruction::FPToSI: return getFPToSI(C, Ty);
1055 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1056 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1057 case Instruction::BitCast: return getBitCast(C, Ty);
1059 return 0;
1062 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1063 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1064 return getCast(Instruction::BitCast, C, Ty);
1065 return getCast(Instruction::ZExt, C, Ty);
1068 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1069 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1070 return getCast(Instruction::BitCast, C, Ty);
1071 return getCast(Instruction::SExt, C, Ty);
1074 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1075 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1076 return getCast(Instruction::BitCast, C, Ty);
1077 return getCast(Instruction::Trunc, C, Ty);
1080 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1081 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1082 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1084 if (Ty->isInteger())
1085 return getCast(Instruction::PtrToInt, S, Ty);
1086 return getCast(Instruction::BitCast, S, Ty);
1089 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1090 bool isSigned) {
1091 assert(C->getType()->isIntOrIntVector() &&
1092 Ty->isIntOrIntVector() && "Invalid cast");
1093 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1094 unsigned DstBits = Ty->getScalarSizeInBits();
1095 Instruction::CastOps opcode =
1096 (SrcBits == DstBits ? Instruction::BitCast :
1097 (SrcBits > DstBits ? Instruction::Trunc :
1098 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1099 return getCast(opcode, C, Ty);
1102 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1103 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1104 "Invalid cast");
1105 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1106 unsigned DstBits = Ty->getScalarSizeInBits();
1107 if (SrcBits == DstBits)
1108 return C; // Avoid a useless cast
1109 Instruction::CastOps opcode =
1110 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1111 return getCast(opcode, C, Ty);
1114 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1115 #ifndef NDEBUG
1116 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1117 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1118 #endif
1119 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1120 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1121 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1122 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1123 "SrcTy must be larger than DestTy for Trunc!");
1125 return getFoldedCast(Instruction::Trunc, C, Ty);
1128 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1129 #ifndef NDEBUG
1130 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1131 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1132 #endif
1133 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1134 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1135 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1136 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1137 "SrcTy must be smaller than DestTy for SExt!");
1139 return getFoldedCast(Instruction::SExt, C, Ty);
1142 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1143 #ifndef NDEBUG
1144 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1145 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1146 #endif
1147 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1148 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1149 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1150 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1151 "SrcTy must be smaller than DestTy for ZExt!");
1153 return getFoldedCast(Instruction::ZExt, C, Ty);
1156 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1157 #ifndef NDEBUG
1158 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1159 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1160 #endif
1161 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1162 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1163 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1164 "This is an illegal floating point truncation!");
1165 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1168 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1169 #ifndef NDEBUG
1170 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1171 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1172 #endif
1173 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1174 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1175 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1176 "This is an illegal floating point extension!");
1177 return getFoldedCast(Instruction::FPExt, C, Ty);
1180 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1181 #ifndef NDEBUG
1182 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1183 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1184 #endif
1185 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1186 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1187 "This is an illegal uint to floating point cast!");
1188 return getFoldedCast(Instruction::UIToFP, C, Ty);
1191 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1192 #ifndef NDEBUG
1193 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1194 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1195 #endif
1196 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1197 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1198 "This is an illegal sint to floating point cast!");
1199 return getFoldedCast(Instruction::SIToFP, C, Ty);
1202 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1203 #ifndef NDEBUG
1204 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1205 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1206 #endif
1207 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1208 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1209 "This is an illegal floating point to uint cast!");
1210 return getFoldedCast(Instruction::FPToUI, C, Ty);
1213 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1214 #ifndef NDEBUG
1215 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1216 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1217 #endif
1218 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1219 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1220 "This is an illegal floating point to sint cast!");
1221 return getFoldedCast(Instruction::FPToSI, C, Ty);
1224 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1225 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1226 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1227 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1230 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1231 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1232 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1233 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1236 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1237 // BitCast implies a no-op cast of type only. No bits change. However, you
1238 // can't cast pointers to anything but pointers.
1239 #ifndef NDEBUG
1240 const Type *SrcTy = C->getType();
1241 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1242 "BitCast cannot cast pointer to non-pointer and vice versa");
1244 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1245 // or nonptr->ptr). For all the other types, the cast is okay if source and
1246 // destination bit widths are identical.
1247 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1248 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1249 #endif
1250 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1252 // It is common to ask for a bitcast of a value to its own type, handle this
1253 // speedily.
1254 if (C->getType() == DstTy) return C;
1256 return getFoldedCast(Instruction::BitCast, C, DstTy);
1259 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1260 Constant *C1, Constant *C2) {
1261 // Check the operands for consistency first
1262 assert(Opcode >= Instruction::BinaryOpsBegin &&
1263 Opcode < Instruction::BinaryOpsEnd &&
1264 "Invalid opcode in binary constant expression");
1265 assert(C1->getType() == C2->getType() &&
1266 "Operand types in binary constant expression should match");
1268 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1269 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1270 Opcode, C1, C2))
1271 return FC; // Fold a few common cases...
1273 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1274 ExprMapKeyType Key(Opcode, argVec);
1276 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1278 // Implicitly locked.
1279 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1282 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1283 Constant *C1, Constant *C2) {
1284 switch (predicate) {
1285 default: llvm_unreachable("Invalid CmpInst predicate");
1286 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1287 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1288 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1289 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1290 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1291 case CmpInst::FCMP_TRUE:
1292 return getFCmp(predicate, C1, C2);
1294 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1295 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1296 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1297 case CmpInst::ICMP_SLE:
1298 return getICmp(predicate, C1, C2);
1302 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1303 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1304 if (C1->getType()->isFPOrFPVector()) {
1305 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1306 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1307 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1309 #ifndef NDEBUG
1310 switch (Opcode) {
1311 case Instruction::Add:
1312 case Instruction::Sub:
1313 case Instruction::Mul:
1314 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1315 assert(C1->getType()->isIntOrIntVector() &&
1316 "Tried to create an integer operation on a non-integer type!");
1317 break;
1318 case Instruction::FAdd:
1319 case Instruction::FSub:
1320 case Instruction::FMul:
1321 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1322 assert(C1->getType()->isFPOrFPVector() &&
1323 "Tried to create a floating-point operation on a "
1324 "non-floating-point type!");
1325 break;
1326 case Instruction::UDiv:
1327 case Instruction::SDiv:
1328 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1329 assert(C1->getType()->isIntOrIntVector() &&
1330 "Tried to create an arithmetic operation on a non-arithmetic type!");
1331 break;
1332 case Instruction::FDiv:
1333 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1334 assert(C1->getType()->isFPOrFPVector() &&
1335 "Tried to create an arithmetic operation on a non-arithmetic type!");
1336 break;
1337 case Instruction::URem:
1338 case Instruction::SRem:
1339 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1340 assert(C1->getType()->isIntOrIntVector() &&
1341 "Tried to create an arithmetic operation on a non-arithmetic type!");
1342 break;
1343 case Instruction::FRem:
1344 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1345 assert(C1->getType()->isFPOrFPVector() &&
1346 "Tried to create an arithmetic operation on a non-arithmetic type!");
1347 break;
1348 case Instruction::And:
1349 case Instruction::Or:
1350 case Instruction::Xor:
1351 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1352 assert(C1->getType()->isIntOrIntVector() &&
1353 "Tried to create a logical operation on a non-integral type!");
1354 break;
1355 case Instruction::Shl:
1356 case Instruction::LShr:
1357 case Instruction::AShr:
1358 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1359 assert(C1->getType()->isIntOrIntVector() &&
1360 "Tried to create a shift operation on a non-integer type!");
1361 break;
1362 default:
1363 break;
1365 #endif
1367 return getTy(C1->getType(), Opcode, C1, C2);
1370 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1371 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1372 // Note that a non-inbounds gep is used, as null isn't within any object.
1373 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1374 Constant *GEP = getGetElementPtr(
1375 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1376 return getCast(Instruction::PtrToInt, GEP,
1377 Type::getInt64Ty(Ty->getContext()));
1380 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1381 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1382 // Note that a non-inbounds gep is used, as null isn't within any object.
1383 const Type *AligningTy = StructType::get(Ty->getContext(),
1384 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1385 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1386 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1387 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1388 Constant *Indices[2] = { Zero, One };
1389 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1390 return getCast(Instruction::PtrToInt, GEP,
1391 Type::getInt32Ty(Ty->getContext()));
1395 Constant *ConstantExpr::getCompare(unsigned short pred,
1396 Constant *C1, Constant *C2) {
1397 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1398 return getCompareTy(pred, C1, C2);
1401 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1402 Constant *V1, Constant *V2) {
1403 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1405 if (ReqTy == V1->getType())
1406 if (Constant *SC = ConstantFoldSelectInstruction(
1407 ReqTy->getContext(), C, V1, V2))
1408 return SC; // Fold common cases
1410 std::vector<Constant*> argVec(3, C);
1411 argVec[1] = V1;
1412 argVec[2] = V2;
1413 ExprMapKeyType Key(Instruction::Select, argVec);
1415 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1417 // Implicitly locked.
1418 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1421 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1422 Value* const *Idxs,
1423 unsigned NumIdx) {
1424 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1425 Idxs+NumIdx) ==
1426 cast<PointerType>(ReqTy)->getElementType() &&
1427 "GEP indices invalid!");
1429 if (Constant *FC = ConstantFoldGetElementPtr(
1430 ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1431 return FC; // Fold a few common cases...
1433 assert(isa<PointerType>(C->getType()) &&
1434 "Non-pointer type for constant GetElementPtr expression");
1435 // Look up the constant in the table first to ensure uniqueness
1436 std::vector<Constant*> ArgVec;
1437 ArgVec.reserve(NumIdx+1);
1438 ArgVec.push_back(C);
1439 for (unsigned i = 0; i != NumIdx; ++i)
1440 ArgVec.push_back(cast<Constant>(Idxs[i]));
1441 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1443 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1445 // Implicitly locked.
1446 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1449 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1450 unsigned NumIdx) {
1451 // Get the result type of the getelementptr!
1452 const Type *Ty =
1453 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1454 assert(Ty && "GEP indices invalid!");
1455 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1456 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1459 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1460 Value* const *Idxs,
1461 unsigned NumIdx) {
1462 Constant *Result = getGetElementPtr(C, Idxs, NumIdx);
1463 // Set in bounds attribute, assuming constant folding didn't eliminate the
1464 // GEP.
1465 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Result))
1466 GEP->setIsInBounds(true);
1467 return Result;
1470 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1471 unsigned NumIdx) {
1472 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1475 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1476 Constant* const *Idxs,
1477 unsigned NumIdx) {
1478 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1481 Constant *
1482 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1483 assert(LHS->getType() == RHS->getType());
1484 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1485 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1487 if (Constant *FC = ConstantFoldCompareInstruction(
1488 LHS->getContext(), pred, LHS, RHS))
1489 return FC; // Fold a few common cases...
1491 // Look up the constant in the table first to ensure uniqueness
1492 std::vector<Constant*> ArgVec;
1493 ArgVec.push_back(LHS);
1494 ArgVec.push_back(RHS);
1495 // Get the key type with both the opcode and predicate
1496 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1498 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1500 // Implicitly locked.
1501 return
1502 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1505 Constant *
1506 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1507 assert(LHS->getType() == RHS->getType());
1508 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1510 if (Constant *FC = ConstantFoldCompareInstruction(
1511 LHS->getContext(), pred, LHS, RHS))
1512 return FC; // Fold a few common cases...
1514 // Look up the constant in the table first to ensure uniqueness
1515 std::vector<Constant*> ArgVec;
1516 ArgVec.push_back(LHS);
1517 ArgVec.push_back(RHS);
1518 // Get the key type with both the opcode and predicate
1519 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1521 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1523 // Implicitly locked.
1524 return
1525 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1528 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1529 Constant *Idx) {
1530 if (Constant *FC = ConstantFoldExtractElementInstruction(
1531 ReqTy->getContext(), Val, Idx))
1532 return FC; // Fold a few common cases...
1533 // Look up the constant in the table first to ensure uniqueness
1534 std::vector<Constant*> ArgVec(1, Val);
1535 ArgVec.push_back(Idx);
1536 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1538 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1540 // Implicitly locked.
1541 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1544 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1545 assert(isa<VectorType>(Val->getType()) &&
1546 "Tried to create extractelement operation on non-vector type!");
1547 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1548 "Extractelement index must be i32 type!");
1549 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1550 Val, Idx);
1553 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1554 Constant *Elt, Constant *Idx) {
1555 if (Constant *FC = ConstantFoldInsertElementInstruction(
1556 ReqTy->getContext(), Val, Elt, Idx))
1557 return FC; // Fold a few common cases...
1558 // Look up the constant in the table first to ensure uniqueness
1559 std::vector<Constant*> ArgVec(1, Val);
1560 ArgVec.push_back(Elt);
1561 ArgVec.push_back(Idx);
1562 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1564 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1566 // Implicitly locked.
1567 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1570 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1571 Constant *Idx) {
1572 assert(isa<VectorType>(Val->getType()) &&
1573 "Tried to create insertelement operation on non-vector type!");
1574 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1575 && "Insertelement types must match!");
1576 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1577 "Insertelement index must be i32 type!");
1578 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1581 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1582 Constant *V2, Constant *Mask) {
1583 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1584 ReqTy->getContext(), V1, V2, Mask))
1585 return FC; // Fold a few common cases...
1586 // Look up the constant in the table first to ensure uniqueness
1587 std::vector<Constant*> ArgVec(1, V1);
1588 ArgVec.push_back(V2);
1589 ArgVec.push_back(Mask);
1590 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1592 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1594 // Implicitly locked.
1595 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1598 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1599 Constant *Mask) {
1600 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1601 "Invalid shuffle vector constant expr operands!");
1603 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1604 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1605 const Type *ShufTy = VectorType::get(EltTy, NElts);
1606 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1609 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1610 Constant *Val,
1611 const unsigned *Idxs, unsigned NumIdx) {
1612 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1613 Idxs+NumIdx) == Val->getType() &&
1614 "insertvalue indices invalid!");
1615 assert(Agg->getType() == ReqTy &&
1616 "insertvalue type invalid!");
1617 assert(Agg->getType()->isFirstClassType() &&
1618 "Non-first-class type for constant InsertValue expression");
1619 Constant *FC = ConstantFoldInsertValueInstruction(
1620 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1621 assert(FC && "InsertValue constant expr couldn't be folded!");
1622 return FC;
1625 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1626 const unsigned *IdxList, unsigned NumIdx) {
1627 assert(Agg->getType()->isFirstClassType() &&
1628 "Tried to create insertelement operation on non-first-class type!");
1630 const Type *ReqTy = Agg->getType();
1631 #ifndef NDEBUG
1632 const Type *ValTy =
1633 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1634 #endif
1635 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1636 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1639 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1640 const unsigned *Idxs, unsigned NumIdx) {
1641 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1642 Idxs+NumIdx) == ReqTy &&
1643 "extractvalue indices invalid!");
1644 assert(Agg->getType()->isFirstClassType() &&
1645 "Non-first-class type for constant extractvalue expression");
1646 Constant *FC = ConstantFoldExtractValueInstruction(
1647 ReqTy->getContext(), Agg, Idxs, NumIdx);
1648 assert(FC && "ExtractValue constant expr couldn't be folded!");
1649 return FC;
1652 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1653 const unsigned *IdxList, unsigned NumIdx) {
1654 assert(Agg->getType()->isFirstClassType() &&
1655 "Tried to create extractelement operation on non-first-class type!");
1657 const Type *ReqTy =
1658 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1659 assert(ReqTy && "extractvalue indices invalid!");
1660 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1663 Constant* ConstantExpr::getNeg(Constant* C) {
1664 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1665 if (C->getType()->isFPOrFPVector())
1666 return getFNeg(C);
1667 assert(C->getType()->isIntOrIntVector() &&
1668 "Cannot NEG a nonintegral value!");
1669 return get(Instruction::Sub,
1670 ConstantFP::getZeroValueForNegation(C->getType()),
1674 Constant* ConstantExpr::getFNeg(Constant* C) {
1675 assert(C->getType()->isFPOrFPVector() &&
1676 "Cannot FNEG a non-floating-point value!");
1677 return get(Instruction::FSub,
1678 ConstantFP::getZeroValueForNegation(C->getType()),
1682 Constant* ConstantExpr::getNot(Constant* C) {
1683 assert(C->getType()->isIntOrIntVector() &&
1684 "Cannot NOT a nonintegral value!");
1685 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1688 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1689 return get(Instruction::Add, C1, C2);
1692 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1693 return get(Instruction::FAdd, C1, C2);
1696 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1697 return get(Instruction::Sub, C1, C2);
1700 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1701 return get(Instruction::FSub, C1, C2);
1704 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1705 return get(Instruction::Mul, C1, C2);
1708 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1709 return get(Instruction::FMul, C1, C2);
1712 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1713 return get(Instruction::UDiv, C1, C2);
1716 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1717 return get(Instruction::SDiv, C1, C2);
1720 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1721 return get(Instruction::FDiv, C1, C2);
1724 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1725 return get(Instruction::URem, C1, C2);
1728 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1729 return get(Instruction::SRem, C1, C2);
1732 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1733 return get(Instruction::FRem, C1, C2);
1736 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1737 return get(Instruction::And, C1, C2);
1740 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1741 return get(Instruction::Or, C1, C2);
1744 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1745 return get(Instruction::Xor, C1, C2);
1748 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1749 return get(Instruction::Shl, C1, C2);
1752 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1753 return get(Instruction::LShr, C1, C2);
1756 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1757 return get(Instruction::AShr, C1, C2);
1760 // destroyConstant - Remove the constant from the constant table...
1762 void ConstantExpr::destroyConstant() {
1763 // Implicitly locked.
1764 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1765 pImpl->ExprConstants.remove(this);
1766 destroyConstantImpl();
1769 const char *ConstantExpr::getOpcodeName() const {
1770 return Instruction::getOpcodeName(getOpcode());
1773 //===----------------------------------------------------------------------===//
1774 // replaceUsesOfWithOnConstant implementations
1776 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1777 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1778 /// etc.
1780 /// Note that we intentionally replace all uses of From with To here. Consider
1781 /// a large array that uses 'From' 1000 times. By handling this case all here,
1782 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1783 /// single invocation handles all 1000 uses. Handling them one at a time would
1784 /// work, but would be really slow because it would have to unique each updated
1785 /// array instance.
1787 static std::vector<Constant*> getValType(ConstantArray *CA) {
1788 std::vector<Constant*> Elements;
1789 Elements.reserve(CA->getNumOperands());
1790 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1791 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1792 return Elements;
1796 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1797 Use *U) {
1798 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1799 Constant *ToC = cast<Constant>(To);
1801 LLVMContext &Context = getType()->getContext();
1802 LLVMContextImpl *pImpl = Context.pImpl;
1804 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1805 Lookup.first.first = getType();
1806 Lookup.second = this;
1808 std::vector<Constant*> &Values = Lookup.first.second;
1809 Values.reserve(getNumOperands()); // Build replacement array.
1811 // Fill values with the modified operands of the constant array. Also,
1812 // compute whether this turns into an all-zeros array.
1813 bool isAllZeros = false;
1814 unsigned NumUpdated = 0;
1815 if (!ToC->isNullValue()) {
1816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1817 Constant *Val = cast<Constant>(O->get());
1818 if (Val == From) {
1819 Val = ToC;
1820 ++NumUpdated;
1822 Values.push_back(Val);
1824 } else {
1825 isAllZeros = true;
1826 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1827 Constant *Val = cast<Constant>(O->get());
1828 if (Val == From) {
1829 Val = ToC;
1830 ++NumUpdated;
1832 Values.push_back(Val);
1833 if (isAllZeros) isAllZeros = Val->isNullValue();
1837 Constant *Replacement = 0;
1838 if (isAllZeros) {
1839 Replacement = ConstantAggregateZero::get(getType());
1840 } else {
1841 // Check to see if we have this array type already.
1842 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1843 bool Exists;
1844 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1845 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1847 if (Exists) {
1848 Replacement = cast<Constant>(I->second);
1849 } else {
1850 // Okay, the new shape doesn't exist in the system yet. Instead of
1851 // creating a new constant array, inserting it, replaceallusesof'ing the
1852 // old with the new, then deleting the old... just update the current one
1853 // in place!
1854 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1856 // Update to the new value. Optimize for the case when we have a single
1857 // operand that we're changing, but handle bulk updates efficiently.
1858 if (NumUpdated == 1) {
1859 unsigned OperandToUpdate = U - OperandList;
1860 assert(getOperand(OperandToUpdate) == From &&
1861 "ReplaceAllUsesWith broken!");
1862 setOperand(OperandToUpdate, ToC);
1863 } else {
1864 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1865 if (getOperand(i) == From)
1866 setOperand(i, ToC);
1868 return;
1872 // Otherwise, I do need to replace this with an existing value.
1873 assert(Replacement != this && "I didn't contain From!");
1875 // Everyone using this now uses the replacement.
1876 uncheckedReplaceAllUsesWith(Replacement);
1878 // Delete the old constant!
1879 destroyConstant();
1882 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1883 std::vector<Constant*> Elements;
1884 Elements.reserve(CS->getNumOperands());
1885 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1886 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1887 return Elements;
1890 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1891 Use *U) {
1892 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1893 Constant *ToC = cast<Constant>(To);
1895 unsigned OperandToUpdate = U-OperandList;
1896 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1898 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1899 Lookup.first.first = getType();
1900 Lookup.second = this;
1901 std::vector<Constant*> &Values = Lookup.first.second;
1902 Values.reserve(getNumOperands()); // Build replacement struct.
1905 // Fill values with the modified operands of the constant struct. Also,
1906 // compute whether this turns into an all-zeros struct.
1907 bool isAllZeros = false;
1908 if (!ToC->isNullValue()) {
1909 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1910 Values.push_back(cast<Constant>(O->get()));
1911 } else {
1912 isAllZeros = true;
1913 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1914 Constant *Val = cast<Constant>(O->get());
1915 Values.push_back(Val);
1916 if (isAllZeros) isAllZeros = Val->isNullValue();
1919 Values[OperandToUpdate] = ToC;
1921 LLVMContext &Context = getType()->getContext();
1922 LLVMContextImpl *pImpl = Context.pImpl;
1924 Constant *Replacement = 0;
1925 if (isAllZeros) {
1926 Replacement = ConstantAggregateZero::get(getType());
1927 } else {
1928 // Check to see if we have this array type already.
1929 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1930 bool Exists;
1931 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1932 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1934 if (Exists) {
1935 Replacement = cast<Constant>(I->second);
1936 } else {
1937 // Okay, the new shape doesn't exist in the system yet. Instead of
1938 // creating a new constant struct, inserting it, replaceallusesof'ing the
1939 // old with the new, then deleting the old... just update the current one
1940 // in place!
1941 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1943 // Update to the new value.
1944 setOperand(OperandToUpdate, ToC);
1945 return;
1949 assert(Replacement != this && "I didn't contain From!");
1951 // Everyone using this now uses the replacement.
1952 uncheckedReplaceAllUsesWith(Replacement);
1954 // Delete the old constant!
1955 destroyConstant();
1958 static std::vector<Constant*> getValType(ConstantVector *CP) {
1959 std::vector<Constant*> Elements;
1960 Elements.reserve(CP->getNumOperands());
1961 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1962 Elements.push_back(CP->getOperand(i));
1963 return Elements;
1966 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1967 Use *U) {
1968 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1970 std::vector<Constant*> Values;
1971 Values.reserve(getNumOperands()); // Build replacement array...
1972 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1973 Constant *Val = getOperand(i);
1974 if (Val == From) Val = cast<Constant>(To);
1975 Values.push_back(Val);
1978 Constant *Replacement = get(getType(), Values);
1979 assert(Replacement != this && "I didn't contain From!");
1981 // Everyone using this now uses the replacement.
1982 uncheckedReplaceAllUsesWith(Replacement);
1984 // Delete the old constant!
1985 destroyConstant();
1988 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1989 Use *U) {
1990 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1991 Constant *To = cast<Constant>(ToV);
1993 Constant *Replacement = 0;
1994 if (getOpcode() == Instruction::GetElementPtr) {
1995 SmallVector<Constant*, 8> Indices;
1996 Constant *Pointer = getOperand(0);
1997 Indices.reserve(getNumOperands()-1);
1998 if (Pointer == From) Pointer = To;
2000 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2001 Constant *Val = getOperand(i);
2002 if (Val == From) Val = To;
2003 Indices.push_back(Val);
2005 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2006 &Indices[0], Indices.size());
2007 } else if (getOpcode() == Instruction::ExtractValue) {
2008 Constant *Agg = getOperand(0);
2009 if (Agg == From) Agg = To;
2011 const SmallVector<unsigned, 4> &Indices = getIndices();
2012 Replacement = ConstantExpr::getExtractValue(Agg,
2013 &Indices[0], Indices.size());
2014 } else if (getOpcode() == Instruction::InsertValue) {
2015 Constant *Agg = getOperand(0);
2016 Constant *Val = getOperand(1);
2017 if (Agg == From) Agg = To;
2018 if (Val == From) Val = To;
2020 const SmallVector<unsigned, 4> &Indices = getIndices();
2021 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2022 &Indices[0], Indices.size());
2023 } else if (isCast()) {
2024 assert(getOperand(0) == From && "Cast only has one use!");
2025 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2026 } else if (getOpcode() == Instruction::Select) {
2027 Constant *C1 = getOperand(0);
2028 Constant *C2 = getOperand(1);
2029 Constant *C3 = getOperand(2);
2030 if (C1 == From) C1 = To;
2031 if (C2 == From) C2 = To;
2032 if (C3 == From) C3 = To;
2033 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2034 } else if (getOpcode() == Instruction::ExtractElement) {
2035 Constant *C1 = getOperand(0);
2036 Constant *C2 = getOperand(1);
2037 if (C1 == From) C1 = To;
2038 if (C2 == From) C2 = To;
2039 Replacement = ConstantExpr::getExtractElement(C1, C2);
2040 } else if (getOpcode() == Instruction::InsertElement) {
2041 Constant *C1 = getOperand(0);
2042 Constant *C2 = getOperand(1);
2043 Constant *C3 = getOperand(1);
2044 if (C1 == From) C1 = To;
2045 if (C2 == From) C2 = To;
2046 if (C3 == From) C3 = To;
2047 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2048 } else if (getOpcode() == Instruction::ShuffleVector) {
2049 Constant *C1 = getOperand(0);
2050 Constant *C2 = getOperand(1);
2051 Constant *C3 = getOperand(2);
2052 if (C1 == From) C1 = To;
2053 if (C2 == From) C2 = To;
2054 if (C3 == From) C3 = To;
2055 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2056 } else if (isCompare()) {
2057 Constant *C1 = getOperand(0);
2058 Constant *C2 = getOperand(1);
2059 if (C1 == From) C1 = To;
2060 if (C2 == From) C2 = To;
2061 if (getOpcode() == Instruction::ICmp)
2062 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2063 else {
2064 assert(getOpcode() == Instruction::FCmp);
2065 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2067 } else if (getNumOperands() == 2) {
2068 Constant *C1 = getOperand(0);
2069 Constant *C2 = getOperand(1);
2070 if (C1 == From) C1 = To;
2071 if (C2 == From) C2 = To;
2072 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2073 } else {
2074 llvm_unreachable("Unknown ConstantExpr type!");
2075 return;
2078 assert(Replacement != this && "I didn't contain From!");
2080 // Everyone using this now uses the replacement.
2081 uncheckedReplaceAllUsesWith(Replacement);
2083 // Delete the old constant!
2084 destroyConstant();