comparison lib/IR/Constants.cpp @ 148:63bd29f05246

merged
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Wed, 14 Aug 2019 19:46:37 +0900
parents c2174574ed3a
children
comparison
equal deleted inserted replaced
146:3fc4d5c3e21e 148:63bd29f05246
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===// 1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 // 2 //
3 // The LLVM Compiler Infrastructure 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // 4 // See https://llvm.org/LICENSE.txt for license information.
5 // This file is distributed under the University of Illinois Open Source 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 // License. See LICENSE.TXT for details.
7 // 6 //
8 //===----------------------------------------------------------------------===// 7 //===----------------------------------------------------------------------===//
9 // 8 //
10 // This file implements the Constant* classes. 9 // This file implements the Constant* classes.
11 // 10 //
182 181
183 // Check for FP which are bitcasted from INT_MIN integers 182 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 183 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue(); 184 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186 185
187 // Check for constant vectors which are splats of INT_MIN values. 186 // Check that vectors don't contain INT_MIN
188 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 187 if (this->getType()->isVectorTy()) {
189 if (Constant *Splat = CV->getSplatValue()) 188 unsigned NumElts = this->getType()->getVectorNumElements();
190 return Splat->isNotMinSignedValue(); 189 for (unsigned i = 0; i != NumElts; ++i) {
191 190 Constant *Elt = this->getAggregateElement(i);
192 // Check for constant vectors which are splats of INT_MIN values. 191 if (!Elt || !Elt->isNotMinSignedValue())
193 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) { 192 return false;
194 if (CV->isSplat()) {
195 if (CV->getElementType()->isFloatingPointTy())
196 return !CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
197 return !CV->getElementAsAPInt(0).isMinSignedValue();
198 } 193 }
194 return true;
199 } 195 }
200 196
201 // It *may* contain INT_MIN, we can't tell. 197 // It *may* contain INT_MIN, we can't tell.
198 return false;
199 }
200
201 bool Constant::isFiniteNonZeroFP() const {
202 if (auto *CFP = dyn_cast<ConstantFP>(this))
203 return CFP->getValueAPF().isFiniteNonZero();
204 if (!getType()->isVectorTy())
205 return false;
206 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209 return false;
210 }
211 return true;
212 }
213
214 bool Constant::isNormalFP() const {
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isNormal();
217 if (!getType()->isVectorTy())
218 return false;
219 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221 if (!CFP || !CFP->getValueAPF().isNormal())
222 return false;
223 }
224 return true;
225 }
226
227 bool Constant::hasExactInverseFP() const {
228 if (auto *CFP = dyn_cast<ConstantFP>(this))
229 return CFP->getValueAPF().getExactInverse(nullptr);
230 if (!getType()->isVectorTy())
231 return false;
232 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235 return false;
236 }
237 return true;
238 }
239
240 bool Constant::isNaN() const {
241 if (auto *CFP = dyn_cast<ConstantFP>(this))
242 return CFP->isNaN();
243 if (!getType()->isVectorTy())
244 return false;
245 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247 if (!CFP || !CFP->isNaN())
248 return false;
249 }
250 return true;
251 }
252
253 bool Constant::containsUndefElement() const {
254 if (!getType()->isVectorTy())
255 return false;
256 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257 if (isa<UndefValue>(getAggregateElement(i)))
258 return true;
259
260 return false;
261 }
262
263 bool Constant::containsConstantExpression() const {
264 if (!getType()->isVectorTy())
265 return false;
266 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
267 if (isa<ConstantExpr>(getAggregateElement(i)))
268 return true;
269
202 return false; 270 return false;
203 } 271 }
204 272
205 /// Constructor to create a '0' constant of arbitrary type. 273 /// Constructor to create a '0' constant of arbitrary type.
206 Constant *Constant::getNullValue(Type *Ty) { 274 Constant *Constant::getNullValue(Type *Ty) {
289 return nullptr; 357 return nullptr;
290 } 358 }
291 359
292 Constant *Constant::getAggregateElement(Constant *Elt) const { 360 Constant *Constant::getAggregateElement(Constant *Elt) const {
293 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer"); 361 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) 362 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
363 // Check if the constant fits into an uint64_t.
364 if (CI->getValue().getActiveBits() > 64)
365 return nullptr;
295 return getAggregateElement(CI->getZExtValue()); 366 return getAggregateElement(CI->getZExtValue());
367 }
296 return nullptr; 368 return nullptr;
297 } 369 }
298 370
299 void Constant::destroyConstant() { 371 void Constant::destroyConstant() {
300 /// First call destroyConstantImpl on the subclass. This gives the subclass 372 /// First call destroyConstantImpl on the subclass. This gives the subclass
428 return true; // Global reference. 500 return true; // Global reference.
429 501
430 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this)) 502 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
431 return BA->getFunction()->needsRelocation(); 503 return BA->getFunction()->needsRelocation();
432 504
433 // While raw uses of blockaddress need to be relocated, differences between 505 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
434 // two of them don't when they are for labels in the same function. This is a
435 // common idiom when creating a table for the indirect goto extension, so we
436 // handle it efficiently here.
437 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
438 if (CE->getOpcode() == Instruction::Sub) { 506 if (CE->getOpcode() == Instruction::Sub) {
439 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0)); 507 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
440 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1)); 508 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
441 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt && 509 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
442 RHS->getOpcode() == Instruction::PtrToInt && 510 RHS->getOpcode() == Instruction::PtrToInt) {
443 isa<BlockAddress>(LHS->getOperand(0)) && 511 Constant *LHSOp0 = LHS->getOperand(0);
444 isa<BlockAddress>(RHS->getOperand(0)) && 512 Constant *RHSOp0 = RHS->getOperand(0);
445 cast<BlockAddress>(LHS->getOperand(0))->getFunction() == 513
446 cast<BlockAddress>(RHS->getOperand(0))->getFunction()) 514 // While raw uses of blockaddress need to be relocated, differences
447 return false; 515 // between two of them don't when they are for labels in the same
516 // function. This is a common idiom when creating a table for the
517 // indirect goto extension, so we handle it efficiently here.
518 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
519 cast<BlockAddress>(LHSOp0)->getFunction() ==
520 cast<BlockAddress>(RHSOp0)->getFunction())
521 return false;
522
523 // Relative pointers do not need to be dynamically relocated.
524 if (auto *LHSGV = dyn_cast<GlobalValue>(
525 LHSOp0->stripPointerCastsNoFollowAliases()))
526 if (auto *RHSGV = dyn_cast<GlobalValue>(
527 RHSOp0->stripPointerCastsNoFollowAliases()))
528 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
529 return false;
530 }
448 } 531 }
532 }
449 533
450 bool Result = false; 534 bool Result = false;
451 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 535 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
452 Result |= cast<Constant>(getOperand(i))->needsRelocation(); 536 Result |= cast<Constant>(getOperand(i))->needsRelocation();
453 537
655 739
656 // For vectors, broadcast the value. 740 // For vectors, broadcast the value.
657 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 741 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
658 return ConstantVector::getSplat(VTy->getNumElements(), C); 742 return ConstantVector::getSplat(VTy->getNumElements(), C);
659 743
660 return C; 744 return C;
661 } 745 }
662 746
663 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) { 747 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
664 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType()); 748 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
665 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type); 749 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
666 Constant *C = get(Ty->getContext(), NaN); 750 Constant *C = get(Ty->getContext(), NaN);
667 751
668 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 752 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
669 return ConstantVector::getSplat(VTy->getNumElements(), C); 753 return ConstantVector::getSplat(VTy->getNumElements(), C);
670 754
755 return C;
756 }
757
758 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
759 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
760 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
761 Constant *C = get(Ty->getContext(), NaN);
762
763 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
764 return ConstantVector::getSplat(VTy->getNumElements(), C);
765
766 return C;
767 }
768
769 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
770 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
771 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
772 Constant *C = get(Ty->getContext(), NaN);
773
774 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
775 return ConstantVector::getSplat(VTy->getNumElements(), C);
776
671 return C; 777 return C;
672 } 778 }
673 779
674 Constant *ConstantFP::getNegativeZero(Type *Ty) { 780 Constant *ConstantFP::getNegativeZero(Type *Ty) {
675 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType()); 781 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
708 else if (&V.getSemantics() == &APFloat::x87DoubleExtended()) 814 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
709 Ty = Type::getX86_FP80Ty(Context); 815 Ty = Type::getX86_FP80Ty(Context);
710 else if (&V.getSemantics() == &APFloat::IEEEquad()) 816 else if (&V.getSemantics() == &APFloat::IEEEquad())
711 Ty = Type::getFP128Ty(Context); 817 Ty = Type::getFP128Ty(Context);
712 else { 818 else {
713 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() && 819 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
714 "Unknown FP format"); 820 "Unknown FP format");
715 Ty = Type::getPPC_FP128Ty(Context); 821 Ty = Type::getPPC_FP128Ty(Context);
716 } 822 }
717 Slot.reset(new ConstantFP(Ty, V)); 823 Slot.reset(new ConstantFP(Ty, V));
718 } 824 }
876 982
877 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT, 983 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
878 ArrayRef<Constant *> V) 984 ArrayRef<Constant *> V)
879 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(), 985 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
880 V.size()) { 986 V.size()) {
881 std::copy(V.begin(), V.end(), op_begin()); 987 llvm::copy(V, op_begin());
882 988
883 // Check that types match, unless this is an opaque struct. 989 // Check that types match, unless this is an opaque struct.
884 if (auto *ST = dyn_cast<StructType>(T)) 990 if (auto *ST = dyn_cast<StructType>(T))
885 if (ST->isOpaque()) 991 if (ST->isOpaque())
886 return; 992 return;
961 "Incorrect # elements specified to ConstantStruct::get"); 1067 "Incorrect # elements specified to ConstantStruct::get");
962 1068
963 // Create a ConstantAggregateZero value if all elements are zeros. 1069 // Create a ConstantAggregateZero value if all elements are zeros.
964 bool isZero = true; 1070 bool isZero = true;
965 bool isUndef = false; 1071 bool isUndef = false;
966 1072
967 if (!V.empty()) { 1073 if (!V.empty()) {
968 isUndef = isa<UndefValue>(V[0]); 1074 isUndef = isa<UndefValue>(V[0]);
969 isZero = V[0]->isNullValue(); 1075 isZero = V[0]->isNullValue();
970 if (isUndef || isZero) { 1076 if (isUndef || isZero) {
971 for (unsigned i = 0, e = V.size(); i != e; ++i) { 1077 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1222 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); 1328 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1223 return !losesInfo; 1329 return !losesInfo;
1224 } 1330 }
1225 case Type::X86_FP80TyID: 1331 case Type::X86_FP80TyID:
1226 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1332 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1227 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1333 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1228 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1334 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1229 &Val2.getSemantics() == &APFloat::x87DoubleExtended(); 1335 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1230 case Type::FP128TyID: 1336 case Type::FP128TyID:
1231 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1337 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1232 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1338 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1233 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1339 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1234 &Val2.getSemantics() == &APFloat::IEEEquad(); 1340 &Val2.getSemantics() == &APFloat::IEEEquad();
1235 case Type::PPC_FP128TyID: 1341 case Type::PPC_FP128TyID:
1236 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1342 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1237 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1343 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1238 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1344 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1239 &Val2.getSemantics() == &APFloat::PPCDoubleDouble(); 1345 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1240 } 1346 }
1241 } 1347 }
1242 1348
1716 C = getBitCast(C, MidTy); 1822 C = getBitCast(C, MidTy);
1717 } 1823 }
1718 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced); 1824 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1719 } 1825 }
1720 1826
1827 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1828 Type *OnlyIfReducedTy) {
1829 // Check the operands for consistency first.
1830 assert(Instruction::isUnaryOp(Opcode) &&
1831 "Invalid opcode in unary constant expression");
1832
1833 #ifndef NDEBUG
1834 switch (Opcode) {
1835 case Instruction::FNeg:
1836 assert(C->getType()->isFPOrFPVectorTy() &&
1837 "Tried to create a floating-point operation on a "
1838 "non-floating-point type!");
1839 break;
1840 default:
1841 break;
1842 }
1843 #endif
1844
1845 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
1846 return FC;
1847
1848 if (OnlyIfReducedTy == C->getType())
1849 return nullptr;
1850
1851 Constant *ArgVec[] = { C };
1852 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1853
1854 LLVMContextImpl *pImpl = C->getContext().pImpl;
1855 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1856 }
1857
1721 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2, 1858 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1722 unsigned Flags, Type *OnlyIfReducedTy) { 1859 unsigned Flags, Type *OnlyIfReducedTy) {
1723 // Check the operands for consistency first. 1860 // Check the operands for consistency first.
1724 assert(Opcode >= Instruction::BinaryOpsBegin && 1861 assert(Instruction::isBinaryOp(Opcode) &&
1725 Opcode < Instruction::BinaryOpsEnd &&
1726 "Invalid opcode in binary constant expression"); 1862 "Invalid opcode in binary constant expression");
1727 assert(C1->getType() == C2->getType() && 1863 assert(C1->getType() == C2->getType() &&
1728 "Operand types in binary constant expression should match"); 1864 "Operand types in binary constant expression should match");
1729 1865
1730 #ifndef NDEBUG 1866 #ifndef NDEBUG
1731 switch (Opcode) { 1867 switch (Opcode) {
1732 case Instruction::Add: 1868 case Instruction::Add:
1733 case Instruction::Sub: 1869 case Instruction::Sub:
1734 case Instruction::Mul: 1870 case Instruction::Mul:
1735 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1871 case Instruction::UDiv:
1872 case Instruction::SDiv:
1873 case Instruction::URem:
1874 case Instruction::SRem:
1736 assert(C1->getType()->isIntOrIntVectorTy() && 1875 assert(C1->getType()->isIntOrIntVectorTy() &&
1737 "Tried to create an integer operation on a non-integer type!"); 1876 "Tried to create an integer operation on a non-integer type!");
1738 break; 1877 break;
1739 case Instruction::FAdd: 1878 case Instruction::FAdd:
1740 case Instruction::FSub: 1879 case Instruction::FSub:
1741 case Instruction::FMul: 1880 case Instruction::FMul:
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1881 case Instruction::FDiv:
1882 case Instruction::FRem:
1743 assert(C1->getType()->isFPOrFPVectorTy() && 1883 assert(C1->getType()->isFPOrFPVectorTy() &&
1744 "Tried to create a floating-point operation on a " 1884 "Tried to create a floating-point operation on a "
1745 "non-floating-point type!"); 1885 "non-floating-point type!");
1746 break; 1886 break;
1747 case Instruction::UDiv:
1748 case Instruction::SDiv:
1749 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1750 assert(C1->getType()->isIntOrIntVectorTy() &&
1751 "Tried to create an arithmetic operation on a non-arithmetic type!");
1752 break;
1753 case Instruction::FDiv:
1754 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1755 assert(C1->getType()->isFPOrFPVectorTy() &&
1756 "Tried to create an arithmetic operation on a non-arithmetic type!");
1757 break;
1758 case Instruction::URem:
1759 case Instruction::SRem:
1760 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1761 assert(C1->getType()->isIntOrIntVectorTy() &&
1762 "Tried to create an arithmetic operation on a non-arithmetic type!");
1763 break;
1764 case Instruction::FRem:
1765 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1766 assert(C1->getType()->isFPOrFPVectorTy() &&
1767 "Tried to create an arithmetic operation on a non-arithmetic type!");
1768 break;
1769 case Instruction::And: 1887 case Instruction::And:
1770 case Instruction::Or: 1888 case Instruction::Or:
1771 case Instruction::Xor: 1889 case Instruction::Xor:
1772 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1773 assert(C1->getType()->isIntOrIntVectorTy() && 1890 assert(C1->getType()->isIntOrIntVectorTy() &&
1774 "Tried to create a logical operation on a non-integral type!"); 1891 "Tried to create a logical operation on a non-integral type!");
1775 break; 1892 break;
1776 case Instruction::Shl: 1893 case Instruction::Shl:
1777 case Instruction::LShr: 1894 case Instruction::LShr:
1778 case Instruction::AShr: 1895 case Instruction::AShr:
1779 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1780 assert(C1->getType()->isIntOrIntVectorTy() && 1896 assert(C1->getType()->isIntOrIntVectorTy() &&
1781 "Tried to create a shift operation on a non-integer type!"); 1897 "Tried to create a shift operation on a non-integer type!");
1782 break; 1898 break;
1783 default: 1899 default:
1784 break; 1900 break;
1785 } 1901 }
1786 #endif 1902 #endif
1787 1903
1788 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2)) 1904 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1789 return FC; // Fold a few common cases. 1905 return FC;
1790 1906
1791 if (OnlyIfReducedTy == C1->getType()) 1907 if (OnlyIfReducedTy == C1->getType())
1792 return nullptr; 1908 return nullptr;
1793 1909
1794 Constant *ArgVec[] = { C1, C2 }; 1910 Constant *ArgVec[] = { C1, C2 };
1802 // sizeof is implemented as: (i64) gep (Ty*)null, 1 1918 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1803 // Note that a non-inbounds gep is used, as null isn't within any object. 1919 // Note that a non-inbounds gep is used, as null isn't within any object.
1804 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 1920 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1805 Constant *GEP = getGetElementPtr( 1921 Constant *GEP = getGetElementPtr(
1806 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 1922 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1807 return getPtrToInt(GEP, 1923 return getPtrToInt(GEP,
1808 Type::getInt64Ty(Ty->getContext())); 1924 Type::getInt64Ty(Ty->getContext()));
1809 } 1925 }
1810 1926
1811 Constant *ConstantExpr::getAlignOf(Type* Ty) { 1927 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1812 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 1928 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1883 Optional<unsigned> InRangeIndex, 1999 Optional<unsigned> InRangeIndex,
1884 Type *OnlyIfReducedTy) { 2000 Type *OnlyIfReducedTy) {
1885 if (!Ty) 2001 if (!Ty)
1886 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType(); 2002 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1887 else 2003 else
1888 assert( 2004 assert(Ty ==
1889 Ty == 2005 cast<PointerType>(C->getType()->getScalarType())->getElementType());
1890 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1891 2006
1892 if (Constant *FC = 2007 if (Constant *FC =
1893 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs)) 2008 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
1894 return FC; // Fold a few common cases. 2009 return FC; // Fold a few common cases.
1895 2010
2111 } 2226 }
2112 2227
2113 Constant *ConstantExpr::getFNeg(Constant *C) { 2228 Constant *ConstantExpr::getFNeg(Constant *C) {
2114 assert(C->getType()->isFPOrFPVectorTy() && 2229 assert(C->getType()->isFPOrFPVectorTy() &&
2115 "Cannot FNEG a non-floating-point value!"); 2230 "Cannot FNEG a non-floating-point value!");
2116 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C); 2231 return get(Instruction::FNeg, C);
2117 } 2232 }
2118 2233
2119 Constant *ConstantExpr::getNot(Constant *C) { 2234 Constant *ConstantExpr::getNot(Constant *C) {
2120 assert(C->getType()->isIntOrIntVectorTy() && 2235 assert(C->getType()->isIntOrIntVectorTy() &&
2121 "Cannot NOT a nonintegral value!"); 2236 "Cannot NOT a nonintegral value!");
2208 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) { 2323 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2209 return get(Instruction::AShr, C1, C2, 2324 return get(Instruction::AShr, C1, C2,
2210 isExact ? PossiblyExactOperator::IsExact : 0); 2325 isExact ? PossiblyExactOperator::IsExact : 0);
2211 } 2326 }
2212 2327
2213 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) { 2328 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2329 bool AllowRHSConstant) {
2330 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2331
2332 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2333 if (Instruction::isCommutative(Opcode)) {
2334 switch (Opcode) {
2335 case Instruction::Add: // X + 0 = X
2336 case Instruction::Or: // X | 0 = X
2337 case Instruction::Xor: // X ^ 0 = X
2338 return Constant::getNullValue(Ty);
2339 case Instruction::Mul: // X * 1 = X
2340 return ConstantInt::get(Ty, 1);
2341 case Instruction::And: // X & -1 = X
2342 return Constant::getAllOnesValue(Ty);
2343 case Instruction::FAdd: // X + -0.0 = X
2344 // TODO: If the fadd has 'nsz', should we return +0.0?
2345 return ConstantFP::getNegativeZero(Ty);
2346 case Instruction::FMul: // X * 1.0 = X
2347 return ConstantFP::get(Ty, 1.0);
2348 default:
2349 llvm_unreachable("Every commutative binop has an identity constant");
2350 }
2351 }
2352
2353 // Non-commutative opcodes: AllowRHSConstant must be set.
2354 if (!AllowRHSConstant)
2355 return nullptr;
2356
2214 switch (Opcode) { 2357 switch (Opcode) {
2215 default: 2358 case Instruction::Sub: // X - 0 = X
2216 // Doesn't have an identity. 2359 case Instruction::Shl: // X << 0 = X
2217 return nullptr; 2360 case Instruction::LShr: // X >>u 0 = X
2218 2361 case Instruction::AShr: // X >> 0 = X
2219 case Instruction::Add: 2362 case Instruction::FSub: // X - 0.0 = X
2220 case Instruction::Or: 2363 return Constant::getNullValue(Ty);
2221 case Instruction::Xor: 2364 case Instruction::SDiv: // X / 1 = X
2222 return Constant::getNullValue(Ty); 2365 case Instruction::UDiv: // X /u 1 = X
2223 2366 return ConstantInt::get(Ty, 1);
2224 case Instruction::Mul: 2367 case Instruction::FDiv: // X / 1.0 = X
2225 return ConstantInt::get(Ty, 1); 2368 return ConstantFP::get(Ty, 1.0);
2226 2369 default:
2227 case Instruction::And: 2370 return nullptr;
2228 return Constant::getAllOnesValue(Ty);
2229 } 2371 }
2230 } 2372 }
2231 2373
2232 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) { 2374 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2233 switch (Opcode) { 2375 switch (Opcode) {
2363 return *Entry = new ConstantDataVector(Ty, Slot.first().data()); 2505 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2364 } 2506 }
2365 2507
2366 void ConstantDataSequential::destroyConstantImpl() { 2508 void ConstantDataSequential::destroyConstantImpl() {
2367 // Remove the constant from the StringMap. 2509 // Remove the constant from the StringMap.
2368 StringMap<ConstantDataSequential*> &CDSConstants = 2510 StringMap<ConstantDataSequential*> &CDSConstants =
2369 getType()->getContext().pImpl->CDSConstants; 2511 getType()->getContext().pImpl->CDSConstants;
2370 2512
2371 StringMap<ConstantDataSequential*>::iterator Slot = 2513 StringMap<ConstantDataSequential*>::iterator Slot =
2372 CDSConstants.find(getRawDataValues()); 2514 CDSConstants.find(getRawDataValues());
2373 2515
2380 // If there is only one value in the bucket (common case) it must be this 2522 // If there is only one value in the bucket (common case) it must be this
2381 // entry, and removing the entry should remove the bucket completely. 2523 // entry, and removing the entry should remove the bucket completely.
2382 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential"); 2524 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2383 getContext().pImpl->CDSConstants.erase(Slot); 2525 getContext().pImpl->CDSConstants.erase(Slot);
2384 } else { 2526 } else {
2385 // Otherwise, there are multiple entries linked off the bucket, unlink the 2527 // Otherwise, there are multiple entries linked off the bucket, unlink the
2386 // node we care about but keep the bucket around. 2528 // node we care about but keep the bucket around.
2387 for (ConstantDataSequential *Node = *Entry; ; 2529 for (ConstantDataSequential *Node = *Entry; ;
2388 Entry = &Node->Next, Node = *Entry) { 2530 Entry = &Node->Next, Node = *Entry) {
2389 assert(Node && "Didn't find entry in its uniquing hash table!"); 2531 assert(Node && "Didn't find entry in its uniquing hash table!");
2390 // If we found our entry, unlink it from the list and we're done. 2532 // If we found our entry, unlink it from the list and we're done.
2398 // If we were part of a list, make sure that we don't delete the list that is 2540 // If we were part of a list, make sure that we don't delete the list that is
2399 // still owned by the uniquing map. 2541 // still owned by the uniquing map.
2400 Next = nullptr; 2542 Next = nullptr;
2401 } 2543 }
2402 2544
2403 /// get() constructors - Return a constant with array type with an element
2404 /// count and element type matching the ArrayRef passed in. Note that this
2405 /// can return a ConstantAggregateZero object.
2406 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2407 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2408 const char *Data = reinterpret_cast<const char *>(Elts.data());
2409 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2410 }
2411 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2412 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2413 const char *Data = reinterpret_cast<const char *>(Elts.data());
2414 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2415 }
2416 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2417 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2418 const char *Data = reinterpret_cast<const char *>(Elts.data());
2419 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2420 }
2421 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2422 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2423 const char *Data = reinterpret_cast<const char *>(Elts.data());
2424 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2425 }
2426 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2427 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2428 const char *Data = reinterpret_cast<const char *>(Elts.data());
2429 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2430 }
2431 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2432 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2433 const char *Data = reinterpret_cast<const char *>(Elts.data());
2434 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2435 }
2436
2437 /// getFP() constructors - Return a constant with array type with an element 2545 /// getFP() constructors - Return a constant with array type with an element
2438 /// count and element type of float with precision matching the number of 2546 /// count and element type of float with precision matching the number of
2439 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits, 2547 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2440 /// double for 64bits) Note that this can return a ConstantAggregateZero 2548 /// double for 64bits) Note that this can return a ConstantAggregateZero
2441 /// object. 2549 /// object.
2459 } 2567 }
2460 2568
2461 Constant *ConstantDataArray::getString(LLVMContext &Context, 2569 Constant *ConstantDataArray::getString(LLVMContext &Context,
2462 StringRef Str, bool AddNull) { 2570 StringRef Str, bool AddNull) {
2463 if (!AddNull) { 2571 if (!AddNull) {
2464 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data()); 2572 const uint8_t *Data = Str.bytes_begin();
2465 return get(Context, makeArrayRef(Data, Str.size())); 2573 return get(Context, makeArrayRef(Data, Str.size()));
2466 } 2574 }
2467 2575
2468 SmallVector<uint8_t, 64> ElementVals; 2576 SmallVector<uint8_t, 64> ElementVals;
2469 ElementVals.append(Str.begin(), Str.end()); 2577 ElementVals.append(Str.begin(), Str.end());
2907 } 3015 }
2908 case Instruction::ICmp: 3016 case Instruction::ICmp:
2909 case Instruction::FCmp: 3017 case Instruction::FCmp:
2910 return CmpInst::Create((Instruction::OtherOps)getOpcode(), 3018 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2911 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]); 3019 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
2912 3020 case Instruction::FNeg:
3021 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]);
2913 default: 3022 default:
2914 assert(getNumOperands() == 2 && "Must be binary operator?"); 3023 assert(getNumOperands() == 2 && "Must be binary operator?");
2915 BinaryOperator *BO = 3024 BinaryOperator *BO =
2916 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(), 3025 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2917 Ops[0], Ops[1]); 3026 Ops[0], Ops[1]);