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