LLVM  10.0.0svn
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 "ConstantFold.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Debug.h"
30 #include <algorithm>
31 
32 using namespace llvm;
33 
34 //===----------------------------------------------------------------------===//
35 // Constant Class
36 //===----------------------------------------------------------------------===//
37 
39  // Floating point values have an explicit -0.0 value.
40  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
41  return CFP->isZero() && CFP->isNegative();
42 
43  // Equivalent for a vector of -0.0's.
44  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
45  if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
46  if (CV->getElementAsAPFloat(0).isNegZero())
47  return true;
48 
49  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
50  if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
51  if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
52  return true;
53 
54  // We've already handled true FP case; any other FP vectors can't represent -0.0.
55  if (getType()->isFPOrFPVectorTy())
56  return false;
57 
58  // Otherwise, just use +0.0.
59  return isNullValue();
60 }
61 
62 // Return true iff this constant is positive zero (floating point), negative
63 // zero (floating point), or a null value.
64 bool Constant::isZeroValue() const {
65  // Floating point values have an explicit -0.0 value.
66  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
67  return CFP->isZero();
68 
69  // Equivalent for a vector of -0.0's.
70  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
71  if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
72  if (CV->getElementAsAPFloat(0).isZero())
73  return true;
74 
75  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76  if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
77  if (SplatCFP && SplatCFP->isZero())
78  return true;
79 
80  // Otherwise, just use +0.0.
81  return isNullValue();
82 }
83 
84 bool Constant::isNullValue() const {
85  // 0 is null.
86  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
87  return CI->isZero();
88 
89  // +0.0 is null.
90  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
91  return CFP->isZero() && !CFP->isNegative();
92 
93  // constant zero is zero for aggregates, cpnull is null for pointers, none for
94  // tokens.
95  return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
96  isa<ConstantTokenNone>(this);
97 }
98 
100  // Check for -1 integers
101  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
102  return CI->isMinusOne();
103 
104  // Check for FP which are bitcasted from -1 integers
105  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
106  return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
107 
108  // Check for constant vectors which are splats of -1 values.
109  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
110  if (Constant *Splat = CV->getSplatValue())
111  return Splat->isAllOnesValue();
112 
113  // Check for constant vectors which are splats of -1 values.
114  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
115  if (CV->isSplat()) {
116  if (CV->getElementType()->isFloatingPointTy())
117  return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
118  return CV->getElementAsAPInt(0).isAllOnesValue();
119  }
120  }
121 
122  return false;
123 }
124 
125 bool Constant::isOneValue() const {
126  // Check for 1 integers
127  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128  return CI->isOne();
129 
130  // Check for FP which are bitcasted from 1 integers
131  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
132  return CFP->getValueAPF().bitcastToAPInt().isOneValue();
133 
134  // Check for constant vectors which are splats of 1 values.
135  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
136  if (Constant *Splat = CV->getSplatValue())
137  return Splat->isOneValue();
138 
139  // Check for constant vectors which are splats of 1 values.
140  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
141  if (CV->isSplat()) {
142  if (CV->getElementType()->isFloatingPointTy())
143  return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
144  return CV->getElementAsAPInt(0).isOneValue();
145  }
146  }
147 
148  return false;
149 }
150 
152  // Check for INT_MIN integers
153  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
154  return CI->isMinValue(/*isSigned=*/true);
155 
156  // Check for FP which are bitcasted from INT_MIN integers
157  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
158  return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
159 
160  // Check for constant vectors which are splats of INT_MIN values.
161  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
162  if (Constant *Splat = CV->getSplatValue())
163  return Splat->isMinSignedValue();
164 
165  // Check for constant vectors which are splats of INT_MIN values.
166  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
167  if (CV->isSplat()) {
168  if (CV->getElementType()->isFloatingPointTy())
169  return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
170  return CV->getElementAsAPInt(0).isMinSignedValue();
171  }
172  }
173 
174  return false;
175 }
176 
178  // Check for INT_MIN integers
179  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
180  return !CI->isMinValue(/*isSigned=*/true);
181 
182  // Check for FP which are bitcasted from INT_MIN integers
183  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
184  return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
185 
186  // Check that vectors don't contain INT_MIN
187  if (this->getType()->isVectorTy()) {
188  unsigned NumElts = this->getType()->getVectorNumElements();
189  for (unsigned i = 0; i != NumElts; ++i) {
190  Constant *Elt = this->getAggregateElement(i);
191  if (!Elt || !Elt->isNotMinSignedValue())
192  return false;
193  }
194  return true;
195  }
196 
197  // It *may* contain INT_MIN, we can't tell.
198  return false;
199 }
200 
202  if (auto *CFP = dyn_cast<ConstantFP>(this))
203  return CFP->getValueAPF().isFiniteNonZero();
204  if (!getType()->isVectorTy())
205  return false;
206  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208  if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209  return false;
210  }
211  return true;
212 }
213 
214 bool Constant::isNormalFP() const {
215  if (auto *CFP = dyn_cast<ConstantFP>(this))
216  return CFP->getValueAPF().isNormal();
217  if (!getType()->isVectorTy())
218  return false;
219  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221  if (!CFP || !CFP->getValueAPF().isNormal())
222  return false;
223  }
224  return true;
225 }
226 
228  if (auto *CFP = dyn_cast<ConstantFP>(this))
229  return CFP->getValueAPF().getExactInverse(nullptr);
230  if (!getType()->isVectorTy())
231  return false;
232  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234  if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235  return false;
236  }
237  return true;
238 }
239 
240 bool Constant::isNaN() const {
241  if (auto *CFP = dyn_cast<ConstantFP>(this))
242  return CFP->isNaN();
243  if (!getType()->isVectorTy())
244  return false;
245  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247  if (!CFP || !CFP->isNaN())
248  return false;
249  }
250  return true;
251 }
252 
254  if (!getType()->isVectorTy())
255  return false;
256  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257  if (isa<UndefValue>(getAggregateElement(i)))
258  return true;
259 
260  return false;
261 }
262 
264  if (!getType()->isVectorTy())
265  return false;
266  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
267  if (isa<ConstantExpr>(getAggregateElement(i)))
268  return true;
269 
270  return false;
271 }
272 
273 /// Constructor to create a '0' constant of arbitrary type.
275  switch (Ty->getTypeID()) {
276  case Type::IntegerTyID:
277  return ConstantInt::get(Ty, 0);
278  case Type::HalfTyID:
279  return ConstantFP::get(Ty->getContext(),
281  case Type::FloatTyID:
282  return ConstantFP::get(Ty->getContext(),
284  case Type::DoubleTyID:
285  return ConstantFP::get(Ty->getContext(),
287  case Type::X86_FP80TyID:
288  return ConstantFP::get(Ty->getContext(),
290  case Type::FP128TyID:
291  return ConstantFP::get(Ty->getContext(),
293  case Type::PPC_FP128TyID:
294  return ConstantFP::get(Ty->getContext(),
296  APInt::getNullValue(128)));
297  case Type::PointerTyID:
298  return ConstantPointerNull::get(cast<PointerType>(Ty));
299  case Type::StructTyID:
300  case Type::ArrayTyID:
301  case Type::VectorTyID:
302  return ConstantAggregateZero::get(Ty);
303  case Type::TokenTyID:
304  return ConstantTokenNone::get(Ty->getContext());
305  default:
306  // Function, Label, or Opaque type?
307  llvm_unreachable("Cannot create a null constant of that type!");
308  }
309 }
310 
312  Type *ScalarTy = Ty->getScalarType();
313 
314  // Create the base integer constant.
315  Constant *C = ConstantInt::get(Ty->getContext(), V);
316 
317  // Convert an integer to a pointer, if necessary.
318  if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
319  C = ConstantExpr::getIntToPtr(C, PTy);
320 
321  // Broadcast a scalar to a vector, if necessary.
322  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
323  C = ConstantVector::getSplat(VTy->getNumElements(), C);
324 
325  return C;
326 }
327 
329  if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
330  return ConstantInt::get(Ty->getContext(),
331  APInt::getAllOnesValue(ITy->getBitWidth()));
332 
333  if (Ty->isFloatingPointTy()) {
335  !Ty->isPPC_FP128Ty());
336  return ConstantFP::get(Ty->getContext(), FL);
337  }
338 
339  VectorType *VTy = cast<VectorType>(Ty);
340  return ConstantVector::getSplat(VTy->getNumElements(),
341  getAllOnesValue(VTy->getElementType()));
342 }
343 
345  if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
346  return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
347 
348  if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
349  return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
350 
351  if (const UndefValue *UV = dyn_cast<UndefValue>(this))
352  return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
353 
354  if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
355  return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
356  : nullptr;
357  return nullptr;
358 }
359 
361  assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
362  if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
363  // Check if the constant fits into an uint64_t.
364  if (CI->getValue().getActiveBits() > 64)
365  return nullptr;
366  return getAggregateElement(CI->getZExtValue());
367  }
368  return nullptr;
369 }
370 
372  /// First call destroyConstantImpl on the subclass. This gives the subclass
373  /// a chance to remove the constant from any maps/pools it's contained in.
374  switch (getValueID()) {
375  default:
376  llvm_unreachable("Not a constant!");
377 #define HANDLE_CONSTANT(Name) \
378  case Value::Name##Val: \
379  cast<Name>(this)->destroyConstantImpl(); \
380  break;
381 #include "llvm/IR/Value.def"
382  }
383 
384  // When a Constant is destroyed, there may be lingering
385  // references to the constant by other constants in the constant pool. These
386  // constants are implicitly dependent on the module that is being deleted,
387  // but they don't know that. Because we only find out when the CPV is
388  // deleted, we must now notify all of our users (that should only be
389  // Constants) that they are, in fact, invalid now and should be deleted.
390  //
391  while (!use_empty()) {
392  Value *V = user_back();
393 #ifndef NDEBUG // Only in -g mode...
394  if (!isa<Constant>(V)) {
395  dbgs() << "While deleting: " << *this
396  << "\n\nUse still stuck around after Def is destroyed: " << *V
397  << "\n\n";
398  }
399 #endif
400  assert(isa<Constant>(V) && "References remain to Constant being destroyed");
401  cast<Constant>(V)->destroyConstant();
402 
403  // The constant should remove itself from our use list...
404  assert((use_empty() || user_back() != V) && "Constant not removed!");
405  }
406 
407  // Value has no outstanding references it is safe to delete it now...
408  delete this;
409 }
410 
411 static bool canTrapImpl(const Constant *C,
412  SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
413  assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
414  // The only thing that could possibly trap are constant exprs.
415  const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
416  if (!CE)
417  return false;
418 
419  // ConstantExpr traps if any operands can trap.
420  for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
421  if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
422  if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
423  return true;
424  }
425  }
426 
427  // Otherwise, only specific operations can trap.
428  switch (CE->getOpcode()) {
429  default:
430  return false;
431  case Instruction::UDiv:
432  case Instruction::SDiv:
433  case Instruction::URem:
434  case Instruction::SRem:
435  // Div and rem can trap if the RHS is not known to be non-zero.
436  if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
437  return true;
438  return false;
439  }
440 }
441 
442 bool Constant::canTrap() const {
444  return canTrapImpl(this, NonTrappingOps);
445 }
446 
447 /// Check if C contains a GlobalValue for which Predicate is true.
448 static bool
450  bool (*Predicate)(const GlobalValue *)) {
453  WorkList.push_back(C);
454  Visited.insert(C);
455 
456  while (!WorkList.empty()) {
457  const Constant *WorkItem = WorkList.pop_back_val();
458  if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
459  if (Predicate(GV))
460  return true;
461  for (const Value *Op : WorkItem->operands()) {
462  const Constant *ConstOp = dyn_cast<Constant>(Op);
463  if (!ConstOp)
464  continue;
465  if (Visited.insert(ConstOp).second)
466  WorkList.push_back(ConstOp);
467  }
468  }
469  return false;
470 }
471 
473  auto DLLImportPredicate = [](const GlobalValue *GV) {
474  return GV->isThreadLocal();
475  };
476  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
477 }
478 
480  auto DLLImportPredicate = [](const GlobalValue *GV) {
481  return GV->hasDLLImportStorageClass();
482  };
483  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
484 }
485 
487  for (const User *U : users()) {
488  const Constant *UC = dyn_cast<Constant>(U);
489  if (!UC || isa<GlobalValue>(UC))
490  return true;
491 
492  if (UC->isConstantUsed())
493  return true;
494  }
495  return false;
496 }
497 
499  if (isa<GlobalValue>(this))
500  return true; // Global reference.
501 
502  if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
503  return BA->getFunction()->needsRelocation();
504 
505  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
506  if (CE->getOpcode() == Instruction::Sub) {
507  ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
508  ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
509  if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
510  RHS->getOpcode() == Instruction::PtrToInt) {
511  Constant *LHSOp0 = LHS->getOperand(0);
512  Constant *RHSOp0 = RHS->getOperand(0);
513 
514  // While raw uses of blockaddress need to be relocated, differences
515  // between two of them don't when they are for labels in the same
516  // function. This is a common idiom when creating a table for the
517  // indirect goto extension, so we handle it efficiently here.
518  if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
519  cast<BlockAddress>(LHSOp0)->getFunction() ==
520  cast<BlockAddress>(RHSOp0)->getFunction())
521  return false;
522 
523  // Relative pointers do not need to be dynamically relocated.
524  if (auto *LHSGV = dyn_cast<GlobalValue>(
526  if (auto *RHSGV = dyn_cast<GlobalValue>(
528  if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
529  return false;
530  }
531  }
532  }
533 
534  bool Result = false;
535  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
536  Result |= cast<Constant>(getOperand(i))->needsRelocation();
537 
538  return Result;
539 }
540 
541 /// If the specified constantexpr is dead, remove it. This involves recursively
542 /// eliminating any dead users of the constantexpr.
543 static bool removeDeadUsersOfConstant(const Constant *C) {
544  if (isa<GlobalValue>(C)) return false; // Cannot remove this
545 
546  while (!C->use_empty()) {
547  const Constant *User = dyn_cast<Constant>(C->user_back());
548  if (!User) return false; // Non-constant usage;
549  if (!removeDeadUsersOfConstant(User))
550  return false; // Constant wasn't dead
551  }
552 
553  const_cast<Constant*>(C)->destroyConstant();
554  return true;
555 }
556 
557 
560  Value::const_user_iterator LastNonDeadUser = E;
561  while (I != E) {
562  const Constant *User = dyn_cast<Constant>(*I);
563  if (!User) {
564  LastNonDeadUser = I;
565  ++I;
566  continue;
567  }
568 
569  if (!removeDeadUsersOfConstant(User)) {
570  // If the constant wasn't dead, remember that this was the last live use
571  // and move on to the next constant.
572  LastNonDeadUser = I;
573  ++I;
574  continue;
575  }
576 
577  // If the constant was dead, then the iterator is invalidated.
578  if (LastNonDeadUser == E) {
579  I = user_begin();
580  if (I == E) break;
581  } else {
582  I = LastNonDeadUser;
583  ++I;
584  }
585  }
586 }
587 
588 
589 
590 //===----------------------------------------------------------------------===//
591 // ConstantInt
592 //===----------------------------------------------------------------------===//
593 
594 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
595  : ConstantData(Ty, ConstantIntVal), Val(V) {
596  assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
597 }
598 
600  LLVMContextImpl *pImpl = Context.pImpl;
601  if (!pImpl->TheTrueVal)
602  pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
603  return pImpl->TheTrueVal;
604 }
605 
607  LLVMContextImpl *pImpl = Context.pImpl;
608  if (!pImpl->TheFalseVal)
609  pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
610  return pImpl->TheFalseVal;
611 }
612 
614  assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
616  if (auto *VTy = dyn_cast<VectorType>(Ty))
617  return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
618  return TrueC;
619 }
620 
622  assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
624  if (auto *VTy = dyn_cast<VectorType>(Ty))
625  return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
626  return FalseC;
627 }
628 
629 // Get a ConstantInt from an APInt.
631  // get an existing value or the insertion position
632  LLVMContextImpl *pImpl = Context.pImpl;
633  std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
634  if (!Slot) {
635  // Get the corresponding integer type for the bit width of the value.
636  IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
637  Slot.reset(new ConstantInt(ITy, V));
638  }
639  assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
640  return Slot.get();
641 }
642 
643 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
644  Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
645 
646  // For vectors, broadcast the value.
647  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
648  return ConstantVector::getSplat(VTy->getNumElements(), C);
649 
650  return C;
651 }
652 
653 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
654  return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
655 }
656 
658  return get(Ty, V, true);
659 }
660 
662  return get(Ty, V, true);
663 }
664 
666  ConstantInt *C = get(Ty->getContext(), V);
667  assert(C->getType() == Ty->getScalarType() &&
668  "ConstantInt type doesn't match the type implied by its value!");
669 
670  // For vectors, broadcast the value.
671  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
672  return ConstantVector::getSplat(VTy->getNumElements(), C);
673 
674  return C;
675 }
676 
678  return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
679 }
680 
681 /// Remove the constant from the constant table.
682 void ConstantInt::destroyConstantImpl() {
683  llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
684 }
685 
686 //===----------------------------------------------------------------------===//
687 // ConstantFP
688 //===----------------------------------------------------------------------===//
689 
691  if (Ty->isHalfTy())
692  return &APFloat::IEEEhalf();
693  if (Ty->isFloatTy())
694  return &APFloat::IEEEsingle();
695  if (Ty->isDoubleTy())
696  return &APFloat::IEEEdouble();
697  if (Ty->isX86_FP80Ty())
698  return &APFloat::x87DoubleExtended();
699  else if (Ty->isFP128Ty())
700  return &APFloat::IEEEquad();
701 
702  assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
703  return &APFloat::PPCDoubleDouble();
704 }
705 
706 Constant *ConstantFP::get(Type *Ty, double V) {
707  LLVMContext &Context = Ty->getContext();
708 
709  APFloat FV(V);
710  bool ignored;
712  APFloat::rmNearestTiesToEven, &ignored);
713  Constant *C = get(Context, FV);
714 
715  // For vectors, broadcast the value.
716  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
717  return ConstantVector::getSplat(VTy->getNumElements(), C);
718 
719  return C;
720 }
721 
723  ConstantFP *C = get(Ty->getContext(), V);
724  assert(C->getType() == Ty->getScalarType() &&
725  "ConstantFP type doesn't match the type implied by its value!");
726 
727  // For vectors, broadcast the value.
728  if (auto *VTy = dyn_cast<VectorType>(Ty))
729  return ConstantVector::getSplat(VTy->getNumElements(), C);
730 
731  return C;
732 }
733 
735  LLVMContext &Context = Ty->getContext();
736 
737  APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
738  Constant *C = get(Context, FV);
739 
740  // For vectors, broadcast the value.
741  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
742  return ConstantVector::getSplat(VTy->getNumElements(), C);
743 
744  return C;
745 }
746 
747 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
748  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
749  APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
750  Constant *C = get(Ty->getContext(), NaN);
751 
752  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
753  return ConstantVector::getSplat(VTy->getNumElements(), C);
754 
755  return C;
756 }
757 
758 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
759  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
760  APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
761  Constant *C = get(Ty->getContext(), NaN);
762 
763  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
764  return ConstantVector::getSplat(VTy->getNumElements(), C);
765 
766  return C;
767 }
768 
769 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
770  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
771  APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
772  Constant *C = get(Ty->getContext(), NaN);
773 
774  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
775  return ConstantVector::getSplat(VTy->getNumElements(), C);
776 
777  return C;
778 }
779 
781  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
782  APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
783  Constant *C = get(Ty->getContext(), NegZero);
784 
785  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
786  return ConstantVector::getSplat(VTy->getNumElements(), C);
787 
788  return C;
789 }
790 
791 
793  if (Ty->isFPOrFPVectorTy())
794  return getNegativeZero(Ty);
795 
796  return Constant::getNullValue(Ty);
797 }
798 
799 
800 // ConstantFP accessors.
802  LLVMContextImpl* pImpl = Context.pImpl;
803 
804  std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
805 
806  if (!Slot) {
807  Type *Ty;
808  if (&V.getSemantics() == &APFloat::IEEEhalf())
809  Ty = Type::getHalfTy(Context);
810  else if (&V.getSemantics() == &APFloat::IEEEsingle())
811  Ty = Type::getFloatTy(Context);
812  else if (&V.getSemantics() == &APFloat::IEEEdouble())
813  Ty = Type::getDoubleTy(Context);
814  else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
815  Ty = Type::getX86_FP80Ty(Context);
816  else if (&V.getSemantics() == &APFloat::IEEEquad())
817  Ty = Type::getFP128Ty(Context);
818  else {
820  "Unknown FP format");
821  Ty = Type::getPPC_FP128Ty(Context);
822  }
823  Slot.reset(new ConstantFP(Ty, V));
824  }
825 
826  return Slot.get();
827 }
828 
829 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
830  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
831  Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
832 
833  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
834  return ConstantVector::getSplat(VTy->getNumElements(), C);
835 
836  return C;
837 }
838 
839 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
840  : ConstantData(Ty, ConstantFPVal), Val(V) {
842  "FP type Mismatch");
843 }
844 
845 bool ConstantFP::isExactlyValue(const APFloat &V) const {
846  return Val.bitwiseIsEqual(V);
847 }
848 
849 /// Remove the constant from the constant table.
850 void ConstantFP::destroyConstantImpl() {
851  llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
852 }
853 
854 //===----------------------------------------------------------------------===//
855 // ConstantAggregateZero Implementation
856 //===----------------------------------------------------------------------===//
857 
859  return Constant::getNullValue(getType()->getSequentialElementType());
860 }
861 
863  return Constant::getNullValue(getType()->getStructElementType(Elt));
864 }
865 
867  if (isa<SequentialType>(getType()))
868  return getSequentialElement();
869  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
870 }
871 
873  if (isa<SequentialType>(getType()))
874  return getSequentialElement();
875  return getStructElement(Idx);
876 }
877 
879  Type *Ty = getType();
880  if (auto *AT = dyn_cast<ArrayType>(Ty))
881  return AT->getNumElements();
882  if (auto *VT = dyn_cast<VectorType>(Ty))
883  return VT->getNumElements();
884  return Ty->getStructNumElements();
885 }
886 
887 //===----------------------------------------------------------------------===//
888 // UndefValue Implementation
889 //===----------------------------------------------------------------------===//
890 
892  return UndefValue::get(getType()->getSequentialElementType());
893 }
894 
896  return UndefValue::get(getType()->getStructElementType(Elt));
897 }
898 
900  if (isa<SequentialType>(getType()))
901  return getSequentialElement();
902  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
903 }
904 
906  if (isa<SequentialType>(getType()))
907  return getSequentialElement();
908  return getStructElement(Idx);
909 }
910 
911 unsigned UndefValue::getNumElements() const {
912  Type *Ty = getType();
913  if (auto *ST = dyn_cast<SequentialType>(Ty))
914  return ST->getNumElements();
915  return Ty->getStructNumElements();
916 }
917 
918 //===----------------------------------------------------------------------===//
919 // ConstantXXX Classes
920 //===----------------------------------------------------------------------===//
921 
922 template <typename ItTy, typename EltTy>
923 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
924  for (; Start != End; ++Start)
925  if (*Start != Elt)
926  return false;
927  return true;
928 }
929 
930 template <typename SequentialTy, typename ElementTy>
932  assert(!V.empty() && "Cannot get empty int sequence.");
933 
935  for (Constant *C : V)
936  if (auto *CI = dyn_cast<ConstantInt>(C))
937  Elts.push_back(CI->getZExtValue());
938  else
939  return nullptr;
940  return SequentialTy::get(V[0]->getContext(), Elts);
941 }
942 
943 template <typename SequentialTy, typename ElementTy>
945  assert(!V.empty() && "Cannot get empty FP sequence.");
946 
948  for (Constant *C : V)
949  if (auto *CFP = dyn_cast<ConstantFP>(C))
950  Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
951  else
952  return nullptr;
953  return SequentialTy::getFP(V[0]->getContext(), Elts);
954 }
955 
956 template <typename SequenceTy>
959  // We speculatively build the elements here even if it turns out that there is
960  // a constantexpr or something else weird, since it is so uncommon for that to
961  // happen.
962  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
963  if (CI->getType()->isIntegerTy(8))
964  return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
965  else if (CI->getType()->isIntegerTy(16))
966  return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
967  else if (CI->getType()->isIntegerTy(32))
968  return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
969  else if (CI->getType()->isIntegerTy(64))
970  return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
971  } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
972  if (CFP->getType()->isHalfTy())
973  return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
974  else if (CFP->getType()->isFloatTy())
975  return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
976  else if (CFP->getType()->isDoubleTy())
977  return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
978  }
979 
980  return nullptr;
981 }
982 
985  : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
986  V.size()) {
987  llvm::copy(V, op_begin());
988 
989  // Check that types match, unless this is an opaque struct.
990  if (auto *ST = dyn_cast<StructType>(T))
991  if (ST->isOpaque())
992  return;
993  for (unsigned I = 0, E = V.size(); I != E; ++I)
994  assert(V[I]->getType() == T->getTypeAtIndex(I) &&
995  "Initializer for composite element doesn't match!");
996 }
997 
998 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
999  : ConstantAggregate(T, ConstantArrayVal, V) {
1000  assert(V.size() == T->getNumElements() &&
1001  "Invalid initializer for constant array");
1002 }
1003 
1005  if (Constant *C = getImpl(Ty, V))
1006  return C;
1007  return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1008 }
1009 
1011  // Empty arrays are canonicalized to ConstantAggregateZero.
1012  if (V.empty())
1013  return ConstantAggregateZero::get(Ty);
1014 
1015  for (unsigned i = 0, e = V.size(); i != e; ++i) {
1016  assert(V[i]->getType() == Ty->getElementType() &&
1017  "Wrong type in array element initializer");
1018  }
1019 
1020  // If this is an all-zero array, return a ConstantAggregateZero object. If
1021  // all undef, return an UndefValue, if "all simple", then return a
1022  // ConstantDataArray.
1023  Constant *C = V[0];
1024  if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1025  return UndefValue::get(Ty);
1026 
1027  if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1028  return ConstantAggregateZero::get(Ty);
1029 
1030  // Check to see if all of the elements are ConstantFP or ConstantInt and if
1031  // the element type is compatible with ConstantDataVector. If so, use it.
1033  return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1034 
1035  // Otherwise, we really do want to create a ConstantArray.
1036  return nullptr;
1037 }
1038 
1041  bool Packed) {
1042  unsigned VecSize = V.size();
1043  SmallVector<Type*, 16> EltTypes(VecSize);
1044  for (unsigned i = 0; i != VecSize; ++i)
1045  EltTypes[i] = V[i]->getType();
1046 
1047  return StructType::get(Context, EltTypes, Packed);
1048 }
1049 
1050 
1052  bool Packed) {
1053  assert(!V.empty() &&
1054  "ConstantStruct::getTypeForElements cannot be called on empty list");
1055  return getTypeForElements(V[0]->getContext(), V, Packed);
1056 }
1057 
1058 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1059  : ConstantAggregate(T, ConstantStructVal, V) {
1060  assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1061  "Invalid initializer for constant struct");
1062 }
1063 
1064 // ConstantStruct accessors.
1066  assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1067  "Incorrect # elements specified to ConstantStruct::get");
1068 
1069  // Create a ConstantAggregateZero value if all elements are zeros.
1070  bool isZero = true;
1071  bool isUndef = false;
1072 
1073  if (!V.empty()) {
1074  isUndef = isa<UndefValue>(V[0]);
1075  isZero = V[0]->isNullValue();
1076  if (isUndef || isZero) {
1077  for (unsigned i = 0, e = V.size(); i != e; ++i) {
1078  if (!V[i]->isNullValue())
1079  isZero = false;
1080  if (!isa<UndefValue>(V[i]))
1081  isUndef = false;
1082  }
1083  }
1084  }
1085  if (isZero)
1086  return ConstantAggregateZero::get(ST);
1087  if (isUndef)
1088  return UndefValue::get(ST);
1089 
1090  return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1091 }
1092 
1093 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1094  : ConstantAggregate(T, ConstantVectorVal, V) {
1095  assert(V.size() == T->getNumElements() &&
1096  "Invalid initializer for constant vector");
1097 }
1098 
1099 // ConstantVector accessors.
1101  if (Constant *C = getImpl(V))
1102  return C;
1103  VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1104  return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1105 }
1106 
1108  assert(!V.empty() && "Vectors can't be empty");
1109  VectorType *T = VectorType::get(V.front()->getType(), V.size());
1110 
1111  // If this is an all-undef or all-zero vector, return a
1112  // ConstantAggregateZero or UndefValue.
1113  Constant *C = V[0];
1114  bool isZero = C->isNullValue();
1115  bool isUndef = isa<UndefValue>(C);
1116 
1117  if (isZero || isUndef) {
1118  for (unsigned i = 1, e = V.size(); i != e; ++i)
1119  if (V[i] != C) {
1120  isZero = isUndef = false;
1121  break;
1122  }
1123  }
1124 
1125  if (isZero)
1126  return ConstantAggregateZero::get(T);
1127  if (isUndef)
1128  return UndefValue::get(T);
1129 
1130  // Check to see if all of the elements are ConstantFP or ConstantInt and if
1131  // the element type is compatible with ConstantDataVector. If so, use it.
1133  return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1134 
1135  // Otherwise, the element type isn't compatible with ConstantDataVector, or
1136  // the operand list contains a ConstantExpr or something else strange.
1137  return nullptr;
1138 }
1139 
1141  // If this splat is compatible with ConstantDataVector, use it instead of
1142  // ConstantVector.
1143  if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1145  return ConstantDataVector::getSplat(NumElts, V);
1146 
1147  SmallVector<Constant*, 32> Elts(NumElts, V);
1148  return get(Elts);
1149 }
1150 
1152  LLVMContextImpl *pImpl = Context.pImpl;
1153  if (!pImpl->TheNoneToken)
1154  pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1155  return pImpl->TheNoneToken.get();
1156 }
1157 
1158 /// Remove the constant from the constant table.
1159 void ConstantTokenNone::destroyConstantImpl() {
1160  llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1161 }
1162 
1163 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1164 // can't be inline because we don't want to #include Instruction.h into
1165 // Constant.h
1166 bool ConstantExpr::isCast() const {
1167  return Instruction::isCast(getOpcode());
1168 }
1169 
1171  return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1172 }
1173 
1175  if (getOpcode() != Instruction::GetElementPtr) return false;
1176 
1177  gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1178  User::const_op_iterator OI = std::next(this->op_begin());
1179 
1180  // The remaining indices may be compile-time known integers within the bounds
1181  // of the corresponding notional static array types.
1182  for (; GEPI != E; ++GEPI, ++OI) {
1183  if (isa<UndefValue>(*OI))
1184  continue;
1185  auto *CI = dyn_cast<ConstantInt>(*OI);
1186  if (!CI || (GEPI.isBoundedSequential() &&
1187  (CI->getValue().getActiveBits() > 64 ||
1188  CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1189  return false;
1190  }
1191 
1192  // All the indices checked out.
1193  return true;
1194 }
1195 
1197  return getOpcode() == Instruction::ExtractValue ||
1198  getOpcode() == Instruction::InsertValue;
1199 }
1200 
1202  if (const ExtractValueConstantExpr *EVCE =
1203  dyn_cast<ExtractValueConstantExpr>(this))
1204  return EVCE->Indices;
1205 
1206  return cast<InsertValueConstantExpr>(this)->Indices;
1207 }
1208 
1209 unsigned ConstantExpr::getPredicate() const {
1210  return cast<CompareConstantExpr>(this)->predicate;
1211 }
1212 
1213 Constant *
1215  assert(Op->getType() == getOperand(OpNo)->getType() &&
1216  "Replacing operand with value of different type!");
1217  if (getOperand(OpNo) == Op)
1218  return const_cast<ConstantExpr*>(this);
1219 
1221  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1222  NewOps.push_back(i == OpNo ? Op : getOperand(i));
1223 
1224  return getWithOperands(NewOps);
1225 }
1226 
1228  bool OnlyIfReduced, Type *SrcTy) const {
1229  assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1230 
1231  // If no operands changed return self.
1232  if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1233  return const_cast<ConstantExpr*>(this);
1234 
1235  Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1236  switch (getOpcode()) {
1237  case Instruction::Trunc:
1238  case Instruction::ZExt:
1239  case Instruction::SExt:
1240  case Instruction::FPTrunc:
1241  case Instruction::FPExt:
1242  case Instruction::UIToFP:
1243  case Instruction::SIToFP:
1244  case Instruction::FPToUI:
1245  case Instruction::FPToSI:
1246  case Instruction::PtrToInt:
1247  case Instruction::IntToPtr:
1248  case Instruction::BitCast:
1249  case Instruction::AddrSpaceCast:
1250  return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1251  case Instruction::Select:
1252  return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1253  case Instruction::InsertElement:
1254  return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1255  OnlyIfReducedTy);
1256  case Instruction::ExtractElement:
1257  return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1258  case Instruction::InsertValue:
1259  return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1260  OnlyIfReducedTy);
1261  case Instruction::ExtractValue:
1262  return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1263  case Instruction::ShuffleVector:
1264  return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1265  OnlyIfReducedTy);
1266  case Instruction::GetElementPtr: {
1267  auto *GEPO = cast<GEPOperator>(this);
1268  assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1270  SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1271  GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1272  }
1273  case Instruction::ICmp:
1274  case Instruction::FCmp:
1275  return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1276  OnlyIfReducedTy);
1277  default:
1278  assert(getNumOperands() == 2 && "Must be binary operator?");
1279  return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1280  OnlyIfReducedTy);
1281  }
1282 }
1283 
1284 
1285 //===----------------------------------------------------------------------===//
1286 // isValueValidForType implementations
1287 
1288 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1289  unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1290  if (Ty->isIntegerTy(1))
1291  return Val == 0 || Val == 1;
1292  return isUIntN(NumBits, Val);
1293 }
1294 
1295 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1296  unsigned NumBits = Ty->getIntegerBitWidth();
1297  if (Ty->isIntegerTy(1))
1298  return Val == 0 || Val == 1 || Val == -1;
1299  return isIntN(NumBits, Val);
1300 }
1301 
1303  // convert modifies in place, so make a copy.
1304  APFloat Val2 = APFloat(Val);
1305  bool losesInfo;
1306  switch (Ty->getTypeID()) {
1307  default:
1308  return false; // These can't be represented as floating point!
1309 
1310  // FIXME rounding mode needs to be more flexible
1311  case Type::HalfTyID: {
1312  if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1313  return true;
1315  return !losesInfo;
1316  }
1317  case Type::FloatTyID: {
1318  if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1319  return true;
1321  return !losesInfo;
1322  }
1323  case Type::DoubleTyID: {
1324  if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1325  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1326  &Val2.getSemantics() == &APFloat::IEEEdouble())
1327  return true;
1329  return !losesInfo;
1330  }
1331  case Type::X86_FP80TyID:
1332  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1333  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1334  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1336  case Type::FP128TyID:
1337  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1338  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1339  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1340  &Val2.getSemantics() == &APFloat::IEEEquad();
1341  case Type::PPC_FP128TyID:
1342  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1343  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1344  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1345  &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1346  }
1347 }
1348 
1349 
1350 //===----------------------------------------------------------------------===//
1351 // Factory Function Implementation
1352 
1354  assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1355  "Cannot create an aggregate zero of non-aggregate type!");
1356 
1357  std::unique_ptr<ConstantAggregateZero> &Entry =
1358  Ty->getContext().pImpl->CAZConstants[Ty];
1359  if (!Entry)
1360  Entry.reset(new ConstantAggregateZero(Ty));
1361 
1362  return Entry.get();
1363 }
1364 
1365 /// Remove the constant from the constant table.
1366 void ConstantAggregateZero::destroyConstantImpl() {
1367  getContext().pImpl->CAZConstants.erase(getType());
1368 }
1369 
1370 /// Remove the constant from the constant table.
1371 void ConstantArray::destroyConstantImpl() {
1373 }
1374 
1375 
1376 //---- ConstantStruct::get() implementation...
1377 //
1378 
1379 /// Remove the constant from the constant table.
1380 void ConstantStruct::destroyConstantImpl() {
1382 }
1383 
1384 /// Remove the constant from the constant table.
1385 void ConstantVector::destroyConstantImpl() {
1387 }
1388 
1390  assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1391  if (isa<ConstantAggregateZero>(this))
1392  return getNullValue(this->getType()->getVectorElementType());
1393  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1394  return CV->getSplatValue();
1395  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1396  return CV->getSplatValue();
1397  return nullptr;
1398 }
1399 
1401  // Check out first element.
1402  Constant *Elt = getOperand(0);
1403  // Then make sure all remaining elements point to the same value.
1404  for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1405  if (getOperand(I) != Elt)
1406  return nullptr;
1407  return Elt;
1408 }
1409 
1411  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1412  return CI->getValue();
1413  assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1414  const Constant *C = this->getAggregateElement(0U);
1415  assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1416  return cast<ConstantInt>(C)->getValue();
1417 }
1418 
1419 //---- ConstantPointerNull::get() implementation.
1420 //
1421 
1423  std::unique_ptr<ConstantPointerNull> &Entry =
1424  Ty->getContext().pImpl->CPNConstants[Ty];
1425  if (!Entry)
1426  Entry.reset(new ConstantPointerNull(Ty));
1427 
1428  return Entry.get();
1429 }
1430 
1431 /// Remove the constant from the constant table.
1432 void ConstantPointerNull::destroyConstantImpl() {
1433  getContext().pImpl->CPNConstants.erase(getType());
1434 }
1435 
1437  std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1438  if (!Entry)
1439  Entry.reset(new UndefValue(Ty));
1440 
1441  return Entry.get();
1442 }
1443 
1444 /// Remove the constant from the constant table.
1445 void UndefValue::destroyConstantImpl() {
1446  // Free the constant and any dangling references to it.
1447  getContext().pImpl->UVConstants.erase(getType());
1448 }
1449 
1451  assert(BB->getParent() && "Block must have a parent");
1452  return get(BB->getParent(), BB);
1453 }
1454 
1456  BlockAddress *&BA =
1457  F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1458  if (!BA)
1459  BA = new BlockAddress(F, BB);
1460 
1461  assert(BA->getFunction() == F && "Basic block moved between functions");
1462  return BA;
1463 }
1464 
1466 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1467  &Op<0>(), 2) {
1468  setOperand(0, F);
1469  setOperand(1, BB);
1470  BB->AdjustBlockAddressRefCount(1);
1471 }
1472 
1474  if (!BB->hasAddressTaken())
1475  return nullptr;
1476 
1477  const Function *F = BB->getParent();
1478  assert(F && "Block must have a parent");
1479  BlockAddress *BA =
1480  F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1481  assert(BA && "Refcount and block address map disagree!");
1482  return BA;
1483 }
1484 
1485 /// Remove the constant from the constant table.
1486 void BlockAddress::destroyConstantImpl() {
1488  ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1489  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1490 }
1491 
1492 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1493  // This could be replacing either the Basic Block or the Function. In either
1494  // case, we have to remove the map entry.
1495  Function *NewF = getFunction();
1496  BasicBlock *NewBB = getBasicBlock();
1497 
1498  if (From == NewF)
1499  NewF = cast<Function>(To->stripPointerCasts());
1500  else {
1501  assert(From == NewBB && "From does not match any operand");
1502  NewBB = cast<BasicBlock>(To);
1503  }
1504 
1505  // See if the 'new' entry already exists, if not, just update this in place
1506  // and return early.
1507  BlockAddress *&NewBA =
1508  getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1509  if (NewBA)
1510  return NewBA;
1511 
1512  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1513 
1514  // Remove the old entry, this can't cause the map to rehash (just a
1515  // tombstone will get added).
1516  getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1517  getBasicBlock()));
1518  NewBA = this;
1519  setOperand(0, NewF);
1520  setOperand(1, NewBB);
1521  getBasicBlock()->AdjustBlockAddressRefCount(1);
1522 
1523  // If we just want to keep the existing value, then return null.
1524  // Callers know that this means we shouldn't delete this value.
1525  return nullptr;
1526 }
1527 
1528 //---- ConstantExpr::get() implementations.
1529 //
1530 
1531 /// This is a utility function to handle folding of casts and lookup of the
1532 /// cast in the ExprConstants map. It is used by the various get* methods below.
1534  bool OnlyIfReduced = false) {
1535  assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1536  // Fold a few common cases
1537  if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1538  return FC;
1539 
1540  if (OnlyIfReduced)
1541  return nullptr;
1542 
1543  LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1544 
1545  // Look up the constant in the table first to ensure uniqueness.
1546  ConstantExprKeyType Key(opc, C);
1547 
1548  return pImpl->ExprConstants.getOrCreate(Ty, Key);
1549 }
1550 
1552  bool OnlyIfReduced) {
1554  assert(Instruction::isCast(opc) && "opcode out of range");
1555  assert(C && Ty && "Null arguments to getCast");
1556  assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1557 
1558  switch (opc) {
1559  default:
1560  llvm_unreachable("Invalid cast opcode");
1561  case Instruction::Trunc:
1562  return getTrunc(C, Ty, OnlyIfReduced);
1563  case Instruction::ZExt:
1564  return getZExt(C, Ty, OnlyIfReduced);
1565  case Instruction::SExt:
1566  return getSExt(C, Ty, OnlyIfReduced);
1567  case Instruction::FPTrunc:
1568  return getFPTrunc(C, Ty, OnlyIfReduced);
1569  case Instruction::FPExt:
1570  return getFPExtend(C, Ty, OnlyIfReduced);
1571  case Instruction::UIToFP:
1572  return getUIToFP(C, Ty, OnlyIfReduced);
1573  case Instruction::SIToFP:
1574  return getSIToFP(C, Ty, OnlyIfReduced);
1575  case Instruction::FPToUI:
1576  return getFPToUI(C, Ty, OnlyIfReduced);
1577  case Instruction::FPToSI:
1578  return getFPToSI(C, Ty, OnlyIfReduced);
1579  case Instruction::PtrToInt:
1580  return getPtrToInt(C, Ty, OnlyIfReduced);
1581  case Instruction::IntToPtr:
1582  return getIntToPtr(C, Ty, OnlyIfReduced);
1583  case Instruction::BitCast:
1584  return getBitCast(C, Ty, OnlyIfReduced);
1585  case Instruction::AddrSpaceCast:
1586  return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1587  }
1588 }
1589 
1591  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1592  return getBitCast(C, Ty);
1593  return getZExt(C, Ty);
1594 }
1595 
1597  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1598  return getBitCast(C, Ty);
1599  return getSExt(C, Ty);
1600 }
1601 
1603  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1604  return getBitCast(C, Ty);
1605  return getTrunc(C, Ty);
1606 }
1607 
1609  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1610  assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1611  "Invalid cast");
1612 
1613  if (Ty->isIntOrIntVectorTy())
1614  return getPtrToInt(S, Ty);
1615 
1616  unsigned SrcAS = S->getType()->getPointerAddressSpace();
1617  if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1618  return getAddrSpaceCast(S, Ty);
1619 
1620  return getBitCast(S, Ty);
1621 }
1622 
1624  Type *Ty) {
1625  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1626  assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1627 
1629  return getAddrSpaceCast(S, Ty);
1630 
1631  return getBitCast(S, Ty);
1632 }
1633 
1635  assert(C->getType()->isIntOrIntVectorTy() &&
1636  Ty->isIntOrIntVectorTy() && "Invalid cast");
1637  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1638  unsigned DstBits = Ty->getScalarSizeInBits();
1639  Instruction::CastOps opcode =
1640  (SrcBits == DstBits ? Instruction::BitCast :
1641  (SrcBits > DstBits ? Instruction::Trunc :
1642  (isSigned ? Instruction::SExt : Instruction::ZExt)));
1643  return getCast(opcode, C, Ty);
1644 }
1645 
1647  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1648  "Invalid cast");
1649  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1650  unsigned DstBits = Ty->getScalarSizeInBits();
1651  if (SrcBits == DstBits)
1652  return C; // Avoid a useless cast
1653  Instruction::CastOps opcode =
1654  (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1655  return getCast(opcode, C, Ty);
1656 }
1657 
1658 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1659 #ifndef NDEBUG
1660  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1661  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1662 #endif
1663  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1664  assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1665  assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1667  "SrcTy must be larger than DestTy for Trunc!");
1668 
1669  return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1670 }
1671 
1672 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1673 #ifndef NDEBUG
1674  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1675  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1676 #endif
1677  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1678  assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1679  assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1681  "SrcTy must be smaller than DestTy for SExt!");
1682 
1683  return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1684 }
1685 
1686 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1687 #ifndef NDEBUG
1688  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1690 #endif
1691  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1692  assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1693  assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1695  "SrcTy must be smaller than DestTy for ZExt!");
1696 
1697  return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1698 }
1699 
1700 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1701 #ifndef NDEBUG
1702  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1703  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1704 #endif
1705  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1706  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1708  "This is an illegal floating point truncation!");
1709  return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1710 }
1711 
1712 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1713 #ifndef NDEBUG
1714  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1716 #endif
1717  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1718  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1720  "This is an illegal floating point extension!");
1721  return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1722 }
1723 
1724 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1725 #ifndef NDEBUG
1726  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1727  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1728 #endif
1729  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1731  "This is an illegal uint to floating point cast!");
1732  return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1733 }
1734 
1735 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1736 #ifndef NDEBUG
1737  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1738  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1739 #endif
1740  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1742  "This is an illegal sint to floating point cast!");
1743  return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1744 }
1745 
1746 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1747 #ifndef NDEBUG
1748  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1749  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1750 #endif
1751  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1753  "This is an illegal floating point to uint cast!");
1754  return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1755 }
1756 
1757 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1758 #ifndef NDEBUG
1759  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1760  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1761 #endif
1762  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1764  "This is an illegal floating point to sint cast!");
1765  return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1766 }
1767 
1769  bool OnlyIfReduced) {
1770  assert(C->getType()->isPtrOrPtrVectorTy() &&
1771  "PtrToInt source must be pointer or pointer vector");
1772  assert(DstTy->isIntOrIntVectorTy() &&
1773  "PtrToInt destination must be integer or integer vector");
1774  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1775  if (isa<VectorType>(C->getType()))
1777  "Invalid cast between a different number of vector elements");
1778  return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1779 }
1780 
1782  bool OnlyIfReduced) {
1783  assert(C->getType()->isIntOrIntVectorTy() &&
1784  "IntToPtr source must be integer or integer vector");
1785  assert(DstTy->isPtrOrPtrVectorTy() &&
1786  "IntToPtr destination must be a pointer or pointer vector");
1787  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1788  if (isa<VectorType>(C->getType()))
1790  "Invalid cast between a different number of vector elements");
1791  return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1792 }
1793 
1795  bool OnlyIfReduced) {
1796  assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1797  "Invalid constantexpr bitcast!");
1798 
1799  // It is common to ask for a bitcast of a value to its own type, handle this
1800  // speedily.
1801  if (C->getType() == DstTy) return C;
1802 
1803  return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1804 }
1805 
1807  bool OnlyIfReduced) {
1808  assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1809  "Invalid constantexpr addrspacecast!");
1810 
1811  // Canonicalize addrspacecasts between different pointer types by first
1812  // bitcasting the pointer type and then converting the address space.
1813  PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1814  PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1815  Type *DstElemTy = DstScalarTy->getElementType();
1816  if (SrcScalarTy->getElementType() != DstElemTy) {
1817  Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1818  if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1819  // Handle vectors of pointers.
1820  MidTy = VectorType::get(MidTy, VT->getNumElements());
1821  }
1822  C = getBitCast(C, MidTy);
1823  }
1824  return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1825 }
1826 
1827 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1828  Type *OnlyIfReducedTy) {
1829  // Check the operands for consistency first.
1830  assert(Instruction::isUnaryOp(Opcode) &&
1831  "Invalid opcode in unary constant expression");
1832 
1833 #ifndef NDEBUG
1834  switch (Opcode) {
1835  case Instruction::FNeg:
1836  assert(C->getType()->isFPOrFPVectorTy() &&
1837  "Tried to create a floating-point operation on a "
1838  "non-floating-point type!");
1839  break;
1840  default:
1841  break;
1842  }
1843 #endif
1844 
1845  if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
1846  return FC;
1847 
1848  if (OnlyIfReducedTy == C->getType())
1849  return nullptr;
1850 
1851  Constant *ArgVec[] = { C };
1852  ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1853 
1854  LLVMContextImpl *pImpl = C->getContext().pImpl;
1855  return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1856 }
1857 
1858 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1859  unsigned Flags, Type *OnlyIfReducedTy) {
1860  // Check the operands for consistency first.
1861  assert(Instruction::isBinaryOp(Opcode) &&
1862  "Invalid opcode in binary constant expression");
1863  assert(C1->getType() == C2->getType() &&
1864  "Operand types in binary constant expression should match");
1865 
1866 #ifndef NDEBUG
1867  switch (Opcode) {
1868  case Instruction::Add:
1869  case Instruction::Sub:
1870  case Instruction::Mul:
1871  case Instruction::UDiv:
1872  case Instruction::SDiv:
1873  case Instruction::URem:
1874  case Instruction::SRem:
1875  assert(C1->getType()->isIntOrIntVectorTy() &&
1876  "Tried to create an integer operation on a non-integer type!");
1877  break;
1878  case Instruction::FAdd:
1879  case Instruction::FSub:
1880  case Instruction::FMul:
1881  case Instruction::FDiv:
1882  case Instruction::FRem:
1883  assert(C1->getType()->isFPOrFPVectorTy() &&
1884  "Tried to create a floating-point operation on a "
1885  "non-floating-point type!");
1886  break;
1887  case Instruction::And:
1888  case Instruction::Or:
1889  case Instruction::Xor:
1890  assert(C1->getType()->isIntOrIntVectorTy() &&
1891  "Tried to create a logical operation on a non-integral type!");
1892  break;
1893  case Instruction::Shl:
1894  case Instruction::LShr:
1895  case Instruction::AShr:
1896  assert(C1->getType()->isIntOrIntVectorTy() &&
1897  "Tried to create a shift operation on a non-integer type!");
1898  break;
1899  default:
1900  break;
1901  }
1902 #endif
1903 
1904  if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1905  return FC;
1906 
1907  if (OnlyIfReducedTy == C1->getType())
1908  return nullptr;
1909 
1910  Constant *ArgVec[] = { C1, C2 };
1911  ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1912 
1913  LLVMContextImpl *pImpl = C1->getContext().pImpl;
1914  return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1915 }
1916 
1918  // sizeof is implemented as: (i64) gep (Ty*)null, 1
1919  // Note that a non-inbounds gep is used, as null isn't within any object.
1921  Constant *GEP = getGetElementPtr(
1923  return getPtrToInt(GEP,
1924  Type::getInt64Ty(Ty->getContext()));
1925 }
1926 
1928  // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1929  // Note that a non-inbounds gep is used, as null isn't within any object.
1930  Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1931  Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1934  Constant *Indices[2] = { Zero, One };
1935  Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1936  return getPtrToInt(GEP,
1937  Type::getInt64Ty(Ty->getContext()));
1938 }
1939 
1941  return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1942  FieldNo));
1943 }
1944 
1946  // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1947  // Note that a non-inbounds gep is used, as null isn't within any object.
1948  Constant *GEPIdx[] = {
1950  FieldNo
1951  };
1952  Constant *GEP = getGetElementPtr(
1954  return getPtrToInt(GEP,
1955  Type::getInt64Ty(Ty->getContext()));
1956 }
1957 
1959  Constant *C2, bool OnlyIfReduced) {
1960  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1961 
1962  switch (Predicate) {
1963  default: llvm_unreachable("Invalid CmpInst predicate");
1969  case CmpInst::FCMP_TRUE:
1970  return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1971 
1975  case CmpInst::ICMP_SLE:
1976  return getICmp(Predicate, C1, C2, OnlyIfReduced);
1977  }
1978 }
1979 
1981  Type *OnlyIfReducedTy) {
1982  assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1983 
1984  if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1985  return SC; // Fold common cases
1986 
1987  if (OnlyIfReducedTy == V1->getType())
1988  return nullptr;
1989 
1990  Constant *ArgVec[] = { C, V1, V2 };
1992 
1993  LLVMContextImpl *pImpl = C->getContext().pImpl;
1994  return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1995 }
1996 
1998  ArrayRef<Value *> Idxs, bool InBounds,
1999  Optional<unsigned> InRangeIndex,
2000  Type *OnlyIfReducedTy) {
2001  if (!Ty)
2002  Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2003  else
2004  assert(Ty ==
2005  cast<PointerType>(C->getType()->getScalarType())->getElementType());
2006 
2007  if (Constant *FC =
2008  ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2009  return FC; // Fold a few common cases.
2010 
2011  // Get the result type of the getelementptr!
2012  Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2013  assert(DestTy && "GEP indices invalid!");
2014  unsigned AS = C->getType()->getPointerAddressSpace();
2015  Type *ReqTy = DestTy->getPointerTo(AS);
2016 
2017  unsigned NumVecElts = 0;
2018  if (C->getType()->isVectorTy())
2019  NumVecElts = C->getType()->getVectorNumElements();
2020  else for (auto Idx : Idxs)
2021  if (Idx->getType()->isVectorTy())
2022  NumVecElts = Idx->getType()->getVectorNumElements();
2023 
2024  if (NumVecElts)
2025  ReqTy = VectorType::get(ReqTy, NumVecElts);
2026 
2027  if (OnlyIfReducedTy == ReqTy)
2028  return nullptr;
2029 
2030  // Look up the constant in the table first to ensure uniqueness
2031  std::vector<Constant*> ArgVec;
2032  ArgVec.reserve(1 + Idxs.size());
2033  ArgVec.push_back(C);
2034  for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2035  assert((!Idxs[i]->getType()->isVectorTy() ||
2036  Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
2037  "getelementptr index type missmatch");
2038 
2039  Constant *Idx = cast<Constant>(Idxs[i]);
2040  if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2041  Idx = ConstantVector::getSplat(NumVecElts, Idx);
2042  ArgVec.push_back(Idx);
2043  }
2044 
2045  unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2046  if (InRangeIndex && *InRangeIndex < 63)
2047  SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2048  const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2049  SubClassOptionalData, None, Ty);
2050 
2051  LLVMContextImpl *pImpl = C->getContext().pImpl;
2052  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2053 }
2054 
2056  Constant *RHS, bool OnlyIfReduced) {
2057  assert(LHS->getType() == RHS->getType());
2059  "Invalid ICmp Predicate");
2060 
2061  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2062  return FC; // Fold a few common cases...
2063 
2064  if (OnlyIfReduced)
2065  return nullptr;
2066 
2067  // Look up the constant in the table first to ensure uniqueness
2068  Constant *ArgVec[] = { LHS, RHS };
2069  // Get the key type with both the opcode and predicate
2070  const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2071 
2072  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2073  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2074  ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2075 
2076  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2077  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2078 }
2079 
2081  Constant *RHS, bool OnlyIfReduced) {
2082  assert(LHS->getType() == RHS->getType());
2084  "Invalid FCmp Predicate");
2085 
2086  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2087  return FC; // Fold a few common cases...
2088 
2089  if (OnlyIfReduced)
2090  return nullptr;
2091 
2092  // Look up the constant in the table first to ensure uniqueness
2093  Constant *ArgVec[] = { LHS, RHS };
2094  // Get the key type with both the opcode and predicate
2095  const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2096 
2097  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2098  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2099  ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2100 
2101  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2102  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2103 }
2104 
2106  Type *OnlyIfReducedTy) {
2107  assert(Val->getType()->isVectorTy() &&
2108  "Tried to create extractelement operation on non-vector type!");
2109  assert(Idx->getType()->isIntegerTy() &&
2110  "Extractelement index must be an integer type!");
2111 
2113  return FC; // Fold a few common cases.
2114 
2115  Type *ReqTy = Val->getType()->getVectorElementType();
2116  if (OnlyIfReducedTy == ReqTy)
2117  return nullptr;
2118 
2119  // Look up the constant in the table first to ensure uniqueness
2120  Constant *ArgVec[] = { Val, Idx };
2121  const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2122 
2123  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2124  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2125 }
2126 
2128  Constant *Idx, Type *OnlyIfReducedTy) {
2129  assert(Val->getType()->isVectorTy() &&
2130  "Tried to create insertelement operation on non-vector type!");
2131  assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2132  "Insertelement types must match!");
2133  assert(Idx->getType()->isIntegerTy() &&
2134  "Insertelement index must be i32 type!");
2135 
2136  if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2137  return FC; // Fold a few common cases.
2138 
2139  if (OnlyIfReducedTy == Val->getType())
2140  return nullptr;
2141 
2142  // Look up the constant in the table first to ensure uniqueness
2143  Constant *ArgVec[] = { Val, Elt, Idx };
2144  const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2145 
2146  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2147  return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2148 }
2149 
2151  Constant *Mask, Type *OnlyIfReducedTy) {
2153  "Invalid shuffle vector constant expr operands!");
2154 
2155  if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2156  return FC; // Fold a few common cases.
2157 
2158  unsigned NElts = Mask->getType()->getVectorNumElements();
2159  Type *EltTy = V1->getType()->getVectorElementType();
2160  Type *ShufTy = VectorType::get(EltTy, NElts);
2161 
2162  if (OnlyIfReducedTy == ShufTy)
2163  return nullptr;
2164 
2165  // Look up the constant in the table first to ensure uniqueness
2166  Constant *ArgVec[] = { V1, V2, Mask };
2167  const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2168 
2169  LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2170  return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2171 }
2172 
2174  ArrayRef<unsigned> Idxs,
2175  Type *OnlyIfReducedTy) {
2176  assert(Agg->getType()->isFirstClassType() &&
2177  "Non-first-class type for constant insertvalue expression");
2178 
2180  Idxs) == Val->getType() &&
2181  "insertvalue indices invalid!");
2182  Type *ReqTy = Val->getType();
2183 
2184  if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2185  return FC;
2186 
2187  if (OnlyIfReducedTy == ReqTy)
2188  return nullptr;
2189 
2190  Constant *ArgVec[] = { Agg, Val };
2191  const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2192 
2193  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2194  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2195 }
2196 
2198  Type *OnlyIfReducedTy) {
2199  assert(Agg->getType()->isFirstClassType() &&
2200  "Tried to create extractelement operation on non-first-class type!");
2201 
2202  Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2203  (void)ReqTy;
2204  assert(ReqTy && "extractvalue indices invalid!");
2205 
2206  assert(Agg->getType()->isFirstClassType() &&
2207  "Non-first-class type for constant extractvalue expression");
2209  return FC;
2210 
2211  if (OnlyIfReducedTy == ReqTy)
2212  return nullptr;
2213 
2214  Constant *ArgVec[] = { Agg };
2215  const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2216 
2217  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2218  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2219 }
2220 
2221 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2222  assert(C->getType()->isIntOrIntVectorTy() &&
2223  "Cannot NEG a nonintegral value!");
2224  return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2225  C, HasNUW, HasNSW);
2226 }
2227 
2229  assert(C->getType()->isFPOrFPVectorTy() &&
2230  "Cannot FNEG a non-floating-point value!");
2231  return get(Instruction::FNeg, C);
2232 }
2233 
2235  assert(C->getType()->isIntOrIntVectorTy() &&
2236  "Cannot NOT a nonintegral value!");
2237  return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2238 }
2239 
2241  bool HasNUW, bool HasNSW) {
2242  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2244  return get(Instruction::Add, C1, C2, Flags);
2245 }
2246 
2248  return get(Instruction::FAdd, C1, C2);
2249 }
2250 
2252  bool HasNUW, bool HasNSW) {
2253  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2255  return get(Instruction::Sub, C1, C2, Flags);
2256 }
2257 
2259  return get(Instruction::FSub, C1, C2);
2260 }
2261 
2263  bool HasNUW, bool HasNSW) {
2264  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2266  return get(Instruction::Mul, C1, C2, Flags);
2267 }
2268 
2270  return get(Instruction::FMul, C1, C2);
2271 }
2272 
2274  return get(Instruction::UDiv, C1, C2,
2275  isExact ? PossiblyExactOperator::IsExact : 0);
2276 }
2277 
2279  return get(Instruction::SDiv, C1, C2,
2280  isExact ? PossiblyExactOperator::IsExact : 0);
2281 }
2282 
2284  return get(Instruction::FDiv, C1, C2);
2285 }
2286 
2288  return get(Instruction::URem, C1, C2);
2289 }
2290 
2292  return get(Instruction::SRem, C1, C2);
2293 }
2294 
2296  return get(Instruction::FRem, C1, C2);
2297 }
2298 
2300  return get(Instruction::And, C1, C2);
2301 }
2302 
2304  return get(Instruction::Or, C1, C2);
2305 }
2306 
2308  return get(Instruction::Xor, C1, C2);
2309 }
2310 
2312  bool HasNUW, bool HasNSW) {
2313  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2315  return get(Instruction::Shl, C1, C2, Flags);
2316 }
2317 
2319  return get(Instruction::LShr, C1, C2,
2320  isExact ? PossiblyExactOperator::IsExact : 0);
2321 }
2322 
2324  return get(Instruction::AShr, C1, C2,
2325  isExact ? PossiblyExactOperator::IsExact : 0);
2326 }
2327 
2329  bool AllowRHSConstant) {
2330  assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2331 
2332  // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2333  if (Instruction::isCommutative(Opcode)) {
2334  switch (Opcode) {
2335  case Instruction::Add: // X + 0 = X
2336  case Instruction::Or: // X | 0 = X
2337  case Instruction::Xor: // X ^ 0 = X
2338  return Constant::getNullValue(Ty);
2339  case Instruction::Mul: // X * 1 = X
2340  return ConstantInt::get(Ty, 1);
2341  case Instruction::And: // X & -1 = X
2342  return Constant::getAllOnesValue(Ty);
2343  case Instruction::FAdd: // X + -0.0 = X
2344  // TODO: If the fadd has 'nsz', should we return +0.0?
2345  return ConstantFP::getNegativeZero(Ty);
2346  case Instruction::FMul: // X * 1.0 = X
2347  return ConstantFP::get(Ty, 1.0);
2348  default:
2349  llvm_unreachable("Every commutative binop has an identity constant");
2350  }
2351  }
2352 
2353  // Non-commutative opcodes: AllowRHSConstant must be set.
2354  if (!AllowRHSConstant)
2355  return nullptr;
2356 
2357  switch (Opcode) {
2358  case Instruction::Sub: // X - 0 = X
2359  case Instruction::Shl: // X << 0 = X
2360  case Instruction::LShr: // X >>u 0 = X
2361  case Instruction::AShr: // X >> 0 = X
2362  case Instruction::FSub: // X - 0.0 = X
2363  return Constant::getNullValue(Ty);
2364  case Instruction::SDiv: // X / 1 = X
2365  case Instruction::UDiv: // X /u 1 = X
2366  return ConstantInt::get(Ty, 1);
2367  case Instruction::FDiv: // X / 1.0 = X
2368  return ConstantFP::get(Ty, 1.0);
2369  default:
2370  return nullptr;
2371  }
2372 }
2373 
2375  switch (Opcode) {
2376  default:
2377  // Doesn't have an absorber.
2378  return nullptr;
2379 
2380  case Instruction::Or:
2381  return Constant::getAllOnesValue(Ty);
2382 
2383  case Instruction::And:
2384  case Instruction::Mul:
2385  return Constant::getNullValue(Ty);
2386  }
2387 }
2388 
2389 /// Remove the constant from the constant table.
2390 void ConstantExpr::destroyConstantImpl() {
2391  getType()->getContext().pImpl->ExprConstants.remove(this);
2392 }
2393 
2394 const char *ConstantExpr::getOpcodeName() const {
2396 }
2397 
2398 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2399  Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2400  : ConstantExpr(DestTy, Instruction::GetElementPtr,
2402  (IdxList.size() + 1),
2403  IdxList.size() + 1),
2404  SrcElementTy(SrcElementTy),
2405  ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2406  Op<0>() = C;
2407  Use *OperandList = getOperandList();
2408  for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2409  OperandList[i+1] = IdxList[i];
2410 }
2411 
2413  return SrcElementTy;
2414 }
2415 
2417  return ResElementTy;
2418 }
2419 
2420 //===----------------------------------------------------------------------===//
2421 // ConstantData* implementations
2422 
2424  return getType()->getElementType();
2425 }
2426 
2428  return StringRef(DataElements, getNumElements()*getElementByteSize());
2429 }
2430 
2432  if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2433  if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2434  switch (IT->getBitWidth()) {
2435  case 8:
2436  case 16:
2437  case 32:
2438  case 64:
2439  return true;
2440  default: break;
2441  }
2442  }
2443  return false;
2444 }
2445 
2447  if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2448  return AT->getNumElements();
2449  return getType()->getVectorNumElements();
2450 }
2451 
2452 
2454  return getElementType()->getPrimitiveSizeInBits()/8;
2455 }
2456 
2457 /// Return the start of the specified element.
2458 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2459  assert(Elt < getNumElements() && "Invalid Elt");
2460  return DataElements+Elt*getElementByteSize();
2461 }
2462 
2463 
2464 /// Return true if the array is empty or all zeros.
2465 static bool isAllZeros(StringRef Arr) {
2466  for (char I : Arr)
2467  if (I != 0)
2468  return false;
2469  return true;
2470 }
2471 
2472 /// This is the underlying implementation of all of the
2473 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2474 /// the correct element type. We take the bytes in as a StringRef because
2475 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2477  assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2478  // If the elements are all zero or there are no elements, return a CAZ, which
2479  // is more dense and canonical.
2480  if (isAllZeros(Elements))
2481  return ConstantAggregateZero::get(Ty);
2482 
2483  // Do a lookup to see if we have already formed one of these.
2484  auto &Slot =
2485  *Ty->getContext()
2486  .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2487  .first;
2488 
2489  // The bucket can point to a linked list of different CDS's that have the same
2490  // body but different types. For example, 0,0,0,1 could be a 4 element array
2491  // of i8, or a 1-element array of i32. They'll both end up in the same
2492  /// StringMap bucket, linked up by their Next pointers. Walk the list.
2493  ConstantDataSequential **Entry = &Slot.second;
2494  for (ConstantDataSequential *Node = *Entry; Node;
2495  Entry = &Node->Next, Node = *Entry)
2496  if (Node->getType() == Ty)
2497  return Node;
2498 
2499  // Okay, we didn't get a hit. Create a node of the right class, link it in,
2500  // and return it.
2501  if (isa<ArrayType>(Ty))
2502  return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2503 
2504  assert(isa<VectorType>(Ty));
2505  return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2506 }
2507 
2508 void ConstantDataSequential::destroyConstantImpl() {
2509  // Remove the constant from the StringMap.
2510  StringMap<ConstantDataSequential*> &CDSConstants =
2512 
2514  CDSConstants.find(getRawDataValues());
2515 
2516  assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2517 
2518  ConstantDataSequential **Entry = &Slot->getValue();
2519 
2520  // Remove the entry from the hash table.
2521  if (!(*Entry)->Next) {
2522  // If there is only one value in the bucket (common case) it must be this
2523  // entry, and removing the entry should remove the bucket completely.
2524  assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2525  getContext().pImpl->CDSConstants.erase(Slot);
2526  } else {
2527  // Otherwise, there are multiple entries linked off the bucket, unlink the
2528  // node we care about but keep the bucket around.
2529  for (ConstantDataSequential *Node = *Entry; ;
2530  Entry = &Node->Next, Node = *Entry) {
2531  assert(Node && "Didn't find entry in its uniquing hash table!");
2532  // If we found our entry, unlink it from the list and we're done.
2533  if (Node == this) {
2534  *Entry = Node->Next;
2535  break;
2536  }
2537  }
2538  }
2539 
2540  // If we were part of a list, make sure that we don't delete the list that is
2541  // still owned by the uniquing map.
2542  Next = nullptr;
2543 }
2544 
2545 /// getFP() constructors - Return a constant with array type with an element
2546 /// count and element type of float with precision matching the number of
2547 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2548 /// double for 64bits) Note that this can return a ConstantAggregateZero
2549 /// object.
2551  ArrayRef<uint16_t> Elts) {
2552  Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2553  const char *Data = reinterpret_cast<const char *>(Elts.data());
2554  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2555 }
2557  ArrayRef<uint32_t> Elts) {
2558  Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2559  const char *Data = reinterpret_cast<const char *>(Elts.data());
2560  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2561 }
2563  ArrayRef<uint64_t> Elts) {
2564  Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2565  const char *Data = reinterpret_cast<const char *>(Elts.data());
2566  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2567 }
2568 
2570  StringRef Str, bool AddNull) {
2571  if (!AddNull) {
2572  const uint8_t *Data = Str.bytes_begin();
2573  return get(Context, makeArrayRef(Data, Str.size()));
2574  }
2575 
2576  SmallVector<uint8_t, 64> ElementVals;
2577  ElementVals.append(Str.begin(), Str.end());
2578  ElementVals.push_back(0);
2579  return get(Context, ElementVals);
2580 }
2581 
2582 /// get() constructors - Return a constant with vector type with an element
2583 /// count and element type matching the ArrayRef passed in. Note that this
2584 /// can return a ConstantAggregateZero object.
2586  Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2587  const char *Data = reinterpret_cast<const char *>(Elts.data());
2588  return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2589 }
2591  Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2592  const char *Data = reinterpret_cast<const char *>(Elts.data());
2593  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2594 }
2596  Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2597  const char *Data = reinterpret_cast<const char *>(Elts.data());
2598  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2599 }
2601  Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2602  const char *Data = reinterpret_cast<const char *>(Elts.data());
2603  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2604 }
2606  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2607  const char *Data = reinterpret_cast<const char *>(Elts.data());
2608  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2609 }
2611  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2612  const char *Data = reinterpret_cast<const char *>(Elts.data());
2613  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2614 }
2615 
2616 /// getFP() constructors - Return a constant with vector type with an element
2617 /// count and element type of float with the precision matching the number of
2618 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2619 /// double for 64bits) Note that this can return a ConstantAggregateZero
2620 /// object.
2622  ArrayRef<uint16_t> Elts) {
2623  Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2624  const char *Data = reinterpret_cast<const char *>(Elts.data());
2625  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2626 }
2628  ArrayRef<uint32_t> Elts) {
2629  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2630  const char *Data = reinterpret_cast<const char *>(Elts.data());
2631  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2632 }
2634  ArrayRef<uint64_t> Elts) {
2635  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2636  const char *Data = reinterpret_cast<const char *>(Elts.data());
2637  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2638 }
2639 
2641  assert(isElementTypeCompatible(V->getType()) &&
2642  "Element type not compatible with ConstantData");
2643  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2644  if (CI->getType()->isIntegerTy(8)) {
2645  SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2646  return get(V->getContext(), Elts);
2647  }
2648  if (CI->getType()->isIntegerTy(16)) {
2649  SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2650  return get(V->getContext(), Elts);
2651  }
2652  if (CI->getType()->isIntegerTy(32)) {
2653  SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2654  return get(V->getContext(), Elts);
2655  }
2656  assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2657  SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2658  return get(V->getContext(), Elts);
2659  }
2660 
2661  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2662  if (CFP->getType()->isHalfTy()) {
2664  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2665  return getFP(V->getContext(), Elts);
2666  }
2667  if (CFP->getType()->isFloatTy()) {
2669  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2670  return getFP(V->getContext(), Elts);
2671  }
2672  if (CFP->getType()->isDoubleTy()) {
2674  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2675  return getFP(V->getContext(), Elts);
2676  }
2677  }
2678  return ConstantVector::getSplat(NumElts, V);
2679 }
2680 
2681 
2682 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2683  assert(isa<IntegerType>(getElementType()) &&
2684  "Accessor can only be used when element is an integer");
2685  const char *EltPtr = getElementPointer(Elt);
2686 
2687  // The data is stored in host byte order, make sure to cast back to the right
2688  // type to load with the right endianness.
2689  switch (getElementType()->getIntegerBitWidth()) {
2690  default: llvm_unreachable("Invalid bitwidth for CDS");
2691  case 8:
2692  return *reinterpret_cast<const uint8_t *>(EltPtr);
2693  case 16:
2694  return *reinterpret_cast<const uint16_t *>(EltPtr);
2695  case 32:
2696  return *reinterpret_cast<const uint32_t *>(EltPtr);
2697  case 64:
2698  return *reinterpret_cast<const uint64_t *>(EltPtr);
2699  }
2700 }
2701 
2703  assert(isa<IntegerType>(getElementType()) &&
2704  "Accessor can only be used when element is an integer");
2705  const char *EltPtr = getElementPointer(Elt);
2706 
2707  // The data is stored in host byte order, make sure to cast back to the right
2708  // type to load with the right endianness.
2709  switch (getElementType()->getIntegerBitWidth()) {
2710  default: llvm_unreachable("Invalid bitwidth for CDS");
2711  case 8: {
2712  auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2713  return APInt(8, EltVal);
2714  }
2715  case 16: {
2716  auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2717  return APInt(16, EltVal);
2718  }
2719  case 32: {
2720  auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2721  return APInt(32, EltVal);
2722  }
2723  case 64: {
2724  auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2725  return APInt(64, EltVal);
2726  }
2727  }
2728 }
2729 
2731  const char *EltPtr = getElementPointer(Elt);
2732 
2733  switch (getElementType()->getTypeID()) {
2734  default:
2735  llvm_unreachable("Accessor can only be used when element is float/double!");
2736  case Type::HalfTyID: {
2737  auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2738  return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2739  }
2740  case Type::FloatTyID: {
2741  auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2742  return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2743  }
2744  case Type::DoubleTyID: {
2745  auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2746  return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2747  }
2748  }
2749 }
2750 
2752  assert(getElementType()->isFloatTy() &&
2753  "Accessor can only be used when element is a 'float'");
2754  return *reinterpret_cast<const float *>(getElementPointer(Elt));
2755 }
2756 
2758  assert(getElementType()->isDoubleTy() &&
2759  "Accessor can only be used when element is a 'float'");
2760  return *reinterpret_cast<const double *>(getElementPointer(Elt));
2761 }
2762 
2764  if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2765  getElementType()->isDoubleTy())
2766  return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2767 
2768  return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2769 }
2770 
2771 bool ConstantDataSequential::isString(unsigned CharSize) const {
2772  return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2773 }
2774 
2776  if (!isString())
2777  return false;
2778 
2779  StringRef Str = getAsString();
2780 
2781  // The last value must be nul.
2782  if (Str.back() != 0) return false;
2783 
2784  // Other elements must be non-nul.
2785  return Str.drop_back().find(0) == StringRef::npos;
2786 }
2787 
2789  const char *Base = getRawDataValues().data();
2790 
2791  // Compare elements 1+ to the 0'th element.
2792  unsigned EltSize = getElementByteSize();
2793  for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2794  if (memcmp(Base, Base+i*EltSize, EltSize))
2795  return false;
2796 
2797  return true;
2798 }
2799 
2801  // If they're all the same, return the 0th one as a representative.
2802  return isSplat() ? getElementAsConstant(0) : nullptr;
2803 }
2804 
2805 //===----------------------------------------------------------------------===//
2806 // handleOperandChange implementations
2807 
2808 /// Update this constant array to change uses of
2809 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2810 /// etc.
2811 ///
2812 /// Note that we intentionally replace all uses of From with To here. Consider
2813 /// a large array that uses 'From' 1000 times. By handling this case all here,
2814 /// ConstantArray::handleOperandChange is only invoked once, and that
2815 /// single invocation handles all 1000 uses. Handling them one at a time would
2816 /// work, but would be really slow because it would have to unique each updated
2817 /// array instance.
2818 ///
2820  Value *Replacement = nullptr;
2821  switch (getValueID()) {
2822  default:
2823  llvm_unreachable("Not a constant!");
2824 #define HANDLE_CONSTANT(Name) \
2825  case Value::Name##Val: \
2826  Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2827  break;
2828 #include "llvm/IR/Value.def"
2829  }
2830 
2831  // If handleOperandChangeImpl returned nullptr, then it handled
2832  // replacing itself and we don't want to delete or replace anything else here.
2833  if (!Replacement)
2834  return;
2835 
2836  // I do need to replace this with an existing value.
2837  assert(Replacement != this && "I didn't contain From!");
2838 
2839  // Everyone using this now uses the replacement.
2840  replaceAllUsesWith(Replacement);
2841 
2842  // Delete the old constant!
2843  destroyConstant();
2844 }
2845 
2846 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2847  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2848  Constant *ToC = cast<Constant>(To);
2849 
2851  Values.reserve(getNumOperands()); // Build replacement array.
2852 
2853  // Fill values with the modified operands of the constant array. Also,
2854  // compute whether this turns into an all-zeros array.
2855  unsigned NumUpdated = 0;
2856 
2857  // Keep track of whether all the values in the array are "ToC".
2858  bool AllSame = true;
2859  Use *OperandList = getOperandList();
2860  unsigned OperandNo = 0;
2861  for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2862  Constant *Val = cast<Constant>(O->get());
2863  if (Val == From) {
2864  OperandNo = (O - OperandList);
2865  Val = ToC;
2866  ++NumUpdated;
2867  }
2868  Values.push_back(Val);
2869  AllSame &= Val == ToC;
2870  }
2871 
2872  if (AllSame && ToC->isNullValue())
2874 
2875  if (AllSame && isa<UndefValue>(ToC))
2876  return UndefValue::get(getType());
2877 
2878  // Check for any other type of constant-folding.
2879  if (Constant *C = getImpl(getType(), Values))
2880  return C;
2881 
2882  // Update to the new value.
2884  Values, this, From, ToC, NumUpdated, OperandNo);
2885 }
2886 
2887 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2888  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2889  Constant *ToC = cast<Constant>(To);
2890 
2891  Use *OperandList = getOperandList();
2892 
2894  Values.reserve(getNumOperands()); // Build replacement struct.
2895 
2896  // Fill values with the modified operands of the constant struct. Also,
2897  // compute whether this turns into an all-zeros struct.
2898  unsigned NumUpdated = 0;
2899  bool AllSame = true;
2900  unsigned OperandNo = 0;
2901  for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2902  Constant *Val = cast<Constant>(O->get());
2903  if (Val == From) {
2904  OperandNo = (O - OperandList);
2905  Val = ToC;
2906  ++NumUpdated;
2907  }
2908  Values.push_back(Val);
2909  AllSame &= Val == ToC;
2910  }
2911 
2912  if (AllSame && ToC->isNullValue())
2914 
2915  if (AllSame && isa<UndefValue>(ToC))
2916  return UndefValue::get(getType());
2917 
2918  // Update to the new value.
2920  Values, this, From, ToC, NumUpdated, OperandNo);
2921 }
2922 
2923 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2924  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2925  Constant *ToC = cast<Constant>(To);
2926 
2928  Values.reserve(getNumOperands()); // Build replacement array...
2929  unsigned NumUpdated = 0;
2930  unsigned OperandNo = 0;
2931  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2932  Constant *Val = getOperand(i);
2933  if (Val == From) {
2934  OperandNo = i;
2935  ++NumUpdated;
2936  Val = ToC;
2937  }
2938  Values.push_back(Val);
2939  }
2940 
2941  if (Constant *C = getImpl(Values))
2942  return C;
2943 
2944  // Update to the new value.
2946  Values, this, From, ToC, NumUpdated, OperandNo);
2947 }
2948 
2949 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2950  assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2951  Constant *To = cast<Constant>(ToV);
2952 
2954  unsigned NumUpdated = 0;
2955  unsigned OperandNo = 0;
2956  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2957  Constant *Op = getOperand(i);
2958  if (Op == From) {
2959  OperandNo = i;
2960  ++NumUpdated;
2961  Op = To;
2962  }
2963  NewOps.push_back(Op);
2964  }
2965  assert(NumUpdated && "I didn't contain From!");
2966 
2967  if (Constant *C = getWithOperands(NewOps, getType(), true))
2968  return C;
2969 
2970  // Update to the new value.
2971  return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2972  NewOps, this, From, To, NumUpdated, OperandNo);
2973 }
2974 
2976  SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2977  ArrayRef<Value*> Ops(ValueOperands);
2978 
2979  switch (getOpcode()) {
2980  case Instruction::Trunc:
2981  case Instruction::ZExt:
2982  case Instruction::SExt:
2983  case Instruction::FPTrunc:
2984  case Instruction::FPExt:
2985  case Instruction::UIToFP:
2986  case Instruction::SIToFP:
2987  case Instruction::FPToUI:
2988  case Instruction::FPToSI:
2989  case Instruction::PtrToInt:
2990  case Instruction::IntToPtr:
2991  case Instruction::BitCast:
2992  case Instruction::AddrSpaceCast:
2994  Ops[0], getType());
2995  case Instruction::Select:
2996  return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2997  case Instruction::InsertElement:
2998  return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2999  case Instruction::ExtractElement:
3000  return ExtractElementInst::Create(Ops[0], Ops[1]);
3001  case Instruction::InsertValue:
3002  return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3003  case Instruction::ExtractValue:
3004  return ExtractValueInst::Create(Ops[0], getIndices());
3005  case Instruction::ShuffleVector:
3006  return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3007 
3008  case Instruction::GetElementPtr: {
3009  const auto *GO = cast<GEPOperator>(this);
3010  if (GO->isInBounds())
3011  return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3012  Ops[0], Ops.slice(1));
3013  return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3014  Ops.slice(1));
3015  }
3016  case Instruction::ICmp:
3017  case Instruction::FCmp:
3019  (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3020  case Instruction::FNeg:
3022  default:
3023  assert(getNumOperands() == 2 && "Must be binary operator?");
3024  BinaryOperator *BO =
3026  Ops[0], Ops[1]);
3027  if (isa<OverflowingBinaryOperator>(BO)) {
3032  }
3033  if (isa<PossiblyExactOperator>(BO))
3035  return BO;
3036  }
3037 }
bool isFPPredicate() const
Definition: InstrTypes.h:824
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:151
static Constant * getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1700
Type * getVectorElementType() const
Definition: Type.h:371
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:1288
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:761
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition: APFloat.h:885
uint64_t CallInst * C
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:161
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:606
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:2569
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt)
Definition: Constants.cpp:923
static Type * getDoubleTy(LLVMContext &C)
Definition: Type.cpp:164
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:99
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:172
static Constant * getFAdd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2247
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1209
unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:878
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:463
LLVMContext & Context
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:240
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:1623
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index&#39;s element.
Definition: Constants.cpp:2763
DenseMap< std::pair< const Function *, const BasicBlock * >, BlockAddress * > BlockAddresses
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1153
iterator begin() const
Definition: ArrayRef.h:136
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:829
2: 32-bit floating point type
Definition: Type.h:58
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry...
Definition: Constants.cpp:498
bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things...
Definition: Constants.cpp:486
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:345
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1806
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1353
ExtractValueConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to i...
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:2702
bool isFP128Ty() const
Return true if this is &#39;fp128&#39;.
Definition: Type.h:155
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:901
Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:632
gep_type_iterator gep_type_end(const User *GEP)
unsigned less or equal
Definition: InstrTypes.h:758
unsigned less than
Definition: InstrTypes.h:757
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1781
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2453
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2105
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:738
iterator find(StringRef Key)
Definition: StringMap.h:332
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:1533
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:732
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:748
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:1410
13: Structures
Definition: Type.h:72
F(f)
4: 80-bit floating point type (X87)
Definition: Type.h:60
const fltSemantics & getSemantics() const
Definition: APFloat.h:1165
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:580
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:865
1: 16-bit floating point type
Definition: Type.h:57
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:301
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:1958
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2251
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
15: Pointers
Definition: Type.h:74
void reserve(size_type N)
Definition: SmallVector.h:369
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:174
unsigned getPredicate() const
Return the ICMP or FCMP predicate value.
Definition: Constants.cpp:1209
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:158
op_iterator op_begin()
Definition: User.h:229
static Type * getX86_FP80Ty(LLVMContext &C)
Definition: Type.cpp:167
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1004
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
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:866
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2127
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:274
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2240
static Constant * getFMul(Constant *C1, Constant *C2)
Definition: Constants.cpp:2269
static Constant * getFPSequenceIfElementsMatch(ArrayRef< Constant *> V)
Definition: Constants.cpp:944
Function * getFunction() const
Definition: Constants.h:865
ConstantClass * replaceOperandsInPlace(ArrayRef< Constant *> Operands, ConstantClass *CP, Value *From, Constant *To, unsigned NumUpdated=0, unsigned OperandNo=~0u)
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:743
The address of a basic block.
Definition: Constants.h:839
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:742
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1634
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
static Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static Type * getFloatTy(LLVMContext &C)
Definition: Type.cpp:163
static Constant * getNegativeZero(Type *Ty)
Definition: Constants.cpp:780
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:450
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:161
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1285
static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE=false)
Returns a float which is bitcasted from an all one value int.
Definition: APFloat.cpp:4508
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2427
Class to represent struct types.
Definition: DerivedTypes.h:233
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2318
Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:654
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:739
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1672
Instruction * getAsInstruction()
Returns an Instruction which implements the same operation as this ConstantExpr.
Definition: Constants.cpp:2975
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:899
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Definition: DerivedTypes.h:393
void remove(ConstantClass *CP)
Remove this constant from the map.
static Type * getPPC_FP128Ty(LLVMContext &C)
Definition: Type.cpp:169
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:341
All zero aggregate value.
Definition: Constants.h:340
static Constant * getSequenceIfElementsMatch(Constant *C, ArrayRef< Constant *> V)
Definition: Constants.cpp:957
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.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1686
Key
PAL metadata keys.
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:1917
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool canTrap() const
Return true if evaluation of this constant could trap.
Definition: Constants.cpp:442
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
Definition: Type.h:243
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4483
static Constant * getFPCast(Constant *C, Type *Ty)
Create a FPExt, Bitcast or FPTrunc for fp -> fp casts.
Definition: Constants.cpp:1646
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:573
static Constant * getAShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2323
Class to represent array types.
Definition: DerivedTypes.h:403
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:1980
std::unique_ptr< ConstantTokenNone > TheNoneToken
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
bool isGEPWithNoNotionalOverIndexing() const
Return true if this is a getelementptr expression and all the index operands are compile-time known i...
Definition: Constants.cpp:1174
ArrayConstantsTy ArrayConstants
bool isFiniteNonZeroFP() const
Return true if this is a finite and non-zero floating-point scalar constant or a vector constant with...
Definition: Constants.cpp:201
Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue instruction with the spe...
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:202
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:158
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2273
static Function * getFunction(Constant *C)
Definition: Evaluator.cpp:258
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:66
Constant(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps)
Definition: Constant.h:43
bool isMinSignedValue() const
Return true if the value is the smallest signed value.
Definition: Constants.cpp:151
static Constant * getFDiv(Constant *C1, Constant *C2)
Definition: Constants.cpp:2283
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition: APFloat.h:874
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2423
Value * getOperand(unsigned i) const
Definition: User.h:169
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:558
Class to represent pointers.
Definition: DerivedTypes.h:544
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:344
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:303
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:64
11: Arbitrary bit width integers
Definition: Type.h:70
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1794
static bool removeDeadUsersOfConstant(const Constant *C)
If the specified constantexpr is dead, remove it.
Definition: Constants.cpp:543
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:146
bool isThreadDependent() const
Return true if the value can vary between threads.
Definition: Constants.cpp:472
DenseMap< PointerType *, std::unique_ptr< ConstantPointerNull > > CPNConstants
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2173
static bool ConstHasGlobalValuePredicate(const Constant *C, bool(*Predicate)(const GlobalValue *))
Check if C contains a GlobalValue for which Predicate is true.
Definition: Constants.cpp:449
Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, Constant *Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and indices...
static Constant * getFNeg(Constant *C)
Definition: Constants.cpp:2228
static Constant * getFRem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2295
const Use * getOperandList() const
Definition: User.h:162
static Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
Definition: Constants.cpp:2476
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1422
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:689
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value, return that value.
Definition: Constants.cpp:2800
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with array type with an element count and element type of fl...
Definition: Constants.cpp:2550
A constant token which is empty.
Definition: Constants.h:817
Constant * getWithOperandReplaced(unsigned OpNo, Constant *Op) const
Return a constant expression identical to this one, but with the specified operand set to the specifi...
Definition: Constants.cpp:1214
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1455
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
const char * getOpcodeName() const
Definition: Instruction.h:127
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
10: Tokens
Definition: Type.h:66
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with vector type with an element count and element type of f...
Definition: Constants.cpp:2621
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2299
bool hasIndices() const
Return true if this is an insertvalue or extractvalue expression, and the getIndices() method may be ...
Definition: Constants.cpp:1196
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
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:370
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1596
float getElementAsFloat(unsigned i) const
If this is an sequential container of floats, return the specified element as a float.
Definition: Constants.cpp:2751
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
Definition: Constants.cpp:479
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2150
op_iterator op_end()
Definition: User.h:231
const char * getOpcodeName() const
Return a string representation for an opcode.
Definition: Constants.cpp:2394
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:143
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
bool isBinaryOp() const
Definition: Instruction.h:130
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2328
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1065
op_range operands()
Definition: User.h:237
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:741
unsigned getStructNumElements() const
Definition: DerivedTypes.h:361
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1302
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:572
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:2055
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:164
Class to represent integer types.
Definition: DerivedTypes.h:40
Constant Vector Declarations.
Definition: Constants.h:499
bool isNegativeZeroValue() const
Return true if the value is what would be returned by getZeroValueForNegation.
Definition: Constants.cpp:38
static Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:758
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2640
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2234
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:328
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:749
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
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:2431
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:397
static const fltSemantics * TypeToFloatSemantics(Type *Ty)
Definition: Constants.cpp:690
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1436
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition: Value.cpp:535
bool isCast() const
Definition: Instruction.h:133
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:141
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
Constant * getWithOperands(ArrayRef< Constant *> Ops) const
This returns the current constant expression with the operands replaced with the specified values...
Definition: Constants.h:1229
Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Constant * getSplatValue() const
If this is a splat vector constant, meaning that all of the elements have the same value...
Definition: Constants.cpp:1389
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:747
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
VectorConstantsTy VectorConstants
const T * data() const
Definition: ArrayRef.h:145
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition: Value.h:90
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:66
signed greater than
Definition: InstrTypes.h:759
static Type * getFP128Ty(LLVMContext &C)
Definition: Type.cpp:168
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:311
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal) floating-point scalar constant or a vector c...
Definition: Constants.cpp:214
hexagon gen pred
14: Arrays
Definition: Type.h:73
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2080
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:736
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1608
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:391
static bool isUndef(ArrayRef< int > Mask)
static Constant * getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1735
static Type * getHalfTy(LLVMContext &C)
Definition: Type.cpp:162
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:226
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1140
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:239
Type * getSequentialElementType() const
Definition: Type.h:357
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:155
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
Definition: Constants.cpp:2465
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:87
unsigned getNumOperands() const
Definition: User.h:191
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:559
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1173
BlockVerifier::State From
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:152
16: SIMD &#39;packed&#39; format, or other vector type
Definition: Type.h:75
static Constant * getSDiv(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2278
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
bool containsUndefElement() const
Return true if this is a vector constant that includes any undefined elements.
Definition: Constants.cpp:253
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:746
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
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:2682
Module.h This file contains the declarations for the Module class.
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:2775
A constant pointer value that points to null.
Definition: Constants.h:538
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
iterator end() const
Definition: ArrayRef.h:137
signed less than
Definition: InstrTypes.h:761
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
CHAIN = SC CHAIN, Imm128 - System call.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1658
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:643
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.cpp:657
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:706
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:599
ValueTy
Concrete subclass of this.
Definition: Value.h:444
bool isCommutative() const
Return true if the instruction is commutative:
Definition: Instruction.h:488
void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Definition: Constants.cpp:2819
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1473
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:535
bool isIntPredicate() const
Definition: InstrTypes.h:825
signed less or equal
Definition: InstrTypes.h:762
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
Class to represent vector types.
Definition: DerivedTypes.h:427
Class for arbitrary precision integers.
Definition: APInt.h:69
Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value, return that value.
Definition: Constants.cpp:1400
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:904
bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value...
Definition: Constants.cpp:2788
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.
iterator_range< user_iterator > users()
Definition: Value.h:399
static Constant * getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1746
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1551
static char getTypeID(Type *Ty)
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:178
iterator begin() const
Definition: StringRef.h:101
static Constant * getZExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1590
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
Common super class of ArrayType, StructType and VectorType.
Definition: DerivedTypes.h:194
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:152
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:369
bool containsConstantExpression() const
Return true if this is a vector constant that includes any constant expressions.
Definition: Constants.cpp:263
static Constant * getFSub(Constant *C1, Constant *C2)
Definition: Constants.cpp:2258
static Constant * getTruncOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1602
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
static Constant * getIntSequenceIfElementsMatch(ArrayRef< Constant *> V)
Definition: Constants.cpp:931
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:170
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2221
Constant * ConstantFoldCompareInstruction(unsigned short predicate, Constant *C1, Constant *C2)
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&#39;s ...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:549
Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
static Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
Definition: Constants.cpp:747
const unsigned char * bytes_begin() const
Definition: StringRef.h:105
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:927
static const size_t npos
Definition: StringRef.h:50
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:2730
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:97
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static Constant * getOffsetOf(StructType *STy, unsigned FieldNo)
getOffsetOf constant expr - computes the offset of a struct field in a target independent way (Note: ...
Definition: Constants.cpp:1940
unsigned greater or equal
Definition: InstrTypes.h:756
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:609
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
double getElementAsDouble(unsigned i) const
If this is an sequential container of doubles, return the specified element as a double.
Definition: Constants.cpp:2757
const Value * stripPointerCastsNoFollowAliases() const
Strip off pointer casts and all-zero GEPs.
Definition: Value.cpp:544
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1768
#define I(x, y, z)
Definition: MD5.cpp:58
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2303
static Constant * getZeroValueForNegation(Type *Ty)
Floating point negation must be implemented with f(x) = -0.0 - x.
Definition: Constants.cpp:792
Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices...
bool isCompare() const
Return true if this is a compare constant expression.
Definition: Constants.cpp:1170
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:740
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:582
Compile-time customization of User operands.
Definition: User.h:42
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2311
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:371
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Definition: Constants.cpp:1151
ConstantUniqueMap< ConstantExpr > ExprConstants
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:744
Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, bool InBounds, Optional< unsigned > InRangeIndex, ArrayRef< Value *> Idxs)
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:862
ArrayRef< unsigned > getIndices() const
Assert that this is an insertvalue or exactvalue expression and return the list of indices...
Definition: Constants.cpp:1201
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:184
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:125
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
3: 64-bit floating point type
Definition: Type.h:59
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Definition: Instructions.h:935
static Constant * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:769
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:375
static Constant * getSRem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2291
Base class for aggregate constants (with operands).
Definition: Constants.h:389
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:735
StructConstantsTy StructConstants
LLVM Value Representation.
Definition: Value.h:72
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:745
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
LLVM_NODISCARD StringRef drop_back(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the last N elements dropped.
Definition: StringRef.h:628
static Constant * getURem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2287
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:1051
bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
Definition: Constants.cpp:227
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
static Constant * getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1724
static Constant * getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1757
bool isCast() const
Return true if this is a convert constant expression.
Definition: Constants.cpp:1166
ConstantClass * getOrCreate(TypeClass *Ty, ValType V)
Return the specified constant from the map, creating it if necessary.
unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:911
Type * getElementType() const
Definition: DerivedTypes.h:394
bool isExactlyValue(const APFloat &V) const
We don&#39;t rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: Constants.cpp:845
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value.
Definition: Constants.cpp:177
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2197
unsigned greater than
Definition: InstrTypes.h:755
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices...
static bool isSplat(ArrayRef< Value *> VL)
Use & Op()
Definition: User.h:133
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2446
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
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:1927
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2262
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:2585
static LazyValueInfoImpl & getImpl(void *&PImpl, AssumptionCache *AC, const DataLayout *DL, DominatorTree *DT=nullptr)
This lazily constructs the LazyValueInfoImpl.
static bool canTrapImpl(const Constant *C, SmallPtrSetImpl< const ConstantExpr *> &NonTrappingOps)
Definition: Constants.cpp:411
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:392
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1244
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:737
iterator end() const
Definition: StringRef.h:103
static Constant * getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1712
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:895
Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
Definition: Constants.cpp:858
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:149
StringMap< ConstantDataSequential * > CDSConstants
Base class for constants with no operands.
Definition: Constants.h:57
ConstantAggregate(CompositeType *T, ValueTy VT, ArrayRef< Constant *> V)
Definition: Constants.cpp:983
bool isUnaryOp() const
Definition: Instruction.h:129
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
Definition: Constants.cpp:2374
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
bool use_empty() const
Definition: Value.h:322
iterator end()
Definition: StringMap.h:317
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:1100
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:896
Type * getElementType() const
Definition: DerivedTypes.h:563
UndefValue * getSequentialElement() const
If this Undef has array or vector type, return a undef with the right element type.
Definition: Constants.cpp:891
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:734
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:217
signed greater or equal
Definition: InstrTypes.h:760
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
User * user_back()
Definition: Value.h:385
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:220
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:531
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2307
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:61
gep_type_iterator gep_type_begin(const User *GEP)
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:2771
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1827
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null...
user_iterator user_end()
Definition: Value.h:383