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