1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Constant* classes.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/IR/Constants.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/ConstantFold.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalAlias.h"
24 #include "llvm/IR/GlobalIFunc.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34
35 using namespace llvm;
36 using namespace PatternMatch;
37
38 //===----------------------------------------------------------------------===//
39 // Constant Class
40 //===----------------------------------------------------------------------===//
41
isNegativeZeroValue() const42 bool Constant::isNegativeZeroValue() const {
43 // Floating point values have an explicit -0.0 value.
44 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
45 return CFP->isZero() && CFP->isNegative();
46
47 // Equivalent for a vector of -0.0's.
48 if (getType()->isVectorTy())
49 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
50 return SplatCFP->isNegativeZeroValue();
51
52 // We've already handled true FP case; any other FP vectors can't represent -0.0.
53 if (getType()->isFPOrFPVectorTy())
54 return false;
55
56 // Otherwise, just use +0.0.
57 return isNullValue();
58 }
59
60 // Return true iff this constant is positive zero (floating point), negative
61 // zero (floating point), or a null value.
isZeroValue() const62 bool Constant::isZeroValue() const {
63 // Floating point values have an explicit -0.0 value.
64 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
65 return CFP->isZero();
66
67 // Check for constant splat vectors of 1 values.
68 if (getType()->isVectorTy())
69 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
70 return SplatCFP->isZero();
71
72 // Otherwise, just use +0.0.
73 return isNullValue();
74 }
75
isNullValue() const76 bool Constant::isNullValue() const {
77 // 0 is null.
78 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
79 return CI->isZero();
80
81 // +0.0 is null.
82 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
83 // ppc_fp128 determine isZero using high order double only
84 // Should check the bitwise value to make sure all bits are zero.
85 return CFP->isExactlyValue(+0.0);
86
87 // constant zero is zero for aggregates, cpnull is null for pointers, none for
88 // tokens.
89 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
90 isa<ConstantTokenNone>(this);
91 }
92
isAllOnesValue() const93 bool Constant::isAllOnesValue() const {
94 // Check for -1 integers
95 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
96 return CI->isMinusOne();
97
98 // Check for FP which are bitcasted from -1 integers
99 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
100 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
101
102 // Check for constant splat vectors of 1 values.
103 if (getType()->isVectorTy())
104 if (const auto *SplatVal = getSplatValue())
105 return SplatVal->isAllOnesValue();
106
107 return false;
108 }
109
isOneValue() const110 bool Constant::isOneValue() const {
111 // Check for 1 integers
112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
113 return CI->isOne();
114
115 // Check for FP which are bitcasted from 1 integers
116 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
117 return CFP->getValueAPF().bitcastToAPInt().isOne();
118
119 // Check for constant splat vectors of 1 values.
120 if (getType()->isVectorTy())
121 if (const auto *SplatVal = getSplatValue())
122 return SplatVal->isOneValue();
123
124 return false;
125 }
126
isNotOneValue() const127 bool Constant::isNotOneValue() const {
128 // Check for 1 integers
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
130 return !CI->isOneValue();
131
132 // Check for FP which are bitcasted from 1 integers
133 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
134 return !CFP->getValueAPF().bitcastToAPInt().isOne();
135
136 // Check that vectors don't contain 1
137 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
138 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
139 Constant *Elt = getAggregateElement(I);
140 if (!Elt || !Elt->isNotOneValue())
141 return false;
142 }
143 return true;
144 }
145
146 // Check for splats that don't contain 1
147 if (getType()->isVectorTy())
148 if (const auto *SplatVal = getSplatValue())
149 return SplatVal->isNotOneValue();
150
151 // It *may* contain 1, we can't tell.
152 return false;
153 }
154
isMinSignedValue() const155 bool Constant::isMinSignedValue() const {
156 // Check for INT_MIN integers
157 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
158 return CI->isMinValue(/*isSigned=*/true);
159
160 // Check for FP which are bitcasted from INT_MIN integers
161 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
162 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
163
164 // Check for splats of INT_MIN values.
165 if (getType()->isVectorTy())
166 if (const auto *SplatVal = getSplatValue())
167 return SplatVal->isMinSignedValue();
168
169 return false;
170 }
171
isNotMinSignedValue() const172 bool Constant::isNotMinSignedValue() const {
173 // Check for INT_MIN integers
174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
175 return !CI->isMinValue(/*isSigned=*/true);
176
177 // Check for FP which are bitcasted from INT_MIN integers
178 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
179 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
180
181 // Check that vectors don't contain INT_MIN
182 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
183 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
184 Constant *Elt = getAggregateElement(I);
185 if (!Elt || !Elt->isNotMinSignedValue())
186 return false;
187 }
188 return true;
189 }
190
191 // Check for splats that aren't INT_MIN
192 if (getType()->isVectorTy())
193 if (const auto *SplatVal = getSplatValue())
194 return SplatVal->isNotMinSignedValue();
195
196 // It *may* contain INT_MIN, we can't tell.
197 return false;
198 }
199
isFiniteNonZeroFP() const200 bool Constant::isFiniteNonZeroFP() const {
201 if (auto *CFP = dyn_cast<ConstantFP>(this))
202 return CFP->getValueAPF().isFiniteNonZero();
203
204 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
205 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
206 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
207 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
208 return false;
209 }
210 return true;
211 }
212
213 if (getType()->isVectorTy())
214 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
215 return SplatCFP->isFiniteNonZeroFP();
216
217 // It *may* contain finite non-zero, we can't tell.
218 return false;
219 }
220
isNormalFP() const221 bool Constant::isNormalFP() const {
222 if (auto *CFP = dyn_cast<ConstantFP>(this))
223 return CFP->getValueAPF().isNormal();
224
225 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
226 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
227 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
228 if (!CFP || !CFP->getValueAPF().isNormal())
229 return false;
230 }
231 return true;
232 }
233
234 if (getType()->isVectorTy())
235 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
236 return SplatCFP->isNormalFP();
237
238 // It *may* contain a normal fp value, we can't tell.
239 return false;
240 }
241
hasExactInverseFP() const242 bool Constant::hasExactInverseFP() const {
243 if (auto *CFP = dyn_cast<ConstantFP>(this))
244 return CFP->getValueAPF().getExactInverse(nullptr);
245
246 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
247 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
248 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
249 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
250 return false;
251 }
252 return true;
253 }
254
255 if (getType()->isVectorTy())
256 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
257 return SplatCFP->hasExactInverseFP();
258
259 // It *may* have an exact inverse fp value, we can't tell.
260 return false;
261 }
262
isNaN() const263 bool Constant::isNaN() const {
264 if (auto *CFP = dyn_cast<ConstantFP>(this))
265 return CFP->isNaN();
266
267 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
268 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
269 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
270 if (!CFP || !CFP->isNaN())
271 return false;
272 }
273 return true;
274 }
275
276 if (getType()->isVectorTy())
277 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
278 return SplatCFP->isNaN();
279
280 // It *may* be NaN, we can't tell.
281 return false;
282 }
283
isElementWiseEqual(Value * Y) const284 bool Constant::isElementWiseEqual(Value *Y) const {
285 // Are they fully identical?
286 if (this == Y)
287 return true;
288
289 // The input value must be a vector constant with the same type.
290 auto *VTy = dyn_cast<VectorType>(getType());
291 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
292 return false;
293
294 // TODO: Compare pointer constants?
295 if (!(VTy->getElementType()->isIntegerTy() ||
296 VTy->getElementType()->isFloatingPointTy()))
297 return false;
298
299 // They may still be identical element-wise (if they have `undef`s).
300 // Bitcast to integer to allow exact bitwise comparison for all types.
301 Type *IntTy = VectorType::getInteger(VTy);
302 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
303 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
304 Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1);
305 return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
306 }
307
308 static bool
containsUndefinedElement(const Constant * C,function_ref<bool (const Constant *)> HasFn)309 containsUndefinedElement(const Constant *C,
310 function_ref<bool(const Constant *)> HasFn) {
311 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
312 if (HasFn(C))
313 return true;
314 if (isa<ConstantAggregateZero>(C))
315 return false;
316 if (isa<ScalableVectorType>(C->getType()))
317 return false;
318
319 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
320 i != e; ++i) {
321 if (Constant *Elem = C->getAggregateElement(i))
322 if (HasFn(Elem))
323 return true;
324 }
325 }
326
327 return false;
328 }
329
containsUndefOrPoisonElement() const330 bool Constant::containsUndefOrPoisonElement() const {
331 return containsUndefinedElement(
332 this, [&](const auto *C) { return isa<UndefValue>(C); });
333 }
334
containsPoisonElement() const335 bool Constant::containsPoisonElement() const {
336 return containsUndefinedElement(
337 this, [&](const auto *C) { return isa<PoisonValue>(C); });
338 }
339
containsConstantExpression() const340 bool Constant::containsConstantExpression() const {
341 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
342 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
343 if (isa<ConstantExpr>(getAggregateElement(i)))
344 return true;
345 }
346 return false;
347 }
348
349 /// Constructor to create a '0' constant of arbitrary type.
getNullValue(Type * Ty)350 Constant *Constant::getNullValue(Type *Ty) {
351 switch (Ty->getTypeID()) {
352 case Type::IntegerTyID:
353 return ConstantInt::get(Ty, 0);
354 case Type::HalfTyID:
355 case Type::BFloatTyID:
356 case Type::FloatTyID:
357 case Type::DoubleTyID:
358 case Type::X86_FP80TyID:
359 case Type::FP128TyID:
360 case Type::PPC_FP128TyID:
361 return ConstantFP::get(Ty->getContext(),
362 APFloat::getZero(Ty->getFltSemantics()));
363 case Type::PointerTyID:
364 return ConstantPointerNull::get(cast<PointerType>(Ty));
365 case Type::StructTyID:
366 case Type::ArrayTyID:
367 case Type::FixedVectorTyID:
368 case Type::ScalableVectorTyID:
369 return ConstantAggregateZero::get(Ty);
370 case Type::TokenTyID:
371 return ConstantTokenNone::get(Ty->getContext());
372 default:
373 // Function, Label, or Opaque type?
374 llvm_unreachable("Cannot create a null constant of that type!");
375 }
376 }
377
getIntegerValue(Type * Ty,const APInt & V)378 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
379 Type *ScalarTy = Ty->getScalarType();
380
381 // Create the base integer constant.
382 Constant *C = ConstantInt::get(Ty->getContext(), V);
383
384 // Convert an integer to a pointer, if necessary.
385 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
386 C = ConstantExpr::getIntToPtr(C, PTy);
387
388 // Broadcast a scalar to a vector, if necessary.
389 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
390 C = ConstantVector::getSplat(VTy->getElementCount(), C);
391
392 return C;
393 }
394
getAllOnesValue(Type * Ty)395 Constant *Constant::getAllOnesValue(Type *Ty) {
396 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
397 return ConstantInt::get(Ty->getContext(),
398 APInt::getAllOnes(ITy->getBitWidth()));
399
400 if (Ty->isFloatingPointTy()) {
401 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
402 return ConstantFP::get(Ty->getContext(), FL);
403 }
404
405 VectorType *VTy = cast<VectorType>(Ty);
406 return ConstantVector::getSplat(VTy->getElementCount(),
407 getAllOnesValue(VTy->getElementType()));
408 }
409
getAggregateElement(unsigned Elt) const410 Constant *Constant::getAggregateElement(unsigned Elt) const {
411 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
412 "Must be an aggregate/vector constant");
413
414 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
415 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
416
417 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
418 return Elt < CAZ->getElementCount().getKnownMinValue()
419 ? CAZ->getElementValue(Elt)
420 : nullptr;
421
422 // FIXME: getNumElements() will fail for non-fixed vector types.
423 if (isa<ScalableVectorType>(getType()))
424 return nullptr;
425
426 if (const auto *PV = dyn_cast<PoisonValue>(this))
427 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
428
429 if (const auto *UV = dyn_cast<UndefValue>(this))
430 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
431
432 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
433 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
434 : nullptr;
435
436 return nullptr;
437 }
438
getAggregateElement(Constant * Elt) const439 Constant *Constant::getAggregateElement(Constant *Elt) const {
440 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
441 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
442 // Check if the constant fits into an uint64_t.
443 if (CI->getValue().getActiveBits() > 64)
444 return nullptr;
445 return getAggregateElement(CI->getZExtValue());
446 }
447 return nullptr;
448 }
449
destroyConstant()450 void Constant::destroyConstant() {
451 /// First call destroyConstantImpl on the subclass. This gives the subclass
452 /// a chance to remove the constant from any maps/pools it's contained in.
453 switch (getValueID()) {
454 default:
455 llvm_unreachable("Not a constant!");
456 #define HANDLE_CONSTANT(Name) \
457 case Value::Name##Val: \
458 cast<Name>(this)->destroyConstantImpl(); \
459 break;
460 #include "llvm/IR/Value.def"
461 }
462
463 // When a Constant is destroyed, there may be lingering
464 // references to the constant by other constants in the constant pool. These
465 // constants are implicitly dependent on the module that is being deleted,
466 // but they don't know that. Because we only find out when the CPV is
467 // deleted, we must now notify all of our users (that should only be
468 // Constants) that they are, in fact, invalid now and should be deleted.
469 //
470 while (!use_empty()) {
471 Value *V = user_back();
472 #ifndef NDEBUG // Only in -g mode...
473 if (!isa<Constant>(V)) {
474 dbgs() << "While deleting: " << *this
475 << "\n\nUse still stuck around after Def is destroyed: " << *V
476 << "\n\n";
477 }
478 #endif
479 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
480 cast<Constant>(V)->destroyConstant();
481
482 // The constant should remove itself from our use list...
483 assert((use_empty() || user_back() != V) && "Constant not removed!");
484 }
485
486 // Value has no outstanding references it is safe to delete it now...
487 deleteConstant(this);
488 }
489
deleteConstant(Constant * C)490 void llvm::deleteConstant(Constant *C) {
491 switch (C->getValueID()) {
492 case Constant::ConstantIntVal:
493 delete static_cast<ConstantInt *>(C);
494 break;
495 case Constant::ConstantFPVal:
496 delete static_cast<ConstantFP *>(C);
497 break;
498 case Constant::ConstantAggregateZeroVal:
499 delete static_cast<ConstantAggregateZero *>(C);
500 break;
501 case Constant::ConstantArrayVal:
502 delete static_cast<ConstantArray *>(C);
503 break;
504 case Constant::ConstantStructVal:
505 delete static_cast<ConstantStruct *>(C);
506 break;
507 case Constant::ConstantVectorVal:
508 delete static_cast<ConstantVector *>(C);
509 break;
510 case Constant::ConstantPointerNullVal:
511 delete static_cast<ConstantPointerNull *>(C);
512 break;
513 case Constant::ConstantDataArrayVal:
514 delete static_cast<ConstantDataArray *>(C);
515 break;
516 case Constant::ConstantDataVectorVal:
517 delete static_cast<ConstantDataVector *>(C);
518 break;
519 case Constant::ConstantTokenNoneVal:
520 delete static_cast<ConstantTokenNone *>(C);
521 break;
522 case Constant::BlockAddressVal:
523 delete static_cast<BlockAddress *>(C);
524 break;
525 case Constant::DSOLocalEquivalentVal:
526 delete static_cast<DSOLocalEquivalent *>(C);
527 break;
528 case Constant::NoCFIValueVal:
529 delete static_cast<NoCFIValue *>(C);
530 break;
531 case Constant::UndefValueVal:
532 delete static_cast<UndefValue *>(C);
533 break;
534 case Constant::PoisonValueVal:
535 delete static_cast<PoisonValue *>(C);
536 break;
537 case Constant::ConstantExprVal:
538 if (isa<UnaryConstantExpr>(C))
539 delete static_cast<UnaryConstantExpr *>(C);
540 else if (isa<BinaryConstantExpr>(C))
541 delete static_cast<BinaryConstantExpr *>(C);
542 else if (isa<SelectConstantExpr>(C))
543 delete static_cast<SelectConstantExpr *>(C);
544 else if (isa<ExtractElementConstantExpr>(C))
545 delete static_cast<ExtractElementConstantExpr *>(C);
546 else if (isa<InsertElementConstantExpr>(C))
547 delete static_cast<InsertElementConstantExpr *>(C);
548 else if (isa<ShuffleVectorConstantExpr>(C))
549 delete static_cast<ShuffleVectorConstantExpr *>(C);
550 else if (isa<GetElementPtrConstantExpr>(C))
551 delete static_cast<GetElementPtrConstantExpr *>(C);
552 else if (isa<CompareConstantExpr>(C))
553 delete static_cast<CompareConstantExpr *>(C);
554 else
555 llvm_unreachable("Unexpected constant expr");
556 break;
557 default:
558 llvm_unreachable("Unexpected constant");
559 }
560 }
561
562 /// Check if C contains a GlobalValue for which Predicate is true.
563 static bool
ConstHasGlobalValuePredicate(const Constant * C,bool (* Predicate)(const GlobalValue *))564 ConstHasGlobalValuePredicate(const Constant *C,
565 bool (*Predicate)(const GlobalValue *)) {
566 SmallPtrSet<const Constant *, 8> Visited;
567 SmallVector<const Constant *, 8> WorkList;
568 WorkList.push_back(C);
569 Visited.insert(C);
570
571 while (!WorkList.empty()) {
572 const Constant *WorkItem = WorkList.pop_back_val();
573 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
574 if (Predicate(GV))
575 return true;
576 for (const Value *Op : WorkItem->operands()) {
577 const Constant *ConstOp = dyn_cast<Constant>(Op);
578 if (!ConstOp)
579 continue;
580 if (Visited.insert(ConstOp).second)
581 WorkList.push_back(ConstOp);
582 }
583 }
584 return false;
585 }
586
isThreadDependent() const587 bool Constant::isThreadDependent() const {
588 auto DLLImportPredicate = [](const GlobalValue *GV) {
589 return GV->isThreadLocal();
590 };
591 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
592 }
593
isDLLImportDependent() const594 bool Constant::isDLLImportDependent() const {
595 auto DLLImportPredicate = [](const GlobalValue *GV) {
596 return GV->hasDLLImportStorageClass();
597 };
598 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
599 }
600
isConstantUsed() const601 bool Constant::isConstantUsed() const {
602 for (const User *U : users()) {
603 const Constant *UC = dyn_cast<Constant>(U);
604 if (!UC || isa<GlobalValue>(UC))
605 return true;
606
607 if (UC->isConstantUsed())
608 return true;
609 }
610 return false;
611 }
612
needsDynamicRelocation() const613 bool Constant::needsDynamicRelocation() const {
614 return getRelocationInfo() == GlobalRelocation;
615 }
616
needsRelocation() const617 bool Constant::needsRelocation() const {
618 return getRelocationInfo() != NoRelocation;
619 }
620
getRelocationInfo() const621 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
622 if (isa<GlobalValue>(this))
623 return GlobalRelocation; // Global reference.
624
625 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
626 return BA->getFunction()->getRelocationInfo();
627
628 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
629 if (CE->getOpcode() == Instruction::Sub) {
630 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
631 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
632 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
633 RHS->getOpcode() == Instruction::PtrToInt) {
634 Constant *LHSOp0 = LHS->getOperand(0);
635 Constant *RHSOp0 = RHS->getOperand(0);
636
637 // While raw uses of blockaddress need to be relocated, differences
638 // between two of them don't when they are for labels in the same
639 // function. This is a common idiom when creating a table for the
640 // indirect goto extension, so we handle it efficiently here.
641 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
642 cast<BlockAddress>(LHSOp0)->getFunction() ==
643 cast<BlockAddress>(RHSOp0)->getFunction())
644 return NoRelocation;
645
646 // Relative pointers do not need to be dynamically relocated.
647 if (auto *RHSGV =
648 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
649 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
650 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
651 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
652 return LocalRelocation;
653 } else if (isa<DSOLocalEquivalent>(LHS)) {
654 if (RHSGV->isDSOLocal())
655 return LocalRelocation;
656 }
657 }
658 }
659 }
660 }
661
662 PossibleRelocationsTy Result = NoRelocation;
663 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
664 Result =
665 std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);
666
667 return Result;
668 }
669
670 /// Return true if the specified constantexpr is dead. This involves
671 /// recursively traversing users of the constantexpr.
672 /// If RemoveDeadUsers is true, also remove dead users at the same time.
constantIsDead(const Constant * C,bool RemoveDeadUsers)673 static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
674 if (isa<GlobalValue>(C)) return false; // Cannot remove this
675
676 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
677 while (I != E) {
678 const Constant *User = dyn_cast<Constant>(*I);
679 if (!User) return false; // Non-constant usage;
680 if (!constantIsDead(User, RemoveDeadUsers))
681 return false; // Constant wasn't dead
682
683 // Just removed User, so the iterator was invalidated.
684 // Since we return immediately upon finding a live user, we can always
685 // restart from user_begin().
686 if (RemoveDeadUsers)
687 I = C->user_begin();
688 else
689 ++I;
690 }
691
692 if (RemoveDeadUsers) {
693 // If C is only used by metadata, it should not be preserved but should
694 // have its uses replaced.
695 ReplaceableMetadataImpl::SalvageDebugInfo(*C);
696 const_cast<Constant *>(C)->destroyConstant();
697 }
698
699 return true;
700 }
701
removeDeadConstantUsers() const702 void Constant::removeDeadConstantUsers() const {
703 Value::const_user_iterator I = user_begin(), E = user_end();
704 Value::const_user_iterator LastNonDeadUser = E;
705 while (I != E) {
706 const Constant *User = dyn_cast<Constant>(*I);
707 if (!User) {
708 LastNonDeadUser = I;
709 ++I;
710 continue;
711 }
712
713 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
714 // If the constant wasn't dead, remember that this was the last live use
715 // and move on to the next constant.
716 LastNonDeadUser = I;
717 ++I;
718 continue;
719 }
720
721 // If the constant was dead, then the iterator is invalidated.
722 if (LastNonDeadUser == E)
723 I = user_begin();
724 else
725 I = std::next(LastNonDeadUser);
726 }
727 }
728
hasOneLiveUse() const729 bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
730
hasZeroLiveUses() const731 bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
732
hasNLiveUses(unsigned N) const733 bool Constant::hasNLiveUses(unsigned N) const {
734 unsigned NumUses = 0;
735 for (const Use &U : uses()) {
736 const Constant *User = dyn_cast<Constant>(U.getUser());
737 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
738 ++NumUses;
739
740 if (NumUses > N)
741 return false;
742 }
743 }
744 return NumUses == N;
745 }
746
replaceUndefsWith(Constant * C,Constant * Replacement)747 Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
748 assert(C && Replacement && "Expected non-nullptr constant arguments");
749 Type *Ty = C->getType();
750 if (match(C, m_Undef())) {
751 assert(Ty == Replacement->getType() && "Expected matching types");
752 return Replacement;
753 }
754
755 // Don't know how to deal with this constant.
756 auto *VTy = dyn_cast<FixedVectorType>(Ty);
757 if (!VTy)
758 return C;
759
760 unsigned NumElts = VTy->getNumElements();
761 SmallVector<Constant *, 32> NewC(NumElts);
762 for (unsigned i = 0; i != NumElts; ++i) {
763 Constant *EltC = C->getAggregateElement(i);
764 assert((!EltC || EltC->getType() == Replacement->getType()) &&
765 "Expected matching types");
766 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
767 }
768 return ConstantVector::get(NewC);
769 }
770
mergeUndefsWith(Constant * C,Constant * Other)771 Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {
772 assert(C && Other && "Expected non-nullptr constant arguments");
773 if (match(C, m_Undef()))
774 return C;
775
776 Type *Ty = C->getType();
777 if (match(Other, m_Undef()))
778 return UndefValue::get(Ty);
779
780 auto *VTy = dyn_cast<FixedVectorType>(Ty);
781 if (!VTy)
782 return C;
783
784 Type *EltTy = VTy->getElementType();
785 unsigned NumElts = VTy->getNumElements();
786 assert(isa<FixedVectorType>(Other->getType()) &&
787 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
788 "Type mismatch");
789
790 bool FoundExtraUndef = false;
791 SmallVector<Constant *, 32> NewC(NumElts);
792 for (unsigned I = 0; I != NumElts; ++I) {
793 NewC[I] = C->getAggregateElement(I);
794 Constant *OtherEltC = Other->getAggregateElement(I);
795 assert(NewC[I] && OtherEltC && "Unknown vector element");
796 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
797 NewC[I] = UndefValue::get(EltTy);
798 FoundExtraUndef = true;
799 }
800 }
801 if (FoundExtraUndef)
802 return ConstantVector::get(NewC);
803 return C;
804 }
805
isManifestConstant() const806 bool Constant::isManifestConstant() const {
807 if (isa<ConstantData>(this))
808 return true;
809 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
810 for (const Value *Op : operand_values())
811 if (!cast<Constant>(Op)->isManifestConstant())
812 return false;
813 return true;
814 }
815 return false;
816 }
817
818 //===----------------------------------------------------------------------===//
819 // ConstantInt
820 //===----------------------------------------------------------------------===//
821
ConstantInt(IntegerType * Ty,const APInt & V)822 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
823 : ConstantData(Ty, ConstantIntVal), Val(V) {
824 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
825 }
826
getTrue(LLVMContext & Context)827 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
828 LLVMContextImpl *pImpl = Context.pImpl;
829 if (!pImpl->TheTrueVal)
830 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
831 return pImpl->TheTrueVal;
832 }
833
getFalse(LLVMContext & Context)834 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
835 LLVMContextImpl *pImpl = Context.pImpl;
836 if (!pImpl->TheFalseVal)
837 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
838 return pImpl->TheFalseVal;
839 }
840
getBool(LLVMContext & Context,bool V)841 ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
842 return V ? getTrue(Context) : getFalse(Context);
843 }
844
getTrue(Type * Ty)845 Constant *ConstantInt::getTrue(Type *Ty) {
846 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
847 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
848 if (auto *VTy = dyn_cast<VectorType>(Ty))
849 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
850 return TrueC;
851 }
852
getFalse(Type * Ty)853 Constant *ConstantInt::getFalse(Type *Ty) {
854 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
855 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
856 if (auto *VTy = dyn_cast<VectorType>(Ty))
857 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
858 return FalseC;
859 }
860
getBool(Type * Ty,bool V)861 Constant *ConstantInt::getBool(Type *Ty, bool V) {
862 return V ? getTrue(Ty) : getFalse(Ty);
863 }
864
865 // Get a ConstantInt from an APInt.
get(LLVMContext & Context,const APInt & V)866 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
867 // get an existing value or the insertion position
868 LLVMContextImpl *pImpl = Context.pImpl;
869 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
870 if (!Slot) {
871 // Get the corresponding integer type for the bit width of the value.
872 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
873 Slot.reset(new ConstantInt(ITy, V));
874 }
875 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
876 return Slot.get();
877 }
878
get(Type * Ty,uint64_t V,bool isSigned)879 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
880 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
881
882 // For vectors, broadcast the value.
883 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
884 return ConstantVector::getSplat(VTy->getElementCount(), C);
885
886 return C;
887 }
888
get(IntegerType * Ty,uint64_t V,bool isSigned)889 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
890 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
891 }
892
getSigned(IntegerType * Ty,int64_t V)893 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
894 return get(Ty, V, true);
895 }
896
getSigned(Type * Ty,int64_t V)897 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
898 return get(Ty, V, true);
899 }
900
get(Type * Ty,const APInt & V)901 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
902 ConstantInt *C = get(Ty->getContext(), V);
903 assert(C->getType() == Ty->getScalarType() &&
904 "ConstantInt type doesn't match the type implied by its value!");
905
906 // For vectors, broadcast the value.
907 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
908 return ConstantVector::getSplat(VTy->getElementCount(), C);
909
910 return C;
911 }
912
get(IntegerType * Ty,StringRef Str,uint8_t radix)913 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
914 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
915 }
916
917 /// Remove the constant from the constant table.
destroyConstantImpl()918 void ConstantInt::destroyConstantImpl() {
919 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
920 }
921
922 //===----------------------------------------------------------------------===//
923 // ConstantFP
924 //===----------------------------------------------------------------------===//
925
get(Type * Ty,double V)926 Constant *ConstantFP::get(Type *Ty, double V) {
927 LLVMContext &Context = Ty->getContext();
928
929 APFloat FV(V);
930 bool ignored;
931 FV.convert(Ty->getScalarType()->getFltSemantics(),
932 APFloat::rmNearestTiesToEven, &ignored);
933 Constant *C = get(Context, FV);
934
935 // For vectors, broadcast the value.
936 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
937 return ConstantVector::getSplat(VTy->getElementCount(), C);
938
939 return C;
940 }
941
get(Type * Ty,const APFloat & V)942 Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
943 ConstantFP *C = get(Ty->getContext(), V);
944 assert(C->getType() == Ty->getScalarType() &&
945 "ConstantFP type doesn't match the type implied by its value!");
946
947 // For vectors, broadcast the value.
948 if (auto *VTy = dyn_cast<VectorType>(Ty))
949 return ConstantVector::getSplat(VTy->getElementCount(), C);
950
951 return C;
952 }
953
get(Type * Ty,StringRef Str)954 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
955 LLVMContext &Context = Ty->getContext();
956
957 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
958 Constant *C = get(Context, FV);
959
960 // For vectors, broadcast the value.
961 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
962 return ConstantVector::getSplat(VTy->getElementCount(), C);
963
964 return C;
965 }
966
getNaN(Type * Ty,bool Negative,uint64_t Payload)967 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
968 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
969 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
970 Constant *C = get(Ty->getContext(), NaN);
971
972 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
973 return ConstantVector::getSplat(VTy->getElementCount(), C);
974
975 return C;
976 }
977
getQNaN(Type * Ty,bool Negative,APInt * Payload)978 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
979 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
980 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
981 Constant *C = get(Ty->getContext(), NaN);
982
983 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
984 return ConstantVector::getSplat(VTy->getElementCount(), C);
985
986 return C;
987 }
988
getSNaN(Type * Ty,bool Negative,APInt * Payload)989 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
990 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
991 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
992 Constant *C = get(Ty->getContext(), NaN);
993
994 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
995 return ConstantVector::getSplat(VTy->getElementCount(), C);
996
997 return C;
998 }
999
getZero(Type * Ty,bool Negative)1000 Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1001 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1002 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1003 Constant *C = get(Ty->getContext(), NegZero);
1004
1005 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1006 return ConstantVector::getSplat(VTy->getElementCount(), C);
1007
1008 return C;
1009 }
1010
getZeroValueForNegation(Type * Ty)1011 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
1012 if (Ty->isFPOrFPVectorTy())
1013 return getNegativeZero(Ty);
1014
1015 return Constant::getNullValue(Ty);
1016 }
1017
1018
1019 // ConstantFP accessors.
get(LLVMContext & Context,const APFloat & V)1020 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1021 LLVMContextImpl* pImpl = Context.pImpl;
1022
1023 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1024
1025 if (!Slot) {
1026 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1027 Slot.reset(new ConstantFP(Ty, V));
1028 }
1029
1030 return Slot.get();
1031 }
1032
getInfinity(Type * Ty,bool Negative)1033 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1034 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1035 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1036
1037 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1038 return ConstantVector::getSplat(VTy->getElementCount(), C);
1039
1040 return C;
1041 }
1042
ConstantFP(Type * Ty,const APFloat & V)1043 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1044 : ConstantData(Ty, ConstantFPVal), Val(V) {
1045 assert(&V.getSemantics() == &Ty->getFltSemantics() &&
1046 "FP type Mismatch");
1047 }
1048
isExactlyValue(const APFloat & V) const1049 bool ConstantFP::isExactlyValue(const APFloat &V) const {
1050 return Val.bitwiseIsEqual(V);
1051 }
1052
1053 /// Remove the constant from the constant table.
destroyConstantImpl()1054 void ConstantFP::destroyConstantImpl() {
1055 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1056 }
1057
1058 //===----------------------------------------------------------------------===//
1059 // ConstantAggregateZero Implementation
1060 //===----------------------------------------------------------------------===//
1061
getSequentialElement() const1062 Constant *ConstantAggregateZero::getSequentialElement() const {
1063 if (auto *AT = dyn_cast<ArrayType>(getType()))
1064 return Constant::getNullValue(AT->getElementType());
1065 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1066 }
1067
getStructElement(unsigned Elt) const1068 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
1069 return Constant::getNullValue(getType()->getStructElementType(Elt));
1070 }
1071
getElementValue(Constant * C) const1072 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1073 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1074 return getSequentialElement();
1075 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1076 }
1077
getElementValue(unsigned Idx) const1078 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1079 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1080 return getSequentialElement();
1081 return getStructElement(Idx);
1082 }
1083
getElementCount() const1084 ElementCount ConstantAggregateZero::getElementCount() const {
1085 Type *Ty = getType();
1086 if (auto *AT = dyn_cast<ArrayType>(Ty))
1087 return ElementCount::getFixed(AT->getNumElements());
1088 if (auto *VT = dyn_cast<VectorType>(Ty))
1089 return VT->getElementCount();
1090 return ElementCount::getFixed(Ty->getStructNumElements());
1091 }
1092
1093 //===----------------------------------------------------------------------===//
1094 // UndefValue Implementation
1095 //===----------------------------------------------------------------------===//
1096
getSequentialElement() const1097 UndefValue *UndefValue::getSequentialElement() const {
1098 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1099 return UndefValue::get(ATy->getElementType());
1100 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1101 }
1102
getStructElement(unsigned Elt) const1103 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1104 return UndefValue::get(getType()->getStructElementType(Elt));
1105 }
1106
getElementValue(Constant * C) const1107 UndefValue *UndefValue::getElementValue(Constant *C) const {
1108 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1109 return getSequentialElement();
1110 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1111 }
1112
getElementValue(unsigned Idx) const1113 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1114 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1115 return getSequentialElement();
1116 return getStructElement(Idx);
1117 }
1118
getNumElements() const1119 unsigned UndefValue::getNumElements() const {
1120 Type *Ty = getType();
1121 if (auto *AT = dyn_cast<ArrayType>(Ty))
1122 return AT->getNumElements();
1123 if (auto *VT = dyn_cast<VectorType>(Ty))
1124 return cast<FixedVectorType>(VT)->getNumElements();
1125 return Ty->getStructNumElements();
1126 }
1127
1128 //===----------------------------------------------------------------------===//
1129 // PoisonValue Implementation
1130 //===----------------------------------------------------------------------===//
1131
getSequentialElement() const1132 PoisonValue *PoisonValue::getSequentialElement() const {
1133 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1134 return PoisonValue::get(ATy->getElementType());
1135 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1136 }
1137
getStructElement(unsigned Elt) const1138 PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1139 return PoisonValue::get(getType()->getStructElementType(Elt));
1140 }
1141
getElementValue(Constant * C) const1142 PoisonValue *PoisonValue::getElementValue(Constant *C) const {
1143 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1144 return getSequentialElement();
1145 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1146 }
1147
getElementValue(unsigned Idx) const1148 PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1149 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1150 return getSequentialElement();
1151 return getStructElement(Idx);
1152 }
1153
1154 //===----------------------------------------------------------------------===//
1155 // ConstantXXX Classes
1156 //===----------------------------------------------------------------------===//
1157
1158 template <typename ItTy, typename EltTy>
rangeOnlyContains(ItTy Start,ItTy End,EltTy Elt)1159 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1160 for (; Start != End; ++Start)
1161 if (*Start != Elt)
1162 return false;
1163 return true;
1164 }
1165
1166 template <typename SequentialTy, typename ElementTy>
getIntSequenceIfElementsMatch(ArrayRef<Constant * > V)1167 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1168 assert(!V.empty() && "Cannot get empty int sequence.");
1169
1170 SmallVector<ElementTy, 16> Elts;
1171 for (Constant *C : V)
1172 if (auto *CI = dyn_cast<ConstantInt>(C))
1173 Elts.push_back(CI->getZExtValue());
1174 else
1175 return nullptr;
1176 return SequentialTy::get(V[0]->getContext(), Elts);
1177 }
1178
1179 template <typename SequentialTy, typename ElementTy>
getFPSequenceIfElementsMatch(ArrayRef<Constant * > V)1180 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1181 assert(!V.empty() && "Cannot get empty FP sequence.");
1182
1183 SmallVector<ElementTy, 16> Elts;
1184 for (Constant *C : V)
1185 if (auto *CFP = dyn_cast<ConstantFP>(C))
1186 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1187 else
1188 return nullptr;
1189 return SequentialTy::getFP(V[0]->getType(), Elts);
1190 }
1191
1192 template <typename SequenceTy>
getSequenceIfElementsMatch(Constant * C,ArrayRef<Constant * > V)1193 static Constant *getSequenceIfElementsMatch(Constant *C,
1194 ArrayRef<Constant *> V) {
1195 // We speculatively build the elements here even if it turns out that there is
1196 // a constantexpr or something else weird, since it is so uncommon for that to
1197 // happen.
1198 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1199 if (CI->getType()->isIntegerTy(8))
1200 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1201 else if (CI->getType()->isIntegerTy(16))
1202 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1203 else if (CI->getType()->isIntegerTy(32))
1204 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1205 else if (CI->getType()->isIntegerTy(64))
1206 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1207 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1208 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1209 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1210 else if (CFP->getType()->isFloatTy())
1211 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1212 else if (CFP->getType()->isDoubleTy())
1213 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1214 }
1215
1216 return nullptr;
1217 }
1218
ConstantAggregate(Type * T,ValueTy VT,ArrayRef<Constant * > V)1219 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
1220 ArrayRef<Constant *> V)
1221 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
1222 V.size()) {
1223 llvm::copy(V, op_begin());
1224
1225 // Check that types match, unless this is an opaque struct.
1226 if (auto *ST = dyn_cast<StructType>(T)) {
1227 if (ST->isOpaque())
1228 return;
1229 for (unsigned I = 0, E = V.size(); I != E; ++I)
1230 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1231 "Initializer for struct element doesn't match!");
1232 }
1233 }
1234
ConstantArray(ArrayType * T,ArrayRef<Constant * > V)1235 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
1236 : ConstantAggregate(T, ConstantArrayVal, V) {
1237 assert(V.size() == T->getNumElements() &&
1238 "Invalid initializer for constant array");
1239 }
1240
get(ArrayType * Ty,ArrayRef<Constant * > V)1241 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1242 if (Constant *C = getImpl(Ty, V))
1243 return C;
1244 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1245 }
1246
getImpl(ArrayType * Ty,ArrayRef<Constant * > V)1247 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1248 // Empty arrays are canonicalized to ConstantAggregateZero.
1249 if (V.empty())
1250 return ConstantAggregateZero::get(Ty);
1251
1252 for (Constant *C : V) {
1253 assert(C->getType() == Ty->getElementType() &&
1254 "Wrong type in array element initializer");
1255 (void)C;
1256 }
1257
1258 // If this is an all-zero array, return a ConstantAggregateZero object. If
1259 // all undef, return an UndefValue, if "all simple", then return a
1260 // ConstantDataArray.
1261 Constant *C = V[0];
1262 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1263 return PoisonValue::get(Ty);
1264
1265 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1266 return UndefValue::get(Ty);
1267
1268 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1269 return ConstantAggregateZero::get(Ty);
1270
1271 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1272 // the element type is compatible with ConstantDataVector. If so, use it.
1273 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1274 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1275
1276 // Otherwise, we really do want to create a ConstantArray.
1277 return nullptr;
1278 }
1279
getTypeForElements(LLVMContext & Context,ArrayRef<Constant * > V,bool Packed)1280 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1281 ArrayRef<Constant*> V,
1282 bool Packed) {
1283 unsigned VecSize = V.size();
1284 SmallVector<Type*, 16> EltTypes(VecSize);
1285 for (unsigned i = 0; i != VecSize; ++i)
1286 EltTypes[i] = V[i]->getType();
1287
1288 return StructType::get(Context, EltTypes, Packed);
1289 }
1290
1291
getTypeForElements(ArrayRef<Constant * > V,bool Packed)1292 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1293 bool Packed) {
1294 assert(!V.empty() &&
1295 "ConstantStruct::getTypeForElements cannot be called on empty list");
1296 return getTypeForElements(V[0]->getContext(), V, Packed);
1297 }
1298
ConstantStruct(StructType * T,ArrayRef<Constant * > V)1299 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1300 : ConstantAggregate(T, ConstantStructVal, V) {
1301 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1302 "Invalid initializer for constant struct");
1303 }
1304
1305 // ConstantStruct accessors.
get(StructType * ST,ArrayRef<Constant * > V)1306 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1307 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1308 "Incorrect # elements specified to ConstantStruct::get");
1309
1310 // Create a ConstantAggregateZero value if all elements are zeros.
1311 bool isZero = true;
1312 bool isUndef = false;
1313 bool isPoison = false;
1314
1315 if (!V.empty()) {
1316 isUndef = isa<UndefValue>(V[0]);
1317 isPoison = isa<PoisonValue>(V[0]);
1318 isZero = V[0]->isNullValue();
1319 // PoisonValue inherits UndefValue, so its check is not necessary.
1320 if (isUndef || isZero) {
1321 for (Constant *C : V) {
1322 if (!C->isNullValue())
1323 isZero = false;
1324 if (!isa<PoisonValue>(C))
1325 isPoison = false;
1326 if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
1327 isUndef = false;
1328 }
1329 }
1330 }
1331 if (isZero)
1332 return ConstantAggregateZero::get(ST);
1333 if (isPoison)
1334 return PoisonValue::get(ST);
1335 if (isUndef)
1336 return UndefValue::get(ST);
1337
1338 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1339 }
1340
ConstantVector(VectorType * T,ArrayRef<Constant * > V)1341 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1342 : ConstantAggregate(T, ConstantVectorVal, V) {
1343 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1344 "Invalid initializer for constant vector");
1345 }
1346
1347 // ConstantVector accessors.
get(ArrayRef<Constant * > V)1348 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1349 if (Constant *C = getImpl(V))
1350 return C;
1351 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1352 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1353 }
1354
getImpl(ArrayRef<Constant * > V)1355 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1356 assert(!V.empty() && "Vectors can't be empty");
1357 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1358
1359 // If this is an all-undef or all-zero vector, return a
1360 // ConstantAggregateZero or UndefValue.
1361 Constant *C = V[0];
1362 bool isZero = C->isNullValue();
1363 bool isUndef = isa<UndefValue>(C);
1364 bool isPoison = isa<PoisonValue>(C);
1365
1366 if (isZero || isUndef) {
1367 for (unsigned i = 1, e = V.size(); i != e; ++i)
1368 if (V[i] != C) {
1369 isZero = isUndef = isPoison = false;
1370 break;
1371 }
1372 }
1373
1374 if (isZero)
1375 return ConstantAggregateZero::get(T);
1376 if (isPoison)
1377 return PoisonValue::get(T);
1378 if (isUndef)
1379 return UndefValue::get(T);
1380
1381 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1382 // the element type is compatible with ConstantDataVector. If so, use it.
1383 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1384 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1385
1386 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1387 // the operand list contains a ConstantExpr or something else strange.
1388 return nullptr;
1389 }
1390
getSplat(ElementCount EC,Constant * V)1391 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
1392 if (!EC.isScalable()) {
1393 // If this splat is compatible with ConstantDataVector, use it instead of
1394 // ConstantVector.
1395 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1396 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1397 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1398
1399 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1400 return get(Elts);
1401 }
1402
1403 Type *VTy = VectorType::get(V->getType(), EC);
1404
1405 if (V->isNullValue())
1406 return ConstantAggregateZero::get(VTy);
1407 else if (isa<UndefValue>(V))
1408 return UndefValue::get(VTy);
1409
1410 Type *I32Ty = Type::getInt32Ty(VTy->getContext());
1411
1412 // Move scalar into vector.
1413 Constant *PoisonV = PoisonValue::get(VTy);
1414 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(I32Ty, 0));
1415 // Build shuffle mask to perform the splat.
1416 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1417 // Splat.
1418 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1419 }
1420
get(LLVMContext & Context)1421 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1422 LLVMContextImpl *pImpl = Context.pImpl;
1423 if (!pImpl->TheNoneToken)
1424 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1425 return pImpl->TheNoneToken.get();
1426 }
1427
1428 /// Remove the constant from the constant table.
destroyConstantImpl()1429 void ConstantTokenNone::destroyConstantImpl() {
1430 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1431 }
1432
1433 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1434 // can't be inline because we don't want to #include Instruction.h into
1435 // Constant.h
isCast() const1436 bool ConstantExpr::isCast() const {
1437 return Instruction::isCast(getOpcode());
1438 }
1439
isCompare() const1440 bool ConstantExpr::isCompare() const {
1441 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1442 }
1443
getPredicate() const1444 unsigned ConstantExpr::getPredicate() const {
1445 return cast<CompareConstantExpr>(this)->predicate;
1446 }
1447
getShuffleMask() const1448 ArrayRef<int> ConstantExpr::getShuffleMask() const {
1449 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1450 }
1451
getShuffleMaskForBitcode() const1452 Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1453 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1454 }
1455
getWithOperands(ArrayRef<Constant * > Ops,Type * Ty,bool OnlyIfReduced,Type * SrcTy) const1456 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1457 bool OnlyIfReduced, Type *SrcTy) const {
1458 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1459
1460 // If no operands changed return self.
1461 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1462 return const_cast<ConstantExpr*>(this);
1463
1464 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1465 switch (getOpcode()) {
1466 case Instruction::Trunc:
1467 case Instruction::ZExt:
1468 case Instruction::SExt:
1469 case Instruction::FPTrunc:
1470 case Instruction::FPExt:
1471 case Instruction::UIToFP:
1472 case Instruction::SIToFP:
1473 case Instruction::FPToUI:
1474 case Instruction::FPToSI:
1475 case Instruction::PtrToInt:
1476 case Instruction::IntToPtr:
1477 case Instruction::BitCast:
1478 case Instruction::AddrSpaceCast:
1479 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1480 case Instruction::Select:
1481 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1482 case Instruction::InsertElement:
1483 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1484 OnlyIfReducedTy);
1485 case Instruction::ExtractElement:
1486 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1487 case Instruction::FNeg:
1488 return ConstantExpr::getFNeg(Ops[0]);
1489 case Instruction::ShuffleVector:
1490 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1491 OnlyIfReducedTy);
1492 case Instruction::GetElementPtr: {
1493 auto *GEPO = cast<GEPOperator>(this);
1494 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1495 return ConstantExpr::getGetElementPtr(
1496 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1497 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1498 }
1499 case Instruction::ICmp:
1500 case Instruction::FCmp:
1501 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1502 OnlyIfReducedTy);
1503 default:
1504 assert(getNumOperands() == 2 && "Must be binary operator?");
1505 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1506 OnlyIfReducedTy);
1507 }
1508 }
1509
1510
1511 //===----------------------------------------------------------------------===//
1512 // isValueValidForType implementations
1513
isValueValidForType(Type * Ty,uint64_t Val)1514 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1515 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1516 if (Ty->isIntegerTy(1))
1517 return Val == 0 || Val == 1;
1518 return isUIntN(NumBits, Val);
1519 }
1520
isValueValidForType(Type * Ty,int64_t Val)1521 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1522 unsigned NumBits = Ty->getIntegerBitWidth();
1523 if (Ty->isIntegerTy(1))
1524 return Val == 0 || Val == 1 || Val == -1;
1525 return isIntN(NumBits, Val);
1526 }
1527
isValueValidForType(Type * Ty,const APFloat & Val)1528 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1529 // convert modifies in place, so make a copy.
1530 APFloat Val2 = APFloat(Val);
1531 bool losesInfo;
1532 switch (Ty->getTypeID()) {
1533 default:
1534 return false; // These can't be represented as floating point!
1535
1536 // FIXME rounding mode needs to be more flexible
1537 case Type::HalfTyID: {
1538 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1539 return true;
1540 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1541 return !losesInfo;
1542 }
1543 case Type::BFloatTyID: {
1544 if (&Val2.getSemantics() == &APFloat::BFloat())
1545 return true;
1546 Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1547 return !losesInfo;
1548 }
1549 case Type::FloatTyID: {
1550 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1551 return true;
1552 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1553 return !losesInfo;
1554 }
1555 case Type::DoubleTyID: {
1556 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1557 &Val2.getSemantics() == &APFloat::BFloat() ||
1558 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1559 &Val2.getSemantics() == &APFloat::IEEEdouble())
1560 return true;
1561 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1562 return !losesInfo;
1563 }
1564 case Type::X86_FP80TyID:
1565 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1566 &Val2.getSemantics() == &APFloat::BFloat() ||
1567 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1568 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1569 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1570 case Type::FP128TyID:
1571 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1572 &Val2.getSemantics() == &APFloat::BFloat() ||
1573 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1574 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1575 &Val2.getSemantics() == &APFloat::IEEEquad();
1576 case Type::PPC_FP128TyID:
1577 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1578 &Val2.getSemantics() == &APFloat::BFloat() ||
1579 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1580 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1581 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1582 }
1583 }
1584
1585
1586 //===----------------------------------------------------------------------===//
1587 // Factory Function Implementation
1588
get(Type * Ty)1589 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1590 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1591 "Cannot create an aggregate zero of non-aggregate type!");
1592
1593 std::unique_ptr<ConstantAggregateZero> &Entry =
1594 Ty->getContext().pImpl->CAZConstants[Ty];
1595 if (!Entry)
1596 Entry.reset(new ConstantAggregateZero(Ty));
1597
1598 return Entry.get();
1599 }
1600
1601 /// Remove the constant from the constant table.
destroyConstantImpl()1602 void ConstantAggregateZero::destroyConstantImpl() {
1603 getContext().pImpl->CAZConstants.erase(getType());
1604 }
1605
1606 /// Remove the constant from the constant table.
destroyConstantImpl()1607 void ConstantArray::destroyConstantImpl() {
1608 getType()->getContext().pImpl->ArrayConstants.remove(this);
1609 }
1610
1611
1612 //---- ConstantStruct::get() implementation...
1613 //
1614
1615 /// Remove the constant from the constant table.
destroyConstantImpl()1616 void ConstantStruct::destroyConstantImpl() {
1617 getType()->getContext().pImpl->StructConstants.remove(this);
1618 }
1619
1620 /// Remove the constant from the constant table.
destroyConstantImpl()1621 void ConstantVector::destroyConstantImpl() {
1622 getType()->getContext().pImpl->VectorConstants.remove(this);
1623 }
1624
getSplatValue(bool AllowUndefs) const1625 Constant *Constant::getSplatValue(bool AllowUndefs) const {
1626 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1627 if (isa<ConstantAggregateZero>(this))
1628 return getNullValue(cast<VectorType>(getType())->getElementType());
1629 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1630 return CV->getSplatValue();
1631 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1632 return CV->getSplatValue(AllowUndefs);
1633
1634 // Check if this is a constant expression splat of the form returned by
1635 // ConstantVector::getSplat()
1636 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1637 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1638 isa<UndefValue>(Shuf->getOperand(1))) {
1639
1640 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1641 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1642 isa<UndefValue>(IElt->getOperand(0))) {
1643
1644 ArrayRef<int> Mask = Shuf->getShuffleMask();
1645 Constant *SplatVal = IElt->getOperand(1);
1646 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1647
1648 if (Index && Index->getValue() == 0 &&
1649 llvm::all_of(Mask, [](int I) { return I == 0; }))
1650 return SplatVal;
1651 }
1652 }
1653
1654 return nullptr;
1655 }
1656
getSplatValue(bool AllowUndefs) const1657 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
1658 // Check out first element.
1659 Constant *Elt = getOperand(0);
1660 // Then make sure all remaining elements point to the same value.
1661 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1662 Constant *OpC = getOperand(I);
1663 if (OpC == Elt)
1664 continue;
1665
1666 // Strict mode: any mismatch is not a splat.
1667 if (!AllowUndefs)
1668 return nullptr;
1669
1670 // Allow undefs mode: ignore undefined elements.
1671 if (isa<UndefValue>(OpC))
1672 continue;
1673
1674 // If we do not have a defined element yet, use the current operand.
1675 if (isa<UndefValue>(Elt))
1676 Elt = OpC;
1677
1678 if (OpC != Elt)
1679 return nullptr;
1680 }
1681 return Elt;
1682 }
1683
getUniqueInteger() const1684 const APInt &Constant::getUniqueInteger() const {
1685 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1686 return CI->getValue();
1687 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1688 const Constant *C = this->getAggregateElement(0U);
1689 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1690 return cast<ConstantInt>(C)->getValue();
1691 }
1692
1693 //---- ConstantPointerNull::get() implementation.
1694 //
1695
get(PointerType * Ty)1696 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1697 std::unique_ptr<ConstantPointerNull> &Entry =
1698 Ty->getContext().pImpl->CPNConstants[Ty];
1699 if (!Entry)
1700 Entry.reset(new ConstantPointerNull(Ty));
1701
1702 return Entry.get();
1703 }
1704
1705 /// Remove the constant from the constant table.
destroyConstantImpl()1706 void ConstantPointerNull::destroyConstantImpl() {
1707 getContext().pImpl->CPNConstants.erase(getType());
1708 }
1709
get(Type * Ty)1710 UndefValue *UndefValue::get(Type *Ty) {
1711 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1712 if (!Entry)
1713 Entry.reset(new UndefValue(Ty));
1714
1715 return Entry.get();
1716 }
1717
1718 /// Remove the constant from the constant table.
destroyConstantImpl()1719 void UndefValue::destroyConstantImpl() {
1720 // Free the constant and any dangling references to it.
1721 if (getValueID() == UndefValueVal) {
1722 getContext().pImpl->UVConstants.erase(getType());
1723 } else if (getValueID() == PoisonValueVal) {
1724 getContext().pImpl->PVConstants.erase(getType());
1725 }
1726 llvm_unreachable("Not a undef or a poison!");
1727 }
1728
get(Type * Ty)1729 PoisonValue *PoisonValue::get(Type *Ty) {
1730 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1731 if (!Entry)
1732 Entry.reset(new PoisonValue(Ty));
1733
1734 return Entry.get();
1735 }
1736
1737 /// Remove the constant from the constant table.
destroyConstantImpl()1738 void PoisonValue::destroyConstantImpl() {
1739 // Free the constant and any dangling references to it.
1740 getContext().pImpl->PVConstants.erase(getType());
1741 }
1742
get(BasicBlock * BB)1743 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1744 assert(BB->getParent() && "Block must have a parent");
1745 return get(BB->getParent(), BB);
1746 }
1747
get(Function * F,BasicBlock * BB)1748 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1749 BlockAddress *&BA =
1750 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1751 if (!BA)
1752 BA = new BlockAddress(F, BB);
1753
1754 assert(BA->getFunction() == F && "Basic block moved between functions");
1755 return BA;
1756 }
1757
BlockAddress(Function * F,BasicBlock * BB)1758 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1759 : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
1760 Value::BlockAddressVal, &Op<0>(), 2) {
1761 setOperand(0, F);
1762 setOperand(1, BB);
1763 BB->AdjustBlockAddressRefCount(1);
1764 }
1765
lookup(const BasicBlock * BB)1766 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1767 if (!BB->hasAddressTaken())
1768 return nullptr;
1769
1770 const Function *F = BB->getParent();
1771 assert(F && "Block must have a parent");
1772 BlockAddress *BA =
1773 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1774 assert(BA && "Refcount and block address map disagree!");
1775 return BA;
1776 }
1777
1778 /// Remove the constant from the constant table.
destroyConstantImpl()1779 void BlockAddress::destroyConstantImpl() {
1780 getFunction()->getType()->getContext().pImpl
1781 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1782 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1783 }
1784
handleOperandChangeImpl(Value * From,Value * To)1785 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1786 // This could be replacing either the Basic Block or the Function. In either
1787 // case, we have to remove the map entry.
1788 Function *NewF = getFunction();
1789 BasicBlock *NewBB = getBasicBlock();
1790
1791 if (From == NewF)
1792 NewF = cast<Function>(To->stripPointerCasts());
1793 else {
1794 assert(From == NewBB && "From does not match any operand");
1795 NewBB = cast<BasicBlock>(To);
1796 }
1797
1798 // See if the 'new' entry already exists, if not, just update this in place
1799 // and return early.
1800 BlockAddress *&NewBA =
1801 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1802 if (NewBA)
1803 return NewBA;
1804
1805 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1806
1807 // Remove the old entry, this can't cause the map to rehash (just a
1808 // tombstone will get added).
1809 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1810 getBasicBlock()));
1811 NewBA = this;
1812 setOperand(0, NewF);
1813 setOperand(1, NewBB);
1814 getBasicBlock()->AdjustBlockAddressRefCount(1);
1815
1816 // If we just want to keep the existing value, then return null.
1817 // Callers know that this means we shouldn't delete this value.
1818 return nullptr;
1819 }
1820
get(GlobalValue * GV)1821 DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1822 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1823 if (!Equiv)
1824 Equiv = new DSOLocalEquivalent(GV);
1825
1826 assert(Equiv->getGlobalValue() == GV &&
1827 "DSOLocalFunction does not match the expected global value");
1828 return Equiv;
1829 }
1830
DSOLocalEquivalent(GlobalValue * GV)1831 DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1832 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
1833 setOperand(0, GV);
1834 }
1835
1836 /// Remove the constant from the constant table.
destroyConstantImpl()1837 void DSOLocalEquivalent::destroyConstantImpl() {
1838 const GlobalValue *GV = getGlobalValue();
1839 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1840 }
1841
handleOperandChangeImpl(Value * From,Value * To)1842 Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1843 assert(From == getGlobalValue() && "Changing value does not match operand.");
1844 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1845
1846 // The replacement is with another global value.
1847 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1848 DSOLocalEquivalent *&NewEquiv =
1849 getContext().pImpl->DSOLocalEquivalents[ToObj];
1850 if (NewEquiv)
1851 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1852 }
1853
1854 // If the argument is replaced with a null value, just replace this constant
1855 // with a null value.
1856 if (cast<Constant>(To)->isNullValue())
1857 return To;
1858
1859 // The replacement could be a bitcast or an alias to another function. We can
1860 // replace it with a bitcast to the dso_local_equivalent of that function.
1861 auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
1862 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
1863 if (NewEquiv)
1864 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1865
1866 // Replace this with the new one.
1867 getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
1868 NewEquiv = this;
1869 setOperand(0, Func);
1870
1871 if (Func->getType() != getType()) {
1872 // It is ok to mutate the type here because this constant should always
1873 // reflect the type of the function it's holding.
1874 mutateType(Func->getType());
1875 }
1876 return nullptr;
1877 }
1878
get(GlobalValue * GV)1879 NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
1880 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1881 if (!NC)
1882 NC = new NoCFIValue(GV);
1883
1884 assert(NC->getGlobalValue() == GV &&
1885 "NoCFIValue does not match the expected global value");
1886 return NC;
1887 }
1888
NoCFIValue(GlobalValue * GV)1889 NoCFIValue::NoCFIValue(GlobalValue *GV)
1890 : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1891 setOperand(0, GV);
1892 }
1893
1894 /// Remove the constant from the constant table.
destroyConstantImpl()1895 void NoCFIValue::destroyConstantImpl() {
1896 const GlobalValue *GV = getGlobalValue();
1897 GV->getContext().pImpl->NoCFIValues.erase(GV);
1898 }
1899
handleOperandChangeImpl(Value * From,Value * To)1900 Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1901 assert(From == getGlobalValue() && "Changing value does not match operand.");
1902
1903 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
1904 assert(GV && "Can only replace the operands with a global value");
1905
1906 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
1907 if (NewNC)
1908 return llvm::ConstantExpr::getBitCast(NewNC, getType());
1909
1910 getContext().pImpl->NoCFIValues.erase(getGlobalValue());
1911 NewNC = this;
1912 setOperand(0, GV);
1913
1914 if (GV->getType() != getType())
1915 mutateType(GV->getType());
1916
1917 return nullptr;
1918 }
1919
1920 //---- ConstantExpr::get() implementations.
1921 //
1922
1923 /// This is a utility function to handle folding of casts and lookup of the
1924 /// cast in the ExprConstants map. It is used by the various get* methods below.
getFoldedCast(Instruction::CastOps opc,Constant * C,Type * Ty,bool OnlyIfReduced=false)1925 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1926 bool OnlyIfReduced = false) {
1927 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1928 // Fold a few common cases
1929 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1930 return FC;
1931
1932 if (OnlyIfReduced)
1933 return nullptr;
1934
1935 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1936
1937 // Look up the constant in the table first to ensure uniqueness.
1938 ConstantExprKeyType Key(opc, C);
1939
1940 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1941 }
1942
getCast(unsigned oc,Constant * C,Type * Ty,bool OnlyIfReduced)1943 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1944 bool OnlyIfReduced) {
1945 Instruction::CastOps opc = Instruction::CastOps(oc);
1946 assert(Instruction::isCast(opc) && "opcode out of range");
1947 assert(C && Ty && "Null arguments to getCast");
1948 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1949
1950 switch (opc) {
1951 default:
1952 llvm_unreachable("Invalid cast opcode");
1953 case Instruction::Trunc:
1954 return getTrunc(C, Ty, OnlyIfReduced);
1955 case Instruction::ZExt:
1956 return getZExt(C, Ty, OnlyIfReduced);
1957 case Instruction::SExt:
1958 return getSExt(C, Ty, OnlyIfReduced);
1959 case Instruction::FPTrunc:
1960 return getFPTrunc(C, Ty, OnlyIfReduced);
1961 case Instruction::FPExt:
1962 return getFPExtend(C, Ty, OnlyIfReduced);
1963 case Instruction::UIToFP:
1964 return getUIToFP(C, Ty, OnlyIfReduced);
1965 case Instruction::SIToFP:
1966 return getSIToFP(C, Ty, OnlyIfReduced);
1967 case Instruction::FPToUI:
1968 return getFPToUI(C, Ty, OnlyIfReduced);
1969 case Instruction::FPToSI:
1970 return getFPToSI(C, Ty, OnlyIfReduced);
1971 case Instruction::PtrToInt:
1972 return getPtrToInt(C, Ty, OnlyIfReduced);
1973 case Instruction::IntToPtr:
1974 return getIntToPtr(C, Ty, OnlyIfReduced);
1975 case Instruction::BitCast:
1976 return getBitCast(C, Ty, OnlyIfReduced);
1977 case Instruction::AddrSpaceCast:
1978 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1979 }
1980 }
1981
getZExtOrBitCast(Constant * C,Type * Ty)1982 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1983 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1984 return getBitCast(C, Ty);
1985 return getZExt(C, Ty);
1986 }
1987
getSExtOrBitCast(Constant * C,Type * Ty)1988 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1989 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1990 return getBitCast(C, Ty);
1991 return getSExt(C, Ty);
1992 }
1993
getTruncOrBitCast(Constant * C,Type * Ty)1994 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1995 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1996 return getBitCast(C, Ty);
1997 return getTrunc(C, Ty);
1998 }
1999
getSExtOrTrunc(Constant * C,Type * Ty)2000 Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) {
2001 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2002 "Can only sign extend/truncate integers!");
2003 Type *CTy = C->getType();
2004 if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits())
2005 return getSExt(C, Ty);
2006 if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits())
2007 return getTrunc(C, Ty);
2008 return C;
2009 }
2010
getPointerCast(Constant * S,Type * Ty)2011 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
2012 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2013 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2014 "Invalid cast");
2015
2016 if (Ty->isIntOrIntVectorTy())
2017 return getPtrToInt(S, Ty);
2018
2019 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2020 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2021 return getAddrSpaceCast(S, Ty);
2022
2023 return getBitCast(S, Ty);
2024 }
2025
getPointerBitCastOrAddrSpaceCast(Constant * S,Type * Ty)2026 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
2027 Type *Ty) {
2028 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2029 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2030
2031 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2032 return getAddrSpaceCast(S, Ty);
2033
2034 return getBitCast(S, Ty);
2035 }
2036
getIntegerCast(Constant * C,Type * Ty,bool isSigned)2037 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
2038 assert(C->getType()->isIntOrIntVectorTy() &&
2039 Ty->isIntOrIntVectorTy() && "Invalid cast");
2040 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2041 unsigned DstBits = Ty->getScalarSizeInBits();
2042 Instruction::CastOps opcode =
2043 (SrcBits == DstBits ? Instruction::BitCast :
2044 (SrcBits > DstBits ? Instruction::Trunc :
2045 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2046 return getCast(opcode, C, Ty);
2047 }
2048
getFPCast(Constant * C,Type * Ty)2049 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
2050 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2051 "Invalid cast");
2052 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2053 unsigned DstBits = Ty->getScalarSizeInBits();
2054 if (SrcBits == DstBits)
2055 return C; // Avoid a useless cast
2056 Instruction::CastOps opcode =
2057 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2058 return getCast(opcode, C, Ty);
2059 }
2060
getTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)2061 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2062 #ifndef NDEBUG
2063 bool fromVec = isa<VectorType>(C->getType());
2064 bool toVec = isa<VectorType>(Ty);
2065 #endif
2066 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2067 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2068 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2069 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2070 "SrcTy must be larger than DestTy for Trunc!");
2071
2072 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2073 }
2074
getSExt(Constant * C,Type * Ty,bool OnlyIfReduced)2075 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2076 #ifndef NDEBUG
2077 bool fromVec = isa<VectorType>(C->getType());
2078 bool toVec = isa<VectorType>(Ty);
2079 #endif
2080 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2081 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
2082 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
2083 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2084 "SrcTy must be smaller than DestTy for SExt!");
2085
2086 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
2087 }
2088
getZExt(Constant * C,Type * Ty,bool OnlyIfReduced)2089 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2090 #ifndef NDEBUG
2091 bool fromVec = isa<VectorType>(C->getType());
2092 bool toVec = isa<VectorType>(Ty);
2093 #endif
2094 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2095 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
2096 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
2097 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2098 "SrcTy must be smaller than DestTy for ZExt!");
2099
2100 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
2101 }
2102
getFPTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)2103 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2104 #ifndef NDEBUG
2105 bool fromVec = isa<VectorType>(C->getType());
2106 bool toVec = isa<VectorType>(Ty);
2107 #endif
2108 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2109 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2110 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2111 "This is an illegal floating point truncation!");
2112 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
2113 }
2114
getFPExtend(Constant * C,Type * Ty,bool OnlyIfReduced)2115 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
2116 #ifndef NDEBUG
2117 bool fromVec = isa<VectorType>(C->getType());
2118 bool toVec = isa<VectorType>(Ty);
2119 #endif
2120 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2121 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2122 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2123 "This is an illegal floating point extension!");
2124 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
2125 }
2126
getUIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)2127 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2128 #ifndef NDEBUG
2129 bool fromVec = isa<VectorType>(C->getType());
2130 bool toVec = isa<VectorType>(Ty);
2131 #endif
2132 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2133 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2134 "This is an illegal uint to floating point cast!");
2135 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
2136 }
2137
getSIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)2138 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2139 #ifndef NDEBUG
2140 bool fromVec = isa<VectorType>(C->getType());
2141 bool toVec = isa<VectorType>(Ty);
2142 #endif
2143 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2144 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2145 "This is an illegal sint to floating point cast!");
2146 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
2147 }
2148
getFPToUI(Constant * C,Type * Ty,bool OnlyIfReduced)2149 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2150 #ifndef NDEBUG
2151 bool fromVec = isa<VectorType>(C->getType());
2152 bool toVec = isa<VectorType>(Ty);
2153 #endif
2154 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2155 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2156 "This is an illegal floating point to uint cast!");
2157 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
2158 }
2159
getFPToSI(Constant * C,Type * Ty,bool OnlyIfReduced)2160 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2161 #ifndef NDEBUG
2162 bool fromVec = isa<VectorType>(C->getType());
2163 bool toVec = isa<VectorType>(Ty);
2164 #endif
2165 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2166 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2167 "This is an illegal floating point to sint cast!");
2168 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
2169 }
2170
getPtrToInt(Constant * C,Type * DstTy,bool OnlyIfReduced)2171 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
2172 bool OnlyIfReduced) {
2173 assert(C->getType()->isPtrOrPtrVectorTy() &&
2174 "PtrToInt source must be pointer or pointer vector");
2175 assert(DstTy->isIntOrIntVectorTy() &&
2176 "PtrToInt destination must be integer or integer vector");
2177 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2178 if (isa<VectorType>(C->getType()))
2179 assert(cast<VectorType>(C->getType())->getElementCount() ==
2180 cast<VectorType>(DstTy)->getElementCount() &&
2181 "Invalid cast between a different number of vector elements");
2182 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2183 }
2184
getIntToPtr(Constant * C,Type * DstTy,bool OnlyIfReduced)2185 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
2186 bool OnlyIfReduced) {
2187 assert(C->getType()->isIntOrIntVectorTy() &&
2188 "IntToPtr source must be integer or integer vector");
2189 assert(DstTy->isPtrOrPtrVectorTy() &&
2190 "IntToPtr destination must be a pointer or pointer vector");
2191 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2192 if (isa<VectorType>(C->getType()))
2193 assert(cast<VectorType>(C->getType())->getElementCount() ==
2194 cast<VectorType>(DstTy)->getElementCount() &&
2195 "Invalid cast between a different number of vector elements");
2196 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2197 }
2198
getBitCast(Constant * C,Type * DstTy,bool OnlyIfReduced)2199 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
2200 bool OnlyIfReduced) {
2201 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2202 "Invalid constantexpr bitcast!");
2203
2204 // It is common to ask for a bitcast of a value to its own type, handle this
2205 // speedily.
2206 if (C->getType() == DstTy) return C;
2207
2208 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2209 }
2210
getAddrSpaceCast(Constant * C,Type * DstTy,bool OnlyIfReduced)2211 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
2212 bool OnlyIfReduced) {
2213 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2214 "Invalid constantexpr addrspacecast!");
2215
2216 // Canonicalize addrspacecasts between different pointer types by first
2217 // bitcasting the pointer type and then converting the address space.
2218 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
2219 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
2220 if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) {
2221 Type *MidTy = PointerType::getWithSamePointeeType(
2222 DstScalarTy, SrcScalarTy->getAddressSpace());
2223 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
2224 // Handle vectors of pointers.
2225 MidTy = FixedVectorType::get(MidTy,
2226 cast<FixedVectorType>(VT)->getNumElements());
2227 }
2228 C = getBitCast(C, MidTy);
2229 }
2230 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2231 }
2232
get(unsigned Opcode,Constant * C,unsigned Flags,Type * OnlyIfReducedTy)2233 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
2234 Type *OnlyIfReducedTy) {
2235 // Check the operands for consistency first.
2236 assert(Instruction::isUnaryOp(Opcode) &&
2237 "Invalid opcode in unary constant expression");
2238
2239 #ifndef NDEBUG
2240 switch (Opcode) {
2241 case Instruction::FNeg:
2242 assert(C->getType()->isFPOrFPVectorTy() &&
2243 "Tried to create a floating-point operation on a "
2244 "non-floating-point type!");
2245 break;
2246 default:
2247 break;
2248 }
2249 #endif
2250
2251 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
2252 return FC;
2253
2254 if (OnlyIfReducedTy == C->getType())
2255 return nullptr;
2256
2257 Constant *ArgVec[] = { C };
2258 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2259
2260 LLVMContextImpl *pImpl = C->getContext().pImpl;
2261 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
2262 }
2263
get(unsigned Opcode,Constant * C1,Constant * C2,unsigned Flags,Type * OnlyIfReducedTy)2264 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2265 unsigned Flags, Type *OnlyIfReducedTy) {
2266 // Check the operands for consistency first.
2267 assert(Instruction::isBinaryOp(Opcode) &&
2268 "Invalid opcode in binary constant expression");
2269 assert(isSupportedBinOp(Opcode) &&
2270 "Binop not supported as constant expression");
2271 assert(C1->getType() == C2->getType() &&
2272 "Operand types in binary constant expression should match");
2273
2274 #ifndef NDEBUG
2275 switch (Opcode) {
2276 case Instruction::Add:
2277 case Instruction::Sub:
2278 case Instruction::Mul:
2279 case Instruction::UDiv:
2280 case Instruction::SDiv:
2281 case Instruction::URem:
2282 case Instruction::SRem:
2283 assert(C1->getType()->isIntOrIntVectorTy() &&
2284 "Tried to create an integer operation on a non-integer type!");
2285 break;
2286 case Instruction::FAdd:
2287 case Instruction::FSub:
2288 case Instruction::FMul:
2289 case Instruction::FDiv:
2290 case Instruction::FRem:
2291 assert(C1->getType()->isFPOrFPVectorTy() &&
2292 "Tried to create a floating-point operation on a "
2293 "non-floating-point type!");
2294 break;
2295 case Instruction::And:
2296 case Instruction::Or:
2297 case Instruction::Xor:
2298 assert(C1->getType()->isIntOrIntVectorTy() &&
2299 "Tried to create a logical operation on a non-integral type!");
2300 break;
2301 case Instruction::Shl:
2302 case Instruction::LShr:
2303 case Instruction::AShr:
2304 assert(C1->getType()->isIntOrIntVectorTy() &&
2305 "Tried to create a shift operation on a non-integer type!");
2306 break;
2307 default:
2308 break;
2309 }
2310 #endif
2311
2312 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2313 return FC;
2314
2315 if (OnlyIfReducedTy == C1->getType())
2316 return nullptr;
2317
2318 Constant *ArgVec[] = { C1, C2 };
2319 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2320
2321 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2322 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2323 }
2324
isDesirableBinOp(unsigned Opcode)2325 bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2326 switch (Opcode) {
2327 case Instruction::UDiv:
2328 case Instruction::SDiv:
2329 case Instruction::URem:
2330 case Instruction::SRem:
2331 case Instruction::FAdd:
2332 case Instruction::FSub:
2333 case Instruction::FMul:
2334 case Instruction::FDiv:
2335 case Instruction::FRem:
2336 return false;
2337 case Instruction::Add:
2338 case Instruction::Sub:
2339 case Instruction::Mul:
2340 case Instruction::Shl:
2341 case Instruction::LShr:
2342 case Instruction::AShr:
2343 case Instruction::And:
2344 case Instruction::Or:
2345 case Instruction::Xor:
2346 return true;
2347 default:
2348 llvm_unreachable("Argument must be binop opcode");
2349 }
2350 }
2351
isSupportedBinOp(unsigned Opcode)2352 bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2353 switch (Opcode) {
2354 case Instruction::UDiv:
2355 case Instruction::SDiv:
2356 case Instruction::URem:
2357 case Instruction::SRem:
2358 case Instruction::FAdd:
2359 case Instruction::FSub:
2360 case Instruction::FMul:
2361 case Instruction::FDiv:
2362 case Instruction::FRem:
2363 return false;
2364 case Instruction::Add:
2365 case Instruction::Sub:
2366 case Instruction::Mul:
2367 case Instruction::Shl:
2368 case Instruction::LShr:
2369 case Instruction::AShr:
2370 case Instruction::And:
2371 case Instruction::Or:
2372 case Instruction::Xor:
2373 return true;
2374 default:
2375 llvm_unreachable("Argument must be binop opcode");
2376 }
2377 }
2378
getSizeOf(Type * Ty)2379 Constant *ConstantExpr::getSizeOf(Type* Ty) {
2380 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2381 // Note that a non-inbounds gep is used, as null isn't within any object.
2382 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2383 Constant *GEP = getGetElementPtr(
2384 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2385 return getPtrToInt(GEP,
2386 Type::getInt64Ty(Ty->getContext()));
2387 }
2388
getAlignOf(Type * Ty)2389 Constant *ConstantExpr::getAlignOf(Type* Ty) {
2390 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2391 // Note that a non-inbounds gep is used, as null isn't within any object.
2392 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2393 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
2394 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2395 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2396 Constant *Indices[2] = { Zero, One };
2397 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2398 return getPtrToInt(GEP,
2399 Type::getInt64Ty(Ty->getContext()));
2400 }
2401
getOffsetOf(StructType * STy,unsigned FieldNo)2402 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
2403 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
2404 FieldNo));
2405 }
2406
getOffsetOf(Type * Ty,Constant * FieldNo)2407 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
2408 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
2409 // Note that a non-inbounds gep is used, as null isn't within any object.
2410 Constant *GEPIdx[] = {
2411 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
2412 FieldNo
2413 };
2414 Constant *GEP = getGetElementPtr(
2415 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2416 return getPtrToInt(GEP,
2417 Type::getInt64Ty(Ty->getContext()));
2418 }
2419
getCompare(unsigned short Predicate,Constant * C1,Constant * C2,bool OnlyIfReduced)2420 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
2421 Constant *C2, bool OnlyIfReduced) {
2422 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2423
2424 switch (Predicate) {
2425 default: llvm_unreachable("Invalid CmpInst predicate");
2426 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2427 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2428 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2429 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2430 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2431 case CmpInst::FCMP_TRUE:
2432 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2433
2434 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2435 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2436 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2437 case CmpInst::ICMP_SLE:
2438 return getICmp(Predicate, C1, C2, OnlyIfReduced);
2439 }
2440 }
2441
getSelect(Constant * C,Constant * V1,Constant * V2,Type * OnlyIfReducedTy)2442 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
2443 Type *OnlyIfReducedTy) {
2444 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2445
2446 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2447 return SC; // Fold common cases
2448
2449 if (OnlyIfReducedTy == V1->getType())
2450 return nullptr;
2451
2452 Constant *ArgVec[] = { C, V1, V2 };
2453 ConstantExprKeyType Key(Instruction::Select, ArgVec);
2454
2455 LLVMContextImpl *pImpl = C->getContext().pImpl;
2456 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
2457 }
2458
getGetElementPtr(Type * Ty,Constant * C,ArrayRef<Value * > Idxs,bool InBounds,Optional<unsigned> InRangeIndex,Type * OnlyIfReducedTy)2459 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2460 ArrayRef<Value *> Idxs, bool InBounds,
2461 Optional<unsigned> InRangeIndex,
2462 Type *OnlyIfReducedTy) {
2463 PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType());
2464 assert(Ty && "Must specify element type");
2465 assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty));
2466
2467 if (Constant *FC =
2468 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2469 return FC; // Fold a few common cases.
2470
2471 // Get the result type of the getelementptr!
2472 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2473 assert(DestTy && "GEP indices invalid!");
2474 unsigned AS = OrigPtrTy->getAddressSpace();
2475 Type *ReqTy = OrigPtrTy->isOpaque()
2476 ? PointerType::get(OrigPtrTy->getContext(), AS)
2477 : DestTy->getPointerTo(AS);
2478
2479 auto EltCount = ElementCount::getFixed(0);
2480 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2481 EltCount = VecTy->getElementCount();
2482 else
2483 for (auto Idx : Idxs)
2484 if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
2485 EltCount = VecTy->getElementCount();
2486
2487 if (EltCount.isNonZero())
2488 ReqTy = VectorType::get(ReqTy, EltCount);
2489
2490 if (OnlyIfReducedTy == ReqTy)
2491 return nullptr;
2492
2493 // Look up the constant in the table first to ensure uniqueness
2494 std::vector<Constant*> ArgVec;
2495 ArgVec.reserve(1 + Idxs.size());
2496 ArgVec.push_back(C);
2497 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2498 for (; GTI != GTE; ++GTI) {
2499 auto *Idx = cast<Constant>(GTI.getOperand());
2500 assert(
2501 (!isa<VectorType>(Idx->getType()) ||
2502 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2503 "getelementptr index type missmatch");
2504
2505 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2506 Idx = Idx->getSplatValue();
2507 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2508 !Idx->getType()->isVectorTy()) {
2509 Idx = ConstantVector::getSplat(EltCount, Idx);
2510 }
2511 ArgVec.push_back(Idx);
2512 }
2513
2514 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2515 if (InRangeIndex && *InRangeIndex < 63)
2516 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2517 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2518 SubClassOptionalData, None, Ty);
2519
2520 LLVMContextImpl *pImpl = C->getContext().pImpl;
2521 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2522 }
2523
getICmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)2524 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2525 Constant *RHS, bool OnlyIfReduced) {
2526 auto Predicate = static_cast<CmpInst::Predicate>(pred);
2527 assert(LHS->getType() == RHS->getType());
2528 assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
2529
2530 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2531 return FC; // Fold a few common cases...
2532
2533 if (OnlyIfReduced)
2534 return nullptr;
2535
2536 // Look up the constant in the table first to ensure uniqueness
2537 Constant *ArgVec[] = { LHS, RHS };
2538 // Get the key type with both the opcode and predicate
2539 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
2540
2541 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2542 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2543 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2544
2545 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2546 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2547 }
2548
getFCmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)2549 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2550 Constant *RHS, bool OnlyIfReduced) {
2551 auto Predicate = static_cast<CmpInst::Predicate>(pred);
2552 assert(LHS->getType() == RHS->getType());
2553 assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
2554
2555 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2556 return FC; // Fold a few common cases...
2557
2558 if (OnlyIfReduced)
2559 return nullptr;
2560
2561 // Look up the constant in the table first to ensure uniqueness
2562 Constant *ArgVec[] = { LHS, RHS };
2563 // Get the key type with both the opcode and predicate
2564 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
2565
2566 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2567 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2568 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2569
2570 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2571 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2572 }
2573
getExtractElement(Constant * Val,Constant * Idx,Type * OnlyIfReducedTy)2574 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2575 Type *OnlyIfReducedTy) {
2576 assert(Val->getType()->isVectorTy() &&
2577 "Tried to create extractelement operation on non-vector type!");
2578 assert(Idx->getType()->isIntegerTy() &&
2579 "Extractelement index must be an integer type!");
2580
2581 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2582 return FC; // Fold a few common cases.
2583
2584 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2585 if (OnlyIfReducedTy == ReqTy)
2586 return nullptr;
2587
2588 // Look up the constant in the table first to ensure uniqueness
2589 Constant *ArgVec[] = { Val, Idx };
2590 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2591
2592 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2593 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2594 }
2595
getInsertElement(Constant * Val,Constant * Elt,Constant * Idx,Type * OnlyIfReducedTy)2596 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2597 Constant *Idx, Type *OnlyIfReducedTy) {
2598 assert(Val->getType()->isVectorTy() &&
2599 "Tried to create insertelement operation on non-vector type!");
2600 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2601 "Insertelement types must match!");
2602 assert(Idx->getType()->isIntegerTy() &&
2603 "Insertelement index must be i32 type!");
2604
2605 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2606 return FC; // Fold a few common cases.
2607
2608 if (OnlyIfReducedTy == Val->getType())
2609 return nullptr;
2610
2611 // Look up the constant in the table first to ensure uniqueness
2612 Constant *ArgVec[] = { Val, Elt, Idx };
2613 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2614
2615 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2616 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2617 }
2618
getShuffleVector(Constant * V1,Constant * V2,ArrayRef<int> Mask,Type * OnlyIfReducedTy)2619 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2620 ArrayRef<int> Mask,
2621 Type *OnlyIfReducedTy) {
2622 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2623 "Invalid shuffle vector constant expr operands!");
2624
2625 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2626 return FC; // Fold a few common cases.
2627
2628 unsigned NElts = Mask.size();
2629 auto V1VTy = cast<VectorType>(V1->getType());
2630 Type *EltTy = V1VTy->getElementType();
2631 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2632 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2633
2634 if (OnlyIfReducedTy == ShufTy)
2635 return nullptr;
2636
2637 // Look up the constant in the table first to ensure uniqueness
2638 Constant *ArgVec[] = {V1, V2};
2639 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, Mask);
2640
2641 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2642 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2643 }
2644
getNeg(Constant * C,bool HasNUW,bool HasNSW)2645 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2646 assert(C->getType()->isIntOrIntVectorTy() &&
2647 "Cannot NEG a nonintegral value!");
2648 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2649 C, HasNUW, HasNSW);
2650 }
2651
getFNeg(Constant * C)2652 Constant *ConstantExpr::getFNeg(Constant *C) {
2653 assert(C->getType()->isFPOrFPVectorTy() &&
2654 "Cannot FNEG a non-floating-point value!");
2655 return get(Instruction::FNeg, C);
2656 }
2657
getNot(Constant * C)2658 Constant *ConstantExpr::getNot(Constant *C) {
2659 assert(C->getType()->isIntOrIntVectorTy() &&
2660 "Cannot NOT a nonintegral value!");
2661 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2662 }
2663
getAdd(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2664 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2665 bool HasNUW, bool HasNSW) {
2666 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2667 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2668 return get(Instruction::Add, C1, C2, Flags);
2669 }
2670
getSub(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2671 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2672 bool HasNUW, bool HasNSW) {
2673 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2674 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2675 return get(Instruction::Sub, C1, C2, Flags);
2676 }
2677
getMul(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2678 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2679 bool HasNUW, bool HasNSW) {
2680 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2681 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2682 return get(Instruction::Mul, C1, C2, Flags);
2683 }
2684
getAnd(Constant * C1,Constant * C2)2685 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2686 return get(Instruction::And, C1, C2);
2687 }
2688
getOr(Constant * C1,Constant * C2)2689 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2690 return get(Instruction::Or, C1, C2);
2691 }
2692
getXor(Constant * C1,Constant * C2)2693 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2694 return get(Instruction::Xor, C1, C2);
2695 }
2696
getUMin(Constant * C1,Constant * C2)2697 Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) {
2698 Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2);
2699 return getSelect(Cmp, C1, C2);
2700 }
2701
getShl(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2702 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2703 bool HasNUW, bool HasNSW) {
2704 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2705 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2706 return get(Instruction::Shl, C1, C2, Flags);
2707 }
2708
getLShr(Constant * C1,Constant * C2,bool isExact)2709 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2710 return get(Instruction::LShr, C1, C2,
2711 isExact ? PossiblyExactOperator::IsExact : 0);
2712 }
2713
getAShr(Constant * C1,Constant * C2,bool isExact)2714 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2715 return get(Instruction::AShr, C1, C2,
2716 isExact ? PossiblyExactOperator::IsExact : 0);
2717 }
2718
getExactLogBase2(Constant * C)2719 Constant *ConstantExpr::getExactLogBase2(Constant *C) {
2720 Type *Ty = C->getType();
2721 const APInt *IVal;
2722 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2723 return ConstantInt::get(Ty, IVal->logBase2());
2724
2725 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2726 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2727 if (!VecTy)
2728 return nullptr;
2729
2730 SmallVector<Constant *, 4> Elts;
2731 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2732 Constant *Elt = C->getAggregateElement(I);
2733 if (!Elt)
2734 return nullptr;
2735 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2736 if (isa<UndefValue>(Elt)) {
2737 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2738 continue;
2739 }
2740 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2741 return nullptr;
2742 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2743 }
2744
2745 return ConstantVector::get(Elts);
2746 }
2747
getBinOpIdentity(unsigned Opcode,Type * Ty,bool AllowRHSConstant,bool NSZ)2748 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2749 bool AllowRHSConstant, bool NSZ) {
2750 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2751
2752 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2753 if (Instruction::isCommutative(Opcode)) {
2754 switch (Opcode) {
2755 case Instruction::Add: // X + 0 = X
2756 case Instruction::Or: // X | 0 = X
2757 case Instruction::Xor: // X ^ 0 = X
2758 return Constant::getNullValue(Ty);
2759 case Instruction::Mul: // X * 1 = X
2760 return ConstantInt::get(Ty, 1);
2761 case Instruction::And: // X & -1 = X
2762 return Constant::getAllOnesValue(Ty);
2763 case Instruction::FAdd: // X + -0.0 = X
2764 return ConstantFP::getZero(Ty, !NSZ);
2765 case Instruction::FMul: // X * 1.0 = X
2766 return ConstantFP::get(Ty, 1.0);
2767 default:
2768 llvm_unreachable("Every commutative binop has an identity constant");
2769 }
2770 }
2771
2772 // Non-commutative opcodes: AllowRHSConstant must be set.
2773 if (!AllowRHSConstant)
2774 return nullptr;
2775
2776 switch (Opcode) {
2777 case Instruction::Sub: // X - 0 = X
2778 case Instruction::Shl: // X << 0 = X
2779 case Instruction::LShr: // X >>u 0 = X
2780 case Instruction::AShr: // X >> 0 = X
2781 case Instruction::FSub: // X - 0.0 = X
2782 return Constant::getNullValue(Ty);
2783 case Instruction::SDiv: // X / 1 = X
2784 case Instruction::UDiv: // X /u 1 = X
2785 return ConstantInt::get(Ty, 1);
2786 case Instruction::FDiv: // X / 1.0 = X
2787 return ConstantFP::get(Ty, 1.0);
2788 default:
2789 return nullptr;
2790 }
2791 }
2792
getBinOpAbsorber(unsigned Opcode,Type * Ty)2793 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2794 switch (Opcode) {
2795 default:
2796 // Doesn't have an absorber.
2797 return nullptr;
2798
2799 case Instruction::Or:
2800 return Constant::getAllOnesValue(Ty);
2801
2802 case Instruction::And:
2803 case Instruction::Mul:
2804 return Constant::getNullValue(Ty);
2805 }
2806 }
2807
2808 /// Remove the constant from the constant table.
destroyConstantImpl()2809 void ConstantExpr::destroyConstantImpl() {
2810 getType()->getContext().pImpl->ExprConstants.remove(this);
2811 }
2812
getOpcodeName() const2813 const char *ConstantExpr::getOpcodeName() const {
2814 return Instruction::getOpcodeName(getOpcode());
2815 }
2816
GetElementPtrConstantExpr(Type * SrcElementTy,Constant * C,ArrayRef<Constant * > IdxList,Type * DestTy)2817 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2818 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2819 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2820 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2821 (IdxList.size() + 1),
2822 IdxList.size() + 1),
2823 SrcElementTy(SrcElementTy),
2824 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2825 Op<0>() = C;
2826 Use *OperandList = getOperandList();
2827 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2828 OperandList[i+1] = IdxList[i];
2829 }
2830
getSourceElementType() const2831 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2832 return SrcElementTy;
2833 }
2834
getResultElementType() const2835 Type *GetElementPtrConstantExpr::getResultElementType() const {
2836 return ResElementTy;
2837 }
2838
2839 //===----------------------------------------------------------------------===//
2840 // ConstantData* implementations
2841
getElementType() const2842 Type *ConstantDataSequential::getElementType() const {
2843 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2844 return ATy->getElementType();
2845 return cast<VectorType>(getType())->getElementType();
2846 }
2847
getRawDataValues() const2848 StringRef ConstantDataSequential::getRawDataValues() const {
2849 return StringRef(DataElements, getNumElements()*getElementByteSize());
2850 }
2851
isElementTypeCompatible(Type * Ty)2852 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2853 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2854 return true;
2855 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2856 switch (IT->getBitWidth()) {
2857 case 8:
2858 case 16:
2859 case 32:
2860 case 64:
2861 return true;
2862 default: break;
2863 }
2864 }
2865 return false;
2866 }
2867
getNumElements() const2868 unsigned ConstantDataSequential::getNumElements() const {
2869 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2870 return AT->getNumElements();
2871 return cast<FixedVectorType>(getType())->getNumElements();
2872 }
2873
2874
getElementByteSize() const2875 uint64_t ConstantDataSequential::getElementByteSize() const {
2876 return getElementType()->getPrimitiveSizeInBits()/8;
2877 }
2878
2879 /// Return the start of the specified element.
getElementPointer(unsigned Elt) const2880 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2881 assert(Elt < getNumElements() && "Invalid Elt");
2882 return DataElements+Elt*getElementByteSize();
2883 }
2884
2885
2886 /// Return true if the array is empty or all zeros.
isAllZeros(StringRef Arr)2887 static bool isAllZeros(StringRef Arr) {
2888 for (char I : Arr)
2889 if (I != 0)
2890 return false;
2891 return true;
2892 }
2893
2894 /// This is the underlying implementation of all of the
2895 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2896 /// the correct element type. We take the bytes in as a StringRef because
2897 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
getImpl(StringRef Elements,Type * Ty)2898 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2899 #ifndef NDEBUG
2900 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2901 assert(isElementTypeCompatible(ATy->getElementType()));
2902 else
2903 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2904 #endif
2905 // If the elements are all zero or there are no elements, return a CAZ, which
2906 // is more dense and canonical.
2907 if (isAllZeros(Elements))
2908 return ConstantAggregateZero::get(Ty);
2909
2910 // Do a lookup to see if we have already formed one of these.
2911 auto &Slot =
2912 *Ty->getContext()
2913 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2914 .first;
2915
2916 // The bucket can point to a linked list of different CDS's that have the same
2917 // body but different types. For example, 0,0,0,1 could be a 4 element array
2918 // of i8, or a 1-element array of i32. They'll both end up in the same
2919 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2920 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2921 for (; *Entry; Entry = &(*Entry)->Next)
2922 if ((*Entry)->getType() == Ty)
2923 return Entry->get();
2924
2925 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2926 // and return it.
2927 if (isa<ArrayType>(Ty)) {
2928 // Use reset because std::make_unique can't access the constructor.
2929 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2930 return Entry->get();
2931 }
2932
2933 assert(isa<VectorType>(Ty));
2934 // Use reset because std::make_unique can't access the constructor.
2935 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2936 return Entry->get();
2937 }
2938
destroyConstantImpl()2939 void ConstantDataSequential::destroyConstantImpl() {
2940 // Remove the constant from the StringMap.
2941 StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
2942 getType()->getContext().pImpl->CDSConstants;
2943
2944 auto Slot = CDSConstants.find(getRawDataValues());
2945
2946 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2947
2948 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2949
2950 // Remove the entry from the hash table.
2951 if (!(*Entry)->Next) {
2952 // If there is only one value in the bucket (common case) it must be this
2953 // entry, and removing the entry should remove the bucket completely.
2954 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2955 getContext().pImpl->CDSConstants.erase(Slot);
2956 return;
2957 }
2958
2959 // Otherwise, there are multiple entries linked off the bucket, unlink the
2960 // node we care about but keep the bucket around.
2961 while (true) {
2962 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2963 assert(Node && "Didn't find entry in its uniquing hash table!");
2964 // If we found our entry, unlink it from the list and we're done.
2965 if (Node.get() == this) {
2966 Node = std::move(Node->Next);
2967 return;
2968 }
2969
2970 Entry = &Node->Next;
2971 }
2972 }
2973
2974 /// getFP() constructors - Return a constant of array type with a float
2975 /// element type taken from argument `ElementType', and count taken from
2976 /// argument `Elts'. The amount of bits of the contained type must match the
2977 /// number of bits of the type contained in the passed in ArrayRef.
2978 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2979 /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)2980 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
2981 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2982 "Element type is not a 16-bit float type");
2983 Type *Ty = ArrayType::get(ElementType, Elts.size());
2984 const char *Data = reinterpret_cast<const char *>(Elts.data());
2985 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2986 }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)2987 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
2988 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2989 Type *Ty = ArrayType::get(ElementType, Elts.size());
2990 const char *Data = reinterpret_cast<const char *>(Elts.data());
2991 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2992 }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)2993 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
2994 assert(ElementType->isDoubleTy() &&
2995 "Element type is not a 64-bit float type");
2996 Type *Ty = ArrayType::get(ElementType, Elts.size());
2997 const char *Data = reinterpret_cast<const char *>(Elts.data());
2998 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2999 }
3000
getString(LLVMContext & Context,StringRef Str,bool AddNull)3001 Constant *ConstantDataArray::getString(LLVMContext &Context,
3002 StringRef Str, bool AddNull) {
3003 if (!AddNull) {
3004 const uint8_t *Data = Str.bytes_begin();
3005 return get(Context, makeArrayRef(Data, Str.size()));
3006 }
3007
3008 SmallVector<uint8_t, 64> ElementVals;
3009 ElementVals.append(Str.begin(), Str.end());
3010 ElementVals.push_back(0);
3011 return get(Context, ElementVals);
3012 }
3013
3014 /// get() constructors - Return a constant with vector type with an element
3015 /// count and element type matching the ArrayRef passed in. Note that this
3016 /// can return a ConstantAggregateZero object.
get(LLVMContext & Context,ArrayRef<uint8_t> Elts)3017 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
3018 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3019 const char *Data = reinterpret_cast<const char *>(Elts.data());
3020 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3021 }
get(LLVMContext & Context,ArrayRef<uint16_t> Elts)3022 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
3023 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3024 const char *Data = reinterpret_cast<const char *>(Elts.data());
3025 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3026 }
get(LLVMContext & Context,ArrayRef<uint32_t> Elts)3027 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
3028 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3029 const char *Data = reinterpret_cast<const char *>(Elts.data());
3030 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3031 }
get(LLVMContext & Context,ArrayRef<uint64_t> Elts)3032 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
3033 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3034 const char *Data = reinterpret_cast<const char *>(Elts.data());
3035 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3036 }
get(LLVMContext & Context,ArrayRef<float> Elts)3037 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
3038 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3039 const char *Data = reinterpret_cast<const char *>(Elts.data());
3040 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3041 }
get(LLVMContext & Context,ArrayRef<double> Elts)3042 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
3043 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3044 const char *Data = reinterpret_cast<const char *>(Elts.data());
3045 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3046 }
3047
3048 /// getFP() constructors - Return a constant of vector type with a float
3049 /// element type taken from argument `ElementType', and count taken from
3050 /// argument `Elts'. The amount of bits of the contained type must match the
3051 /// number of bits of the type contained in the passed in ArrayRef.
3052 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3053 /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)3054 Constant *ConstantDataVector::getFP(Type *ElementType,
3055 ArrayRef<uint16_t> Elts) {
3056 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3057 "Element type is not a 16-bit float type");
3058 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3059 const char *Data = reinterpret_cast<const char *>(Elts.data());
3060 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3061 }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)3062 Constant *ConstantDataVector::getFP(Type *ElementType,
3063 ArrayRef<uint32_t> Elts) {
3064 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3065 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3066 const char *Data = reinterpret_cast<const char *>(Elts.data());
3067 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3068 }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)3069 Constant *ConstantDataVector::getFP(Type *ElementType,
3070 ArrayRef<uint64_t> Elts) {
3071 assert(ElementType->isDoubleTy() &&
3072 "Element type is not a 64-bit float type");
3073 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3074 const char *Data = reinterpret_cast<const char *>(Elts.data());
3075 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3076 }
3077
getSplat(unsigned NumElts,Constant * V)3078 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
3079 assert(isElementTypeCompatible(V->getType()) &&
3080 "Element type not compatible with ConstantData");
3081 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3082 if (CI->getType()->isIntegerTy(8)) {
3083 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3084 return get(V->getContext(), Elts);
3085 }
3086 if (CI->getType()->isIntegerTy(16)) {
3087 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3088 return get(V->getContext(), Elts);
3089 }
3090 if (CI->getType()->isIntegerTy(32)) {
3091 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3092 return get(V->getContext(), Elts);
3093 }
3094 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3095 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3096 return get(V->getContext(), Elts);
3097 }
3098
3099 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3100 if (CFP->getType()->isHalfTy()) {
3101 SmallVector<uint16_t, 16> Elts(
3102 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3103 return getFP(V->getType(), Elts);
3104 }
3105 if (CFP->getType()->isBFloatTy()) {
3106 SmallVector<uint16_t, 16> Elts(
3107 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3108 return getFP(V->getType(), Elts);
3109 }
3110 if (CFP->getType()->isFloatTy()) {
3111 SmallVector<uint32_t, 16> Elts(
3112 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3113 return getFP(V->getType(), Elts);
3114 }
3115 if (CFP->getType()->isDoubleTy()) {
3116 SmallVector<uint64_t, 16> Elts(
3117 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3118 return getFP(V->getType(), Elts);
3119 }
3120 }
3121 return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
3122 }
3123
3124
getElementAsInteger(unsigned Elt) const3125 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
3126 assert(isa<IntegerType>(getElementType()) &&
3127 "Accessor can only be used when element is an integer");
3128 const char *EltPtr = getElementPointer(Elt);
3129
3130 // The data is stored in host byte order, make sure to cast back to the right
3131 // type to load with the right endianness.
3132 switch (getElementType()->getIntegerBitWidth()) {
3133 default: llvm_unreachable("Invalid bitwidth for CDS");
3134 case 8:
3135 return *reinterpret_cast<const uint8_t *>(EltPtr);
3136 case 16:
3137 return *reinterpret_cast<const uint16_t *>(EltPtr);
3138 case 32:
3139 return *reinterpret_cast<const uint32_t *>(EltPtr);
3140 case 64:
3141 return *reinterpret_cast<const uint64_t *>(EltPtr);
3142 }
3143 }
3144
getElementAsAPInt(unsigned Elt) const3145 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
3146 assert(isa<IntegerType>(getElementType()) &&
3147 "Accessor can only be used when element is an integer");
3148 const char *EltPtr = getElementPointer(Elt);
3149
3150 // The data is stored in host byte order, make sure to cast back to the right
3151 // type to load with the right endianness.
3152 switch (getElementType()->getIntegerBitWidth()) {
3153 default: llvm_unreachable("Invalid bitwidth for CDS");
3154 case 8: {
3155 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3156 return APInt(8, EltVal);
3157 }
3158 case 16: {
3159 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3160 return APInt(16, EltVal);
3161 }
3162 case 32: {
3163 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3164 return APInt(32, EltVal);
3165 }
3166 case 64: {
3167 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3168 return APInt(64, EltVal);
3169 }
3170 }
3171 }
3172
getElementAsAPFloat(unsigned Elt) const3173 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
3174 const char *EltPtr = getElementPointer(Elt);
3175
3176 switch (getElementType()->getTypeID()) {
3177 default:
3178 llvm_unreachable("Accessor can only be used when element is float/double!");
3179 case Type::HalfTyID: {
3180 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3181 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3182 }
3183 case Type::BFloatTyID: {
3184 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3185 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3186 }
3187 case Type::FloatTyID: {
3188 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3189 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3190 }
3191 case Type::DoubleTyID: {
3192 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3193 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3194 }
3195 }
3196 }
3197
getElementAsFloat(unsigned Elt) const3198 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
3199 assert(getElementType()->isFloatTy() &&
3200 "Accessor can only be used when element is a 'float'");
3201 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3202 }
3203
getElementAsDouble(unsigned Elt) const3204 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
3205 assert(getElementType()->isDoubleTy() &&
3206 "Accessor can only be used when element is a 'float'");
3207 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3208 }
3209
getElementAsConstant(unsigned Elt) const3210 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3211 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3212 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3213 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3214
3215 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3216 }
3217
isString(unsigned CharSize) const3218 bool ConstantDataSequential::isString(unsigned CharSize) const {
3219 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3220 }
3221
isCString() const3222 bool ConstantDataSequential::isCString() const {
3223 if (!isString())
3224 return false;
3225
3226 StringRef Str = getAsString();
3227
3228 // The last value must be nul.
3229 if (Str.back() != 0) return false;
3230
3231 // Other elements must be non-nul.
3232 return !Str.drop_back().contains(0);
3233 }
3234
isSplatData() const3235 bool ConstantDataVector::isSplatData() const {
3236 const char *Base = getRawDataValues().data();
3237
3238 // Compare elements 1+ to the 0'th element.
3239 unsigned EltSize = getElementByteSize();
3240 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3241 if (memcmp(Base, Base+i*EltSize, EltSize))
3242 return false;
3243
3244 return true;
3245 }
3246
isSplat() const3247 bool ConstantDataVector::isSplat() const {
3248 if (!IsSplatSet) {
3249 IsSplatSet = true;
3250 IsSplat = isSplatData();
3251 }
3252 return IsSplat;
3253 }
3254
getSplatValue() const3255 Constant *ConstantDataVector::getSplatValue() const {
3256 // If they're all the same, return the 0th one as a representative.
3257 return isSplat() ? getElementAsConstant(0) : nullptr;
3258 }
3259
3260 //===----------------------------------------------------------------------===//
3261 // handleOperandChange implementations
3262
3263 /// Update this constant array to change uses of
3264 /// 'From' to be uses of 'To'. This must update the uniquing data structures
3265 /// etc.
3266 ///
3267 /// Note that we intentionally replace all uses of From with To here. Consider
3268 /// a large array that uses 'From' 1000 times. By handling this case all here,
3269 /// ConstantArray::handleOperandChange is only invoked once, and that
3270 /// single invocation handles all 1000 uses. Handling them one at a time would
3271 /// work, but would be really slow because it would have to unique each updated
3272 /// array instance.
3273 ///
handleOperandChange(Value * From,Value * To)3274 void Constant::handleOperandChange(Value *From, Value *To) {
3275 Value *Replacement = nullptr;
3276 switch (getValueID()) {
3277 default:
3278 llvm_unreachable("Not a constant!");
3279 #define HANDLE_CONSTANT(Name) \
3280 case Value::Name##Val: \
3281 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3282 break;
3283 #include "llvm/IR/Value.def"
3284 }
3285
3286 // If handleOperandChangeImpl returned nullptr, then it handled
3287 // replacing itself and we don't want to delete or replace anything else here.
3288 if (!Replacement)
3289 return;
3290
3291 // I do need to replace this with an existing value.
3292 assert(Replacement != this && "I didn't contain From!");
3293
3294 // Everyone using this now uses the replacement.
3295 replaceAllUsesWith(Replacement);
3296
3297 // Delete the old constant!
3298 destroyConstant();
3299 }
3300
handleOperandChangeImpl(Value * From,Value * To)3301 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3302 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3303 Constant *ToC = cast<Constant>(To);
3304
3305 SmallVector<Constant*, 8> Values;
3306 Values.reserve(getNumOperands()); // Build replacement array.
3307
3308 // Fill values with the modified operands of the constant array. Also,
3309 // compute whether this turns into an all-zeros array.
3310 unsigned NumUpdated = 0;
3311
3312 // Keep track of whether all the values in the array are "ToC".
3313 bool AllSame = true;
3314 Use *OperandList = getOperandList();
3315 unsigned OperandNo = 0;
3316 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3317 Constant *Val = cast<Constant>(O->get());
3318 if (Val == From) {
3319 OperandNo = (O - OperandList);
3320 Val = ToC;
3321 ++NumUpdated;
3322 }
3323 Values.push_back(Val);
3324 AllSame &= Val == ToC;
3325 }
3326
3327 if (AllSame && ToC->isNullValue())
3328 return ConstantAggregateZero::get(getType());
3329
3330 if (AllSame && isa<UndefValue>(ToC))
3331 return UndefValue::get(getType());
3332
3333 // Check for any other type of constant-folding.
3334 if (Constant *C = getImpl(getType(), Values))
3335 return C;
3336
3337 // Update to the new value.
3338 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
3339 Values, this, From, ToC, NumUpdated, OperandNo);
3340 }
3341
handleOperandChangeImpl(Value * From,Value * To)3342 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3343 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3344 Constant *ToC = cast<Constant>(To);
3345
3346 Use *OperandList = getOperandList();
3347
3348 SmallVector<Constant*, 8> Values;
3349 Values.reserve(getNumOperands()); // Build replacement struct.
3350
3351 // Fill values with the modified operands of the constant struct. Also,
3352 // compute whether this turns into an all-zeros struct.
3353 unsigned NumUpdated = 0;
3354 bool AllSame = true;
3355 unsigned OperandNo = 0;
3356 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3357 Constant *Val = cast<Constant>(O->get());
3358 if (Val == From) {
3359 OperandNo = (O - OperandList);
3360 Val = ToC;
3361 ++NumUpdated;
3362 }
3363 Values.push_back(Val);
3364 AllSame &= Val == ToC;
3365 }
3366
3367 if (AllSame && ToC->isNullValue())
3368 return ConstantAggregateZero::get(getType());
3369
3370 if (AllSame && isa<UndefValue>(ToC))
3371 return UndefValue::get(getType());
3372
3373 // Update to the new value.
3374 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
3375 Values, this, From, ToC, NumUpdated, OperandNo);
3376 }
3377
handleOperandChangeImpl(Value * From,Value * To)3378 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3379 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3380 Constant *ToC = cast<Constant>(To);
3381
3382 SmallVector<Constant*, 8> Values;
3383 Values.reserve(getNumOperands()); // Build replacement array...
3384 unsigned NumUpdated = 0;
3385 unsigned OperandNo = 0;
3386 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3387 Constant *Val = getOperand(i);
3388 if (Val == From) {
3389 OperandNo = i;
3390 ++NumUpdated;
3391 Val = ToC;
3392 }
3393 Values.push_back(Val);
3394 }
3395
3396 if (Constant *C = getImpl(Values))
3397 return C;
3398
3399 // Update to the new value.
3400 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3401 Values, this, From, ToC, NumUpdated, OperandNo);
3402 }
3403
handleOperandChangeImpl(Value * From,Value * ToV)3404 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3405 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3406 Constant *To = cast<Constant>(ToV);
3407
3408 SmallVector<Constant*, 8> NewOps;
3409 unsigned NumUpdated = 0;
3410 unsigned OperandNo = 0;
3411 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3412 Constant *Op = getOperand(i);
3413 if (Op == From) {
3414 OperandNo = i;
3415 ++NumUpdated;
3416 Op = To;
3417 }
3418 NewOps.push_back(Op);
3419 }
3420 assert(NumUpdated && "I didn't contain From!");
3421
3422 if (Constant *C = getWithOperands(NewOps, getType(), true))
3423 return C;
3424
3425 // Update to the new value.
3426 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3427 NewOps, this, From, To, NumUpdated, OperandNo);
3428 }
3429
getAsInstruction(Instruction * InsertBefore) const3430 Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const {
3431 SmallVector<Value *, 4> ValueOperands(operands());
3432 ArrayRef<Value*> Ops(ValueOperands);
3433
3434 switch (getOpcode()) {
3435 case Instruction::Trunc:
3436 case Instruction::ZExt:
3437 case Instruction::SExt:
3438 case Instruction::FPTrunc:
3439 case Instruction::FPExt:
3440 case Instruction::UIToFP:
3441 case Instruction::SIToFP:
3442 case Instruction::FPToUI:
3443 case Instruction::FPToSI:
3444 case Instruction::PtrToInt:
3445 case Instruction::IntToPtr:
3446 case Instruction::BitCast:
3447 case Instruction::AddrSpaceCast:
3448 return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
3449 getType(), "", InsertBefore);
3450 case Instruction::Select:
3451 return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3452 case Instruction::InsertElement:
3453 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3454 case Instruction::ExtractElement:
3455 return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
3456 case Instruction::ShuffleVector:
3457 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
3458 InsertBefore);
3459
3460 case Instruction::GetElementPtr: {
3461 const auto *GO = cast<GEPOperator>(this);
3462 if (GO->isInBounds())
3463 return GetElementPtrInst::CreateInBounds(
3464 GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
3465 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3466 Ops.slice(1), "", InsertBefore);
3467 }
3468 case Instruction::ICmp:
3469 case Instruction::FCmp:
3470 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3471 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
3472 "", InsertBefore);
3473 case Instruction::FNeg:
3474 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0], "",
3475 InsertBefore);
3476 default:
3477 assert(getNumOperands() == 2 && "Must be binary operator?");
3478 BinaryOperator *BO = BinaryOperator::Create(
3479 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
3480 if (isa<OverflowingBinaryOperator>(BO)) {
3481 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3482 OverflowingBinaryOperator::NoUnsignedWrap);
3483 BO->setHasNoSignedWrap(SubclassOptionalData &
3484 OverflowingBinaryOperator::NoSignedWrap);
3485 }
3486 if (isa<PossiblyExactOperator>(BO))
3487 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3488 return BO;
3489 }
3490 }
3491