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