LLVM  3.7.0
ConstantFolding.cpp
Go to the documentation of this file.
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
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 defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18 
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Operator.h"
37 #include <cerrno>
38 #include <cmath>
39 
40 #ifdef HAVE_FENV_H
41 #include <fenv.h>
42 #endif
43 
44 using namespace llvm;
45 
46 //===----------------------------------------------------------------------===//
47 // Constant Folding internal helper functions
48 //===----------------------------------------------------------------------===//
49 
50 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
51 /// This always returns a non-null constant, but it may be a
52 /// ConstantExpr if unfoldable.
53 static Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
54  // Catch the obvious splat cases.
55  if (C->isNullValue() && !DestTy->isX86_MMXTy())
56  return Constant::getNullValue(DestTy);
57  if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
58  !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
59  return Constant::getAllOnesValue(DestTy);
60 
61  // Handle a vector->integer cast.
62  if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
63  VectorType *VTy = dyn_cast<VectorType>(C->getType());
64  if (!VTy)
65  return ConstantExpr::getBitCast(C, DestTy);
66 
67  unsigned NumSrcElts = VTy->getNumElements();
68  Type *SrcEltTy = VTy->getElementType();
69 
70  // If the vector is a vector of floating point, convert it to vector of int
71  // to simplify things.
72  if (SrcEltTy->isFloatingPointTy()) {
73  unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
74  Type *SrcIVTy =
75  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
76  // Ask IR to do the conversion now that #elts line up.
77  C = ConstantExpr::getBitCast(C, SrcIVTy);
78  }
79 
81  if (!CDV)
82  return ConstantExpr::getBitCast(C, DestTy);
83 
84  // Now that we know that the input value is a vector of integers, just shift
85  // and insert them into our result.
86  unsigned BitShift = DL.getTypeAllocSizeInBits(SrcEltTy);
87  APInt Result(IT->getBitWidth(), 0);
88  for (unsigned i = 0; i != NumSrcElts; ++i) {
89  Result <<= BitShift;
90  if (DL.isLittleEndian())
91  Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
92  else
93  Result |= CDV->getElementAsInteger(i);
94  }
95 
96  return ConstantInt::get(IT, Result);
97  }
98 
99  // The code below only handles casts to vectors currently.
100  VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
101  if (!DestVTy)
102  return ConstantExpr::getBitCast(C, DestTy);
103 
104  // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
105  // vector so the code below can handle it uniformly.
106  if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
107  Constant *Ops = C; // don't take the address of C!
108  return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
109  }
110 
111  // If this is a bitcast from constant vector -> vector, fold it.
112  if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
113  return ConstantExpr::getBitCast(C, DestTy);
114 
115  // If the element types match, IR can fold it.
116  unsigned NumDstElt = DestVTy->getNumElements();
117  unsigned NumSrcElt = C->getType()->getVectorNumElements();
118  if (NumDstElt == NumSrcElt)
119  return ConstantExpr::getBitCast(C, DestTy);
120 
121  Type *SrcEltTy = C->getType()->getVectorElementType();
122  Type *DstEltTy = DestVTy->getElementType();
123 
124  // Otherwise, we're changing the number of elements in a vector, which
125  // requires endianness information to do the right thing. For example,
126  // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
127  // folds to (little endian):
128  // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
129  // and to (big endian):
130  // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
131 
132  // First thing is first. We only want to think about integer here, so if
133  // we have something in FP form, recast it as integer.
134  if (DstEltTy->isFloatingPointTy()) {
135  // Fold to an vector of integers with same size as our FP type.
136  unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
137  Type *DestIVTy =
138  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
139  // Recursively handle this integer conversion, if possible.
140  C = FoldBitCast(C, DestIVTy, DL);
141 
142  // Finally, IR can handle this now that #elts line up.
143  return ConstantExpr::getBitCast(C, DestTy);
144  }
145 
146  // Okay, we know the destination is integer, if the input is FP, convert
147  // it to integer first.
148  if (SrcEltTy->isFloatingPointTy()) {
149  unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
150  Type *SrcIVTy =
151  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
152  // Ask IR to do the conversion now that #elts line up.
153  C = ConstantExpr::getBitCast(C, SrcIVTy);
154  // If IR wasn't able to fold it, bail out.
155  if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
156  !isa<ConstantDataVector>(C))
157  return C;
158  }
159 
160  // Now we know that the input and output vectors are both integer vectors
161  // of the same size, and that their #elements is not the same. Do the
162  // conversion here, which depends on whether the input or output has
163  // more elements.
164  bool isLittleEndian = DL.isLittleEndian();
165 
167  if (NumDstElt < NumSrcElt) {
168  // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
169  Constant *Zero = Constant::getNullValue(DstEltTy);
170  unsigned Ratio = NumSrcElt/NumDstElt;
171  unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
172  unsigned SrcElt = 0;
173  for (unsigned i = 0; i != NumDstElt; ++i) {
174  // Build each element of the result.
175  Constant *Elt = Zero;
176  unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
177  for (unsigned j = 0; j != Ratio; ++j) {
178  Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
179  if (!Src) // Reject constantexpr elements.
180  return ConstantExpr::getBitCast(C, DestTy);
181 
182  // Zero extend the element to the right size.
183  Src = ConstantExpr::getZExt(Src, Elt->getType());
184 
185  // Shift it to the right place, depending on endianness.
186  Src = ConstantExpr::getShl(Src,
187  ConstantInt::get(Src->getType(), ShiftAmt));
188  ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
189 
190  // Mix it in.
191  Elt = ConstantExpr::getOr(Elt, Src);
192  }
193  Result.push_back(Elt);
194  }
195  return ConstantVector::get(Result);
196  }
197 
198  // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
199  unsigned Ratio = NumDstElt/NumSrcElt;
200  unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
201 
202  // Loop over each source value, expanding into multiple results.
203  for (unsigned i = 0; i != NumSrcElt; ++i) {
205  if (!Src) // Reject constantexpr elements.
206  return ConstantExpr::getBitCast(C, DestTy);
207 
208  unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
209  for (unsigned j = 0; j != Ratio; ++j) {
210  // Shift the piece of the value into the right place, depending on
211  // endianness.
212  Constant *Elt = ConstantExpr::getLShr(Src,
213  ConstantInt::get(Src->getType(), ShiftAmt));
214  ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
215 
216  // Truncate the element to an integer with the same pointer size and
217  // convert the element back to a pointer using a inttoptr.
218  if (DstEltTy->isPointerTy()) {
219  IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
220  Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
221  Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
222  continue;
223  }
224 
225  // Truncate and remember this piece.
226  Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
227  }
228  }
229 
230  return ConstantVector::get(Result);
231 }
232 
233 
234 /// If this constant is a constant offset from a global, return the global and
235 /// the constant. Because of constantexprs, this function is recursive.
237  APInt &Offset, const DataLayout &DL) {
238  // Trivial case, constant is the global.
239  if ((GV = dyn_cast<GlobalValue>(C))) {
240  unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
241  Offset = APInt(BitWidth, 0);
242  return true;
243  }
244 
245  // Otherwise, if this isn't a constant expr, bail out.
247  if (!CE) return false;
248 
249  // Look through ptr->int and ptr->ptr casts.
250  if (CE->getOpcode() == Instruction::PtrToInt ||
251  CE->getOpcode() == Instruction::BitCast ||
252  CE->getOpcode() == Instruction::AddrSpaceCast)
253  return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
254 
255  // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
257  if (!GEP)
258  return false;
259 
260  unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
261  APInt TmpOffset(BitWidth, 0);
262 
263  // If the base isn't a global+constant, we aren't either.
264  if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
265  return false;
266 
267  // Otherwise, add any offset that our operands provide.
268  if (!GEP->accumulateConstantOffset(DL, TmpOffset))
269  return false;
270 
271  Offset = TmpOffset;
272  return true;
273 }
274 
275 /// Recursive helper to read bits out of global. C is the constant being copied
276 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
277 /// results into and BytesLeft is the number of bytes left in
278 /// the CurPtr buffer. DL is the DataLayout.
279 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
280  unsigned char *CurPtr, unsigned BytesLeft,
281  const DataLayout &DL) {
282  assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
283  "Out of range access");
284 
285  // If this element is zero or undefined, we can just return since *CurPtr is
286  // zero initialized.
287  if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
288  return true;
289 
290  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
291  if (CI->getBitWidth() > 64 ||
292  (CI->getBitWidth() & 7) != 0)
293  return false;
294 
295  uint64_t Val = CI->getZExtValue();
296  unsigned IntBytes = unsigned(CI->getBitWidth()/8);
297 
298  for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
299  int n = ByteOffset;
300  if (!DL.isLittleEndian())
301  n = IntBytes - n - 1;
302  CurPtr[i] = (unsigned char)(Val >> (n * 8));
303  ++ByteOffset;
304  }
305  return true;
306  }
307 
308  if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
309  if (CFP->getType()->isDoubleTy()) {
310  C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
311  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
312  }
313  if (CFP->getType()->isFloatTy()){
314  C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
315  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
316  }
317  if (CFP->getType()->isHalfTy()){
318  C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
319  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
320  }
321  return false;
322  }
323 
324  if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
325  const StructLayout *SL = DL.getStructLayout(CS->getType());
326  unsigned Index = SL->getElementContainingOffset(ByteOffset);
327  uint64_t CurEltOffset = SL->getElementOffset(Index);
328  ByteOffset -= CurEltOffset;
329 
330  while (1) {
331  // If the element access is to the element itself and not to tail padding,
332  // read the bytes from the element.
333  uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
334 
335  if (ByteOffset < EltSize &&
336  !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
337  BytesLeft, DL))
338  return false;
339 
340  ++Index;
341 
342  // Check to see if we read from the last struct element, if so we're done.
343  if (Index == CS->getType()->getNumElements())
344  return true;
345 
346  // If we read all of the bytes we needed from this element we're done.
347  uint64_t NextEltOffset = SL->getElementOffset(Index);
348 
349  if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
350  return true;
351 
352  // Move to the next element of the struct.
353  CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
354  BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
355  ByteOffset = 0;
356  CurEltOffset = NextEltOffset;
357  }
358  // not reached.
359  }
360 
361  if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
362  isa<ConstantDataSequential>(C)) {
363  Type *EltTy = C->getType()->getSequentialElementType();
364  uint64_t EltSize = DL.getTypeAllocSize(EltTy);
365  uint64_t Index = ByteOffset / EltSize;
366  uint64_t Offset = ByteOffset - Index * EltSize;
367  uint64_t NumElts;
368  if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
369  NumElts = AT->getNumElements();
370  else
371  NumElts = C->getType()->getVectorNumElements();
372 
373  for (; Index != NumElts; ++Index) {
374  if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
375  BytesLeft, DL))
376  return false;
377 
378  uint64_t BytesWritten = EltSize - Offset;
379  assert(BytesWritten <= EltSize && "Not indexing into this element?");
380  if (BytesWritten >= BytesLeft)
381  return true;
382 
383  Offset = 0;
384  BytesLeft -= BytesWritten;
385  CurPtr += BytesWritten;
386  }
387  return true;
388  }
389 
390  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
391  if (CE->getOpcode() == Instruction::IntToPtr &&
392  CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
393  return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
394  BytesLeft, DL);
395  }
396  }
397 
398  // Otherwise, unknown initializer type.
399  return false;
400 }
401 
403  const DataLayout &DL) {
404  PointerType *PTy = cast<PointerType>(C->getType());
405  Type *LoadTy = PTy->getElementType();
406  IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
407 
408  // If this isn't an integer load we can't fold it directly.
409  if (!IntType) {
410  unsigned AS = PTy->getAddressSpace();
411 
412  // If this is a float/double load, we can try folding it as an int32/64 load
413  // and then bitcast the result. This can be useful for union cases. Note
414  // that address spaces don't matter here since we're not going to result in
415  // an actual new load.
416  Type *MapTy;
417  if (LoadTy->isHalfTy())
418  MapTy = Type::getInt16PtrTy(C->getContext(), AS);
419  else if (LoadTy->isFloatTy())
420  MapTy = Type::getInt32PtrTy(C->getContext(), AS);
421  else if (LoadTy->isDoubleTy())
422  MapTy = Type::getInt64PtrTy(C->getContext(), AS);
423  else if (LoadTy->isVectorTy()) {
425  DL.getTypeAllocSizeInBits(LoadTy), AS);
426  } else
427  return nullptr;
428 
429  C = FoldBitCast(C, MapTy, DL);
430  if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, DL))
431  return FoldBitCast(Res, LoadTy, DL);
432  return nullptr;
433  }
434 
435  unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
436  if (BytesLoaded > 32 || BytesLoaded == 0)
437  return nullptr;
438 
439  GlobalValue *GVal;
440  APInt Offset;
441  if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
442  return nullptr;
443 
445  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
446  !GV->getInitializer()->getType()->isSized())
447  return nullptr;
448 
449  // If we're loading off the beginning of the global, some bytes may be valid,
450  // but we don't try to handle this.
451  if (Offset.isNegative())
452  return nullptr;
453 
454  // If we're not accessing anything in this constant, the result is undefined.
455  if (Offset.getZExtValue() >=
457  return UndefValue::get(IntType);
458 
459  unsigned char RawBytes[32] = {0};
460  if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
461  BytesLoaded, DL))
462  return nullptr;
463 
464  APInt ResultVal = APInt(IntType->getBitWidth(), 0);
465  if (DL.isLittleEndian()) {
466  ResultVal = RawBytes[BytesLoaded - 1];
467  for (unsigned i = 1; i != BytesLoaded; ++i) {
468  ResultVal <<= 8;
469  ResultVal |= RawBytes[BytesLoaded - 1 - i];
470  }
471  } else {
472  ResultVal = RawBytes[0];
473  for (unsigned i = 1; i != BytesLoaded; ++i) {
474  ResultVal <<= 8;
475  ResultVal |= RawBytes[i];
476  }
477  }
478 
479  return ConstantInt::get(IntType->getContext(), ResultVal);
480 }
481 
483  const DataLayout &DL) {
484  auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
485  if (!DestPtrTy)
486  return nullptr;
487  Type *DestTy = DestPtrTy->getElementType();
488 
490  if (!C)
491  return nullptr;
492 
493  do {
494  Type *SrcTy = C->getType();
495 
496  // If the type sizes are the same and a cast is legal, just directly
497  // cast the constant.
498  if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
499  Instruction::CastOps Cast = Instruction::BitCast;
500  // If we are going from a pointer to int or vice versa, we spell the cast
501  // differently.
502  if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
503  Cast = Instruction::IntToPtr;
504  else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
505  Cast = Instruction::PtrToInt;
506 
507  if (CastInst::castIsValid(Cast, C, DestTy))
508  return ConstantExpr::getCast(Cast, C, DestTy);
509  }
510 
511  // If this isn't an aggregate type, there is nothing we can do to drill down
512  // and find a bitcastable constant.
513  if (!SrcTy->isAggregateType())
514  return nullptr;
515 
516  // We're simulating a load through a pointer that was bitcast to point to
517  // a different type, so we can try to walk down through the initial
518  // elements of an aggregate to see if some part of th e aggregate is
519  // castable to implement the "load" semantic model.
520  C = C->getAggregateElement(0u);
521  } while (C);
522 
523  return nullptr;
524 }
525 
526 /// Return the value that a load from C would produce if it is constant and
527 /// determinable. If this is not determinable, return null.
529  const DataLayout &DL) {
530  // First, try the easy cases:
531  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
532  if (GV->isConstant() && GV->hasDefinitiveInitializer())
533  return GV->getInitializer();
534 
535  // If the loaded value isn't a constant expr, we can't handle it.
537  if (!CE)
538  return nullptr;
539 
540  if (CE->getOpcode() == Instruction::GetElementPtr) {
541  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
542  if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
543  if (Constant *V =
544  ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
545  return V;
546  }
547  }
548  }
549 
550  if (CE->getOpcode() == Instruction::BitCast)
551  if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, DL))
552  return LoadedC;
553 
554  // Instead of loading constant c string, use corresponding integer value
555  // directly if string length is small enough.
556  StringRef Str;
557  if (getConstantStringInfo(CE, Str) && !Str.empty()) {
558  unsigned StrLen = Str.size();
559  Type *Ty = cast<PointerType>(CE->getType())->getElementType();
560  unsigned NumBits = Ty->getPrimitiveSizeInBits();
561  // Replace load with immediate integer if the result is an integer or fp
562  // value.
563  if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
564  (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
565  APInt StrVal(NumBits, 0);
566  APInt SingleChar(NumBits, 0);
567  if (DL.isLittleEndian()) {
568  for (signed i = StrLen-1; i >= 0; i--) {
569  SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
570  StrVal = (StrVal << 8) | SingleChar;
571  }
572  } else {
573  for (unsigned i = 0; i < StrLen; i++) {
574  SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
575  StrVal = (StrVal << 8) | SingleChar;
576  }
577  // Append NULL at the end.
578  SingleChar = 0;
579  StrVal = (StrVal << 8) | SingleChar;
580  }
581 
583  if (Ty->isFloatingPointTy())
584  Res = ConstantExpr::getBitCast(Res, Ty);
585  return Res;
586  }
587  }
588 
589  // If this load comes from anywhere in a constant global, and if the global
590  // is all undef or zero, we know what it loads.
591  if (GlobalVariable *GV =
592  dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
593  if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
594  Type *ResTy = cast<PointerType>(C->getType())->getElementType();
595  if (GV->getInitializer()->isNullValue())
596  return Constant::getNullValue(ResTy);
597  if (isa<UndefValue>(GV->getInitializer()))
598  return UndefValue::get(ResTy);
599  }
600  }
601 
602  // Try hard to fold loads from bitcasted strange and non-type-safe things.
603  return FoldReinterpretLoadFromConstPtr(CE, DL);
604 }
605 
607  const DataLayout &DL) {
608  if (LI->isVolatile()) return nullptr;
609 
610  if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
611  return ConstantFoldLoadFromConstPtr(C, DL);
612 
613  return nullptr;
614 }
615 
616 /// One of Op0/Op1 is a constant expression.
617 /// Attempt to symbolically evaluate the result of a binary operator merging
618 /// these together. If target data info is available, it is provided as DL,
619 /// otherwise DL is null.
620 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
621  Constant *Op1,
622  const DataLayout &DL) {
623  // SROA
624 
625  // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
626  // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
627  // bits.
628 
629  if (Opc == Instruction::And) {
630  unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
631  APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
632  APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
633  computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
634  computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
635  if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
636  // All the bits of Op0 that the 'and' could be masking are already zero.
637  return Op0;
638  }
639  if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
640  // All the bits of Op1 that the 'and' could be masking are already zero.
641  return Op1;
642  }
643 
644  APInt KnownZero = KnownZero0 | KnownZero1;
645  APInt KnownOne = KnownOne0 & KnownOne1;
646  if ((KnownZero | KnownOne).isAllOnesValue()) {
647  return ConstantInt::get(Op0->getType(), KnownOne);
648  }
649  }
650 
651  // If the constant expr is something like &A[123] - &A[4].f, fold this into a
652  // constant. This happens frequently when iterating over a global array.
653  if (Opc == Instruction::Sub) {
654  GlobalValue *GV1, *GV2;
655  APInt Offs1, Offs2;
656 
657  if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
658  if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
659  unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
660 
661  // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
662  // PtrToInt may change the bitwidth so we have convert to the right size
663  // first.
664  return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
665  Offs2.zextOrTrunc(OpSize));
666  }
667  }
668 
669  return nullptr;
670 }
671 
672 /// If array indices are not pointer-sized integers, explicitly cast them so
673 /// that they aren't implicitly casted by the getelementptr.
675  Type *ResultTy, const DataLayout &DL,
676  const TargetLibraryInfo *TLI) {
677  Type *IntPtrTy = DL.getIntPtrType(ResultTy);
678 
679  bool Any = false;
681  for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
682  if ((i == 1 ||
683  !isa<StructType>(GetElementPtrInst::getIndexedType(
684  cast<PointerType>(Ops[0]->getType()->getScalarType())
685  ->getElementType(),
686  Ops.slice(1, i - 1)))) &&
687  Ops[i]->getType() != IntPtrTy) {
688  Any = true;
690  true,
691  IntPtrTy,
692  true),
693  Ops[i], IntPtrTy));
694  } else
695  NewIdxs.push_back(Ops[i]);
696  }
697 
698  if (!Any)
699  return nullptr;
700 
701  Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ops[0], NewIdxs);
702  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
703  if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
704  C = Folded;
705  }
706 
707  return C;
708 }
709 
710 /// Strip the pointer casts, but preserve the address space information.
712  assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
713  PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
714  Ptr = Ptr->stripPointerCasts();
715  PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
716 
717  // Preserve the address space number of the pointer.
718  if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
719  NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
720  OldPtrTy->getAddressSpace());
721  Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
722  }
723  return Ptr;
724 }
725 
726 /// If we can symbolically evaluate the GEP constant expression, do so.
728  Type *ResultTy, const DataLayout &DL,
729  const TargetLibraryInfo *TLI) {
730  Constant *Ptr = Ops[0];
731  if (!Ptr->getType()->getPointerElementType()->isSized() ||
732  !Ptr->getType()->isPointerTy())
733  return nullptr;
734 
735  Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
736  Type *ResultElementTy = ResultTy->getPointerElementType();
737 
738  // If this is a constant expr gep that is effectively computing an
739  // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
740  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
741  if (!isa<ConstantInt>(Ops[i])) {
742 
743  // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
744  // "inttoptr (sub (ptrtoint Ptr), V)"
745  if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
746  ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
747  assert((!CE || CE->getType() == IntPtrTy) &&
748  "CastGEPIndices didn't canonicalize index types!");
749  if (CE && CE->getOpcode() == Instruction::Sub &&
750  CE->getOperand(0)->isNullValue()) {
751  Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
752  Res = ConstantExpr::getSub(Res, CE->getOperand(1));
753  Res = ConstantExpr::getIntToPtr(Res, ResultTy);
754  if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
755  Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
756  return Res;
757  }
758  }
759  return nullptr;
760  }
761 
762  unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
763  APInt Offset =
764  APInt(BitWidth,
765  DL.getIndexedOffset(
766  Ptr->getType(),
767  makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
768  Ptr = StripPtrCastKeepAS(Ptr);
769 
770  // If this is a GEP of a GEP, fold it all into a single GEP.
771  while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
772  SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
773 
774  // Do not try the incorporate the sub-GEP if some index is not a number.
775  bool AllConstantInt = true;
776  for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
777  if (!isa<ConstantInt>(NestedOps[i])) {
778  AllConstantInt = false;
779  break;
780  }
781  if (!AllConstantInt)
782  break;
783 
784  Ptr = cast<Constant>(GEP->getOperand(0));
785  Offset += APInt(BitWidth, DL.getIndexedOffset(Ptr->getType(), NestedOps));
786  Ptr = StripPtrCastKeepAS(Ptr);
787  }
788 
789  // If the base value for this address is a literal integer value, fold the
790  // getelementptr to the resulting integer value casted to the pointer type.
791  APInt BasePtr(BitWidth, 0);
792  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
793  if (CE->getOpcode() == Instruction::IntToPtr) {
794  if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
795  BasePtr = Base->getValue().zextOrTrunc(BitWidth);
796  }
797  }
798 
799  if (Ptr->isNullValue() || BasePtr != 0) {
800  Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
801  return ConstantExpr::getIntToPtr(C, ResultTy);
802  }
803 
804  // Otherwise form a regular getelementptr. Recompute the indices so that
805  // we eliminate over-indexing of the notional static type array bounds.
806  // This makes it easy to determine if the getelementptr is "inbounds".
807  // Also, this helps GlobalOpt do SROA on GlobalVariables.
808  Type *Ty = Ptr->getType();
809  assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
811 
812  do {
813  if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
814  if (ATy->isPointerTy()) {
815  // The only pointer indexing we'll do is on the first index of the GEP.
816  if (!NewIdxs.empty())
817  break;
818 
819  // Only handle pointers to sized types, not pointers to functions.
820  if (!ATy->getElementType()->isSized())
821  return nullptr;
822  }
823 
824  // Determine which element of the array the offset points into.
825  APInt ElemSize(BitWidth, DL.getTypeAllocSize(ATy->getElementType()));
826  if (ElemSize == 0)
827  // The element size is 0. This may be [0 x Ty]*, so just use a zero
828  // index for this level and proceed to the next level to see if it can
829  // accommodate the offset.
830  NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
831  else {
832  // The element size is non-zero divide the offset by the element
833  // size (rounding down), to compute the index at this level.
834  APInt NewIdx = Offset.udiv(ElemSize);
835  Offset -= NewIdx * ElemSize;
836  NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
837  }
838  Ty = ATy->getElementType();
839  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
840  // If we end up with an offset that isn't valid for this struct type, we
841  // can't re-form this GEP in a regular form, so bail out. The pointer
842  // operand likely went through casts that are necessary to make the GEP
843  // sensible.
844  const StructLayout &SL = *DL.getStructLayout(STy);
845  if (Offset.uge(SL.getSizeInBytes()))
846  break;
847 
848  // Determine which field of the struct the offset points into. The
849  // getZExtValue is fine as we've already ensured that the offset is
850  // within the range representable by the StructLayout API.
851  unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
852  NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
853  ElIdx));
854  Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
855  Ty = STy->getTypeAtIndex(ElIdx);
856  } else {
857  // We've reached some non-indexable type.
858  break;
859  }
860  } while (Ty != ResultElementTy);
861 
862  // If we haven't used up the entire offset by descending the static
863  // type, then the offset is pointing into the middle of an indivisible
864  // member, so we can't simplify it.
865  if (Offset != 0)
866  return nullptr;
867 
868  // Create a GEP.
869  Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ptr, NewIdxs);
870  assert(C->getType()->getPointerElementType() == Ty &&
871  "Computed GetElementPtr has unexpected type!");
872 
873  // If we ended up indexing a member with a type that doesn't match
874  // the type of what the original indices indexed, add a cast.
875  if (Ty != ResultElementTy)
876  C = FoldBitCast(C, ResultTy, DL);
877 
878  return C;
879 }
880 
881 
882 
883 //===----------------------------------------------------------------------===//
884 // Constant Folding public APIs
885 //===----------------------------------------------------------------------===//
886 
887 /// Try to constant fold the specified instruction.
888 /// If successful, the constant result is returned, if not, null is returned.
889 /// Note that this fails if not all of the operands are constant. Otherwise,
890 /// this function can only fail when attempting to fold instructions like loads
891 /// and stores, which have no constant expression form.
893  const TargetLibraryInfo *TLI) {
894  // Handle PHI nodes quickly here...
895  if (PHINode *PN = dyn_cast<PHINode>(I)) {
896  Constant *CommonValue = nullptr;
897 
898  for (Value *Incoming : PN->incoming_values()) {
899  // If the incoming value is undef then skip it. Note that while we could
900  // skip the value if it is equal to the phi node itself we choose not to
901  // because that would break the rule that constant folding only applies if
902  // all operands are constants.
903  if (isa<UndefValue>(Incoming))
904  continue;
905  // If the incoming value is not a constant, then give up.
906  Constant *C = dyn_cast<Constant>(Incoming);
907  if (!C)
908  return nullptr;
909  // Fold the PHI's operands.
910  if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
911  C = ConstantFoldConstantExpression(NewC, DL, TLI);
912  // If the incoming value is a different constant to
913  // the one we saw previously, then give up.
914  if (CommonValue && C != CommonValue)
915  return nullptr;
916  CommonValue = C;
917  }
918 
919 
920  // If we reach here, all incoming values are the same constant or undef.
921  return CommonValue ? CommonValue : UndefValue::get(PN->getType());
922  }
923 
924  // Scan the operand list, checking to see if they are all constants, if so,
925  // hand off to ConstantFoldInstOperands.
927  for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
928  Constant *Op = dyn_cast<Constant>(*i);
929  if (!Op)
930  return nullptr; // All operands not constant!
931 
932  // Fold the Instruction's operands.
933  if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
934  Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
935 
936  Ops.push_back(Op);
937  }
938 
939  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
940  return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
941  DL, TLI);
942 
943  if (const LoadInst *LI = dyn_cast<LoadInst>(I))
944  return ConstantFoldLoadInst(LI, DL);
945 
946  if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
948  cast<Constant>(IVI->getAggregateOperand()),
949  cast<Constant>(IVI->getInsertedValueOperand()),
950  IVI->getIndices());
951  }
952 
953  if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
955  cast<Constant>(EVI->getAggregateOperand()),
956  EVI->getIndices());
957  }
958 
959  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, DL, TLI);
960 }
961 
962 static Constant *
964  const TargetLibraryInfo *TLI,
965  SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
967  for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
968  ++i) {
969  Constant *NewC = cast<Constant>(*i);
970  // Recursively fold the ConstantExpr's operands. If we have already folded
971  // a ConstantExpr, we don't have to process it again.
972  if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
973  if (FoldedOps.insert(NewCE).second)
974  NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
975  }
976  Ops.push_back(NewC);
977  }
978 
979  if (CE->isCompare())
980  return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
981  DL, TLI);
982  return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, DL, TLI);
983 }
984 
985 /// Attempt to fold the constant expression
986 /// using the specified DataLayout. If successful, the constant result is
987 /// result is returned, if not, null is returned.
989  const DataLayout &DL,
990  const TargetLibraryInfo *TLI) {
992  return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
993 }
994 
995 /// Attempt to constant fold an instruction with the
996 /// specified opcode and operands. If successful, the constant result is
997 /// returned, if not, null is returned. Note that this function can fail when
998 /// attempting to fold instructions like loads and stores, which have no
999 /// constant expression form.
1000 ///
1001 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1002 /// information, due to only being passed an opcode and operands. Constant
1003 /// folding using this function strips this information.
1004 ///
1007  const DataLayout &DL,
1008  const TargetLibraryInfo *TLI) {
1009  // Handle easy binops first.
1010  if (Instruction::isBinaryOp(Opcode)) {
1011  if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
1012  if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], DL))
1013  return C;
1014  }
1015 
1016  return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
1017  }
1018 
1019  switch (Opcode) {
1020  default: return nullptr;
1021  case Instruction::ICmp:
1022  case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1023  case Instruction::Call:
1024  if (Function *F = dyn_cast<Function>(Ops.back()))
1025  if (canConstantFoldCallTo(F))
1026  return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1027  return nullptr;
1028  case Instruction::PtrToInt:
1029  // If the input is a inttoptr, eliminate the pair. This requires knowing
1030  // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1031  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1032  if (CE->getOpcode() == Instruction::IntToPtr) {
1033  Constant *Input = CE->getOperand(0);
1034  unsigned InWidth = Input->getType()->getScalarSizeInBits();
1035  unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1036  if (PtrWidth < InWidth) {
1037  Constant *Mask =
1038  ConstantInt::get(CE->getContext(),
1039  APInt::getLowBitsSet(InWidth, PtrWidth));
1040  Input = ConstantExpr::getAnd(Input, Mask);
1041  }
1042  // Do a zext or trunc to get to the dest size.
1043  return ConstantExpr::getIntegerCast(Input, DestTy, false);
1044  }
1045  }
1046  return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1047  case Instruction::IntToPtr:
1048  // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1049  // the int size is >= the ptr size and the address spaces are the same.
1050  // This requires knowing the width of a pointer, so it can't be done in
1051  // ConstantExpr::getCast.
1052  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1053  if (CE->getOpcode() == Instruction::PtrToInt) {
1054  Constant *SrcPtr = CE->getOperand(0);
1055  unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1056  unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1057 
1058  if (MidIntSize >= SrcPtrSize) {
1059  unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1060  if (SrcAS == DestTy->getPointerAddressSpace())
1061  return FoldBitCast(CE->getOperand(0), DestTy, DL);
1062  }
1063  }
1064  }
1065 
1066  return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1067  case Instruction::Trunc:
1068  case Instruction::ZExt:
1069  case Instruction::SExt:
1070  case Instruction::FPTrunc:
1071  case Instruction::FPExt:
1072  case Instruction::UIToFP:
1073  case Instruction::SIToFP:
1074  case Instruction::FPToUI:
1075  case Instruction::FPToSI:
1076  case Instruction::AddrSpaceCast:
1077  return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1078  case Instruction::BitCast:
1079  return FoldBitCast(Ops[0], DestTy, DL);
1080  case Instruction::Select:
1081  return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1083  return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1084  case Instruction::InsertElement:
1085  return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1086  case Instruction::ShuffleVector:
1087  return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1088  case Instruction::GetElementPtr: {
1089  Type *SrcTy = nullptr;
1090  if (Constant *C = CastGEPIndices(SrcTy, Ops, DestTy, DL, TLI))
1091  return C;
1092  if (Constant *C = SymbolicallyEvaluateGEP(SrcTy, Ops, DestTy, DL, TLI))
1093  return C;
1094 
1095  return ConstantExpr::getGetElementPtr(SrcTy, Ops[0], Ops.slice(1));
1096  }
1097  }
1098 }
1099 
1100 /// Attempt to constant fold a compare
1101 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
1102 /// returns a constant expression of the specified operands.
1104  Constant *Ops0, Constant *Ops1,
1105  const DataLayout &DL,
1106  const TargetLibraryInfo *TLI) {
1107  // fold: icmp (inttoptr x), null -> icmp x, 0
1108  // fold: icmp (ptrtoint x), 0 -> icmp x, null
1109  // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1110  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1111  //
1112  // FIXME: The following comment is out of data and the DataLayout is here now.
1113  // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1114  // around to know if bit truncation is happening.
1115  if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1116  if (Ops1->isNullValue()) {
1117  if (CE0->getOpcode() == Instruction::IntToPtr) {
1118  Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1119  // Convert the integer value to the right size to ensure we get the
1120  // proper extension or truncation.
1121  Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1122  IntPtrTy, false);
1124  return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1125  }
1126 
1127  // Only do this transformation if the int is intptrty in size, otherwise
1128  // there is a truncation or extension that we aren't modeling.
1129  if (CE0->getOpcode() == Instruction::PtrToInt) {
1130  Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1131  if (CE0->getType() == IntPtrTy) {
1132  Constant *C = CE0->getOperand(0);
1134  return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1135  }
1136  }
1137  }
1138 
1139  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1140  if (CE0->getOpcode() == CE1->getOpcode()) {
1141  if (CE0->getOpcode() == Instruction::IntToPtr) {
1142  Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1143 
1144  // Convert the integer value to the right size to ensure we get the
1145  // proper extension or truncation.
1146  Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1147  IntPtrTy, false);
1148  Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1149  IntPtrTy, false);
1150  return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1151  }
1152 
1153  // Only do this transformation if the int is intptrty in size, otherwise
1154  // there is a truncation or extension that we aren't modeling.
1155  if (CE0->getOpcode() == Instruction::PtrToInt) {
1156  Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1157  if (CE0->getType() == IntPtrTy &&
1158  CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1160  Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1161  }
1162  }
1163  }
1164  }
1165 
1166  // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1167  // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1168  if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1169  CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1171  Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1173  Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1174  unsigned OpC =
1176  Constant *Ops[] = { LHS, RHS };
1177  return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, DL, TLI);
1178  }
1179  }
1180 
1181  return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1182 }
1183 
1184 
1185 /// Given a constant and a getelementptr constantexpr, return the constant value
1186 /// being addressed by the constant expression, or null if something is funny
1187 /// and we can't decide.
1189  ConstantExpr *CE) {
1190  if (!CE->getOperand(1)->isNullValue())
1191  return nullptr; // Do not allow stepping over the value!
1192 
1193  // Loop over all of the operands, tracking down which value we are
1194  // addressing.
1195  for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1196  C = C->getAggregateElement(CE->getOperand(i));
1197  if (!C)
1198  return nullptr;
1199  }
1200  return C;
1201 }
1202 
1203 /// Given a constant and getelementptr indices (with an *implied* zero pointer
1204 /// index that is not in the list), return the constant value being addressed by
1205 /// a virtual load, or null if something is funny and we can't decide.
1207  ArrayRef<Constant*> Indices) {
1208  // Loop over all of the operands, tracking down which value we are
1209  // addressing.
1210  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1211  C = C->getAggregateElement(Indices[i]);
1212  if (!C)
1213  return nullptr;
1214  }
1215  return C;
1216 }
1217 
1218 
1219 //===----------------------------------------------------------------------===//
1220 // Constant Folding for Calls
1221 //
1222 
1223 /// Return true if it's even possible to fold a call to the specified function.
1225  switch (F->getIntrinsicID()) {
1226  case Intrinsic::fabs:
1227  case Intrinsic::minnum:
1228  case Intrinsic::maxnum:
1229  case Intrinsic::log:
1230  case Intrinsic::log2:
1231  case Intrinsic::log10:
1232  case Intrinsic::exp:
1233  case Intrinsic::exp2:
1234  case Intrinsic::floor:
1235  case Intrinsic::ceil:
1236  case Intrinsic::sqrt:
1237  case Intrinsic::sin:
1238  case Intrinsic::cos:
1239  case Intrinsic::pow:
1240  case Intrinsic::powi:
1241  case Intrinsic::bswap:
1242  case Intrinsic::ctpop:
1243  case Intrinsic::ctlz:
1244  case Intrinsic::cttz:
1245  case Intrinsic::fma:
1246  case Intrinsic::fmuladd:
1247  case Intrinsic::copysign:
1248  case Intrinsic::round:
1249  case Intrinsic::sadd_with_overflow:
1250  case Intrinsic::uadd_with_overflow:
1251  case Intrinsic::ssub_with_overflow:
1252  case Intrinsic::usub_with_overflow:
1253  case Intrinsic::smul_with_overflow:
1254  case Intrinsic::umul_with_overflow:
1255  case Intrinsic::convert_from_fp16:
1256  case Intrinsic::convert_to_fp16:
1257  case Intrinsic::x86_sse_cvtss2si:
1258  case Intrinsic::x86_sse_cvtss2si64:
1259  case Intrinsic::x86_sse_cvttss2si:
1260  case Intrinsic::x86_sse_cvttss2si64:
1261  case Intrinsic::x86_sse2_cvtsd2si:
1262  case Intrinsic::x86_sse2_cvtsd2si64:
1263  case Intrinsic::x86_sse2_cvttsd2si:
1264  case Intrinsic::x86_sse2_cvttsd2si64:
1265  return true;
1266  default:
1267  return false;
1268  case 0: break;
1269  }
1270 
1271  if (!F->hasName())
1272  return false;
1273  StringRef Name = F->getName();
1274 
1275  // In these cases, the check of the length is required. We don't want to
1276  // return true for a name like "cos\0blah" which strcmp would return equal to
1277  // "cos", but has length 8.
1278  switch (Name[0]) {
1279  default: return false;
1280  case 'a':
1281  return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1282  case 'c':
1283  return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1284  case 'e':
1285  return Name == "exp" || Name == "exp2";
1286  case 'f':
1287  return Name == "fabs" || Name == "fmod" || Name == "floor";
1288  case 'l':
1289  return Name == "log" || Name == "log10";
1290  case 'p':
1291  return Name == "pow";
1292  case 's':
1293  return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1294  Name == "sinf" || Name == "sqrtf";
1295  case 't':
1296  return Name == "tan" || Name == "tanh";
1297  }
1298 }
1299 
1300 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1301  if (Ty->isHalfTy()) {
1302  APFloat APF(V);
1303  bool unused;
1305  return ConstantFP::get(Ty->getContext(), APF);
1306  }
1307  if (Ty->isFloatTy())
1308  return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1309  if (Ty->isDoubleTy())
1310  return ConstantFP::get(Ty->getContext(), APFloat(V));
1311  llvm_unreachable("Can only constant fold half/float/double");
1312 
1313 }
1314 
1315 namespace {
1316 /// Clear the floating-point exception state.
1317 static inline void llvm_fenv_clearexcept() {
1318 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1319  feclearexcept(FE_ALL_EXCEPT);
1320 #endif
1321  errno = 0;
1322 }
1323 
1324 /// Test if a floating-point exception was raised.
1325 static inline bool llvm_fenv_testexcept() {
1326  int errno_val = errno;
1327  if (errno_val == ERANGE || errno_val == EDOM)
1328  return true;
1329 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1330  if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1331  return true;
1332 #endif
1333  return false;
1334 }
1335 } // End namespace
1336 
1337 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1338  Type *Ty) {
1339  llvm_fenv_clearexcept();
1340  V = NativeFP(V);
1341  if (llvm_fenv_testexcept()) {
1342  llvm_fenv_clearexcept();
1343  return nullptr;
1344  }
1345 
1346  return GetConstantFoldFPValue(V, Ty);
1347 }
1348 
1349 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1350  double V, double W, Type *Ty) {
1351  llvm_fenv_clearexcept();
1352  V = NativeFP(V, W);
1353  if (llvm_fenv_testexcept()) {
1354  llvm_fenv_clearexcept();
1355  return nullptr;
1356  }
1357 
1358  return GetConstantFoldFPValue(V, Ty);
1359 }
1360 
1361 /// Attempt to fold an SSE floating point to integer conversion of a constant
1362 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1363 /// used (toward nearest, ties to even). This matches the behavior of the
1364 /// non-truncating SSE instructions in the default rounding mode. The desired
1365 /// integer type Ty is used to select how many bits are available for the
1366 /// result. Returns null if the conversion cannot be performed, otherwise
1367 /// returns the Constant value resulting from the conversion.
1369  bool roundTowardZero, Type *Ty) {
1370  // All of these conversion intrinsics form an integer of at most 64bits.
1371  unsigned ResultWidth = Ty->getIntegerBitWidth();
1372  assert(ResultWidth <= 64 &&
1373  "Can only constant fold conversions to 64 and 32 bit ints");
1374 
1375  uint64_t UIntVal;
1376  bool isExact = false;
1377  APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1379  APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1380  /*isSigned=*/true, mode,
1381  &isExact);
1382  if (status != APFloat::opOK && status != APFloat::opInexact)
1383  return nullptr;
1384  return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1385 }
1386 
1387 static double getValueAsDouble(ConstantFP *Op) {
1388  Type *Ty = Op->getType();
1389 
1390  if (Ty->isFloatTy())
1391  return Op->getValueAPF().convertToFloat();
1392 
1393  if (Ty->isDoubleTy())
1394  return Op->getValueAPF().convertToDouble();
1395 
1396  bool unused;
1397  APFloat APF = Op->getValueAPF();
1399  return APF.convertToDouble();
1400 }
1401 
1402 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1404  const TargetLibraryInfo *TLI) {
1405  if (Operands.size() == 1) {
1406  if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1407  if (IntrinsicID == Intrinsic::convert_to_fp16) {
1408  APFloat Val(Op->getValueAPF());
1409 
1410  bool lost = false;
1412 
1413  return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1414  }
1415 
1416  if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1417  return nullptr;
1418 
1419  if (IntrinsicID == Intrinsic::round) {
1420  APFloat V = Op->getValueAPF();
1422  return ConstantFP::get(Ty->getContext(), V);
1423  }
1424 
1425  /// We only fold functions with finite arguments. Folding NaN and inf is
1426  /// likely to be aborted with an exception anyway, and some host libms
1427  /// have known errors raising exceptions.
1428  if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1429  return nullptr;
1430 
1431  /// Currently APFloat versions of these functions do not exist, so we use
1432  /// the host native double versions. Float versions are not called
1433  /// directly but for all these it is true (float)(f((double)arg)) ==
1434  /// f(arg). Long double not supported yet.
1435  double V = getValueAsDouble(Op);
1436 
1437  switch (IntrinsicID) {
1438  default: break;
1439  case Intrinsic::fabs:
1440  return ConstantFoldFP(fabs, V, Ty);
1441  case Intrinsic::log2:
1442  return ConstantFoldFP(Log2, V, Ty);
1443  case Intrinsic::log:
1444  return ConstantFoldFP(log, V, Ty);
1445  case Intrinsic::log10:
1446  return ConstantFoldFP(log10, V, Ty);
1447  case Intrinsic::exp:
1448  return ConstantFoldFP(exp, V, Ty);
1449  case Intrinsic::exp2:
1450  return ConstantFoldFP(exp2, V, Ty);
1451  case Intrinsic::floor:
1452  return ConstantFoldFP(floor, V, Ty);
1453  case Intrinsic::ceil:
1454  return ConstantFoldFP(ceil, V, Ty);
1455  case Intrinsic::sin:
1456  return ConstantFoldFP(sin, V, Ty);
1457  case Intrinsic::cos:
1458  return ConstantFoldFP(cos, V, Ty);
1459  }
1460 
1461  if (!TLI)
1462  return nullptr;
1463 
1464  switch (Name[0]) {
1465  case 'a':
1466  if (Name == "acos" && TLI->has(LibFunc::acos))
1467  return ConstantFoldFP(acos, V, Ty);
1468  else if (Name == "asin" && TLI->has(LibFunc::asin))
1469  return ConstantFoldFP(asin, V, Ty);
1470  else if (Name == "atan" && TLI->has(LibFunc::atan))
1471  return ConstantFoldFP(atan, V, Ty);
1472  break;
1473  case 'c':
1474  if (Name == "ceil" && TLI->has(LibFunc::ceil))
1475  return ConstantFoldFP(ceil, V, Ty);
1476  else if (Name == "cos" && TLI->has(LibFunc::cos))
1477  return ConstantFoldFP(cos, V, Ty);
1478  else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1479  return ConstantFoldFP(cosh, V, Ty);
1480  else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1481  return ConstantFoldFP(cos, V, Ty);
1482  break;
1483  case 'e':
1484  if (Name == "exp" && TLI->has(LibFunc::exp))
1485  return ConstantFoldFP(exp, V, Ty);
1486 
1487  if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1488  // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1489  // C99 library.
1490  return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1491  }
1492  break;
1493  case 'f':
1494  if (Name == "fabs" && TLI->has(LibFunc::fabs))
1495  return ConstantFoldFP(fabs, V, Ty);
1496  else if (Name == "floor" && TLI->has(LibFunc::floor))
1497  return ConstantFoldFP(floor, V, Ty);
1498  break;
1499  case 'l':
1500  if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1501  return ConstantFoldFP(log, V, Ty);
1502  else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1503  return ConstantFoldFP(log10, V, Ty);
1504  else if (IntrinsicID == Intrinsic::sqrt &&
1505  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1506  if (V >= -0.0)
1507  return ConstantFoldFP(sqrt, V, Ty);
1508  else {
1509  // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1510  // all guarantee or favor returning NaN - the square root of a
1511  // negative number is not defined for the LLVM sqrt intrinsic.
1512  // This is because the intrinsic should only be emitted in place of
1513  // libm's sqrt function when using "no-nans-fp-math".
1514  return UndefValue::get(Ty);
1515  }
1516  }
1517  break;
1518  case 's':
1519  if (Name == "sin" && TLI->has(LibFunc::sin))
1520  return ConstantFoldFP(sin, V, Ty);
1521  else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1522  return ConstantFoldFP(sinh, V, Ty);
1523  else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1524  return ConstantFoldFP(sqrt, V, Ty);
1525  else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1526  return ConstantFoldFP(sqrt, V, Ty);
1527  else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1528  return ConstantFoldFP(sin, V, Ty);
1529  break;
1530  case 't':
1531  if (Name == "tan" && TLI->has(LibFunc::tan))
1532  return ConstantFoldFP(tan, V, Ty);
1533  else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1534  return ConstantFoldFP(tanh, V, Ty);
1535  break;
1536  default:
1537  break;
1538  }
1539  return nullptr;
1540  }
1541 
1542  if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1543  switch (IntrinsicID) {
1544  case Intrinsic::bswap:
1545  return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1546  case Intrinsic::ctpop:
1547  return ConstantInt::get(Ty, Op->getValue().countPopulation());
1548  case Intrinsic::convert_from_fp16: {
1549  APFloat Val(APFloat::IEEEhalf, Op->getValue());
1550 
1551  bool lost = false;
1552  APFloat::opStatus status = Val.convert(
1554 
1555  // Conversion is always precise.
1556  (void)status;
1557  assert(status == APFloat::opOK && !lost &&
1558  "Precision lost during fp16 constfolding");
1559 
1560  return ConstantFP::get(Ty->getContext(), Val);
1561  }
1562  default:
1563  return nullptr;
1564  }
1565  }
1566 
1567  // Support ConstantVector in case we have an Undef in the top.
1568  if (isa<ConstantVector>(Operands[0]) ||
1569  isa<ConstantDataVector>(Operands[0])) {
1570  Constant *Op = cast<Constant>(Operands[0]);
1571  switch (IntrinsicID) {
1572  default: break;
1573  case Intrinsic::x86_sse_cvtss2si:
1574  case Intrinsic::x86_sse_cvtss2si64:
1575  case Intrinsic::x86_sse2_cvtsd2si:
1576  case Intrinsic::x86_sse2_cvtsd2si64:
1577  if (ConstantFP *FPOp =
1578  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1579  return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1580  /*roundTowardZero=*/false, Ty);
1581  case Intrinsic::x86_sse_cvttss2si:
1582  case Intrinsic::x86_sse_cvttss2si64:
1583  case Intrinsic::x86_sse2_cvttsd2si:
1584  case Intrinsic::x86_sse2_cvttsd2si64:
1585  if (ConstantFP *FPOp =
1586  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1587  return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1588  /*roundTowardZero=*/true, Ty);
1589  }
1590  }
1591 
1592  if (isa<UndefValue>(Operands[0])) {
1593  if (IntrinsicID == Intrinsic::bswap)
1594  return Operands[0];
1595  return nullptr;
1596  }
1597 
1598  return nullptr;
1599  }
1600 
1601  if (Operands.size() == 2) {
1602  if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1603  if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1604  return nullptr;
1605  double Op1V = getValueAsDouble(Op1);
1606 
1607  if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1608  if (Op2->getType() != Op1->getType())
1609  return nullptr;
1610 
1611  double Op2V = getValueAsDouble(Op2);
1612  if (IntrinsicID == Intrinsic::pow) {
1613  return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1614  }
1615  if (IntrinsicID == Intrinsic::copysign) {
1616  APFloat V1 = Op1->getValueAPF();
1617  APFloat V2 = Op2->getValueAPF();
1618  V1.copySign(V2);
1619  return ConstantFP::get(Ty->getContext(), V1);
1620  }
1621 
1622  if (IntrinsicID == Intrinsic::minnum) {
1623  const APFloat &C1 = Op1->getValueAPF();
1624  const APFloat &C2 = Op2->getValueAPF();
1625  return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1626  }
1627 
1628  if (IntrinsicID == Intrinsic::maxnum) {
1629  const APFloat &C1 = Op1->getValueAPF();
1630  const APFloat &C2 = Op2->getValueAPF();
1631  return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1632  }
1633 
1634  if (!TLI)
1635  return nullptr;
1636  if (Name == "pow" && TLI->has(LibFunc::pow))
1637  return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1638  if (Name == "fmod" && TLI->has(LibFunc::fmod))
1639  return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1640  if (Name == "atan2" && TLI->has(LibFunc::atan2))
1641  return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1642  } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1643  if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1644  return ConstantFP::get(Ty->getContext(),
1645  APFloat((float)std::pow((float)Op1V,
1646  (int)Op2C->getZExtValue())));
1647  if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1648  return ConstantFP::get(Ty->getContext(),
1649  APFloat((float)std::pow((float)Op1V,
1650  (int)Op2C->getZExtValue())));
1651  if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1652  return ConstantFP::get(Ty->getContext(),
1653  APFloat((double)std::pow((double)Op1V,
1654  (int)Op2C->getZExtValue())));
1655  }
1656  return nullptr;
1657  }
1658 
1659  if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1660  if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1661  switch (IntrinsicID) {
1662  default: break;
1663  case Intrinsic::sadd_with_overflow:
1664  case Intrinsic::uadd_with_overflow:
1665  case Intrinsic::ssub_with_overflow:
1666  case Intrinsic::usub_with_overflow:
1667  case Intrinsic::smul_with_overflow:
1668  case Intrinsic::umul_with_overflow: {
1669  APInt Res;
1670  bool Overflow;
1671  switch (IntrinsicID) {
1672  default: llvm_unreachable("Invalid case");
1673  case Intrinsic::sadd_with_overflow:
1674  Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1675  break;
1676  case Intrinsic::uadd_with_overflow:
1677  Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1678  break;
1679  case Intrinsic::ssub_with_overflow:
1680  Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1681  break;
1682  case Intrinsic::usub_with_overflow:
1683  Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1684  break;
1685  case Intrinsic::smul_with_overflow:
1686  Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1687  break;
1688  case Intrinsic::umul_with_overflow:
1689  Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1690  break;
1691  }
1692  Constant *Ops[] = {
1693  ConstantInt::get(Ty->getContext(), Res),
1694  ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1695  };
1696  return ConstantStruct::get(cast<StructType>(Ty), Ops);
1697  }
1698  case Intrinsic::cttz:
1699  if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1700  return UndefValue::get(Ty);
1701  return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1702  case Intrinsic::ctlz:
1703  if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1704  return UndefValue::get(Ty);
1705  return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1706  }
1707  }
1708 
1709  return nullptr;
1710  }
1711  return nullptr;
1712  }
1713 
1714  if (Operands.size() != 3)
1715  return nullptr;
1716 
1717  if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1718  if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1719  if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1720  switch (IntrinsicID) {
1721  default: break;
1722  case Intrinsic::fma:
1723  case Intrinsic::fmuladd: {
1724  APFloat V = Op1->getValueAPF();
1725  APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1726  Op3->getValueAPF(),
1728  if (s != APFloat::opInvalidOp)
1729  return ConstantFP::get(Ty->getContext(), V);
1730 
1731  return nullptr;
1732  }
1733  }
1734  }
1735  }
1736  }
1737 
1738  return nullptr;
1739 }
1740 
1741 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1742  VectorType *VTy,
1744  const TargetLibraryInfo *TLI) {
1746  SmallVector<Constant *, 4> Lane(Operands.size());
1747  Type *Ty = VTy->getElementType();
1748 
1749  for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1750  // Gather a column of constants.
1751  for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1752  Constant *Agg = Operands[J]->getAggregateElement(I);
1753  if (!Agg)
1754  return nullptr;
1755 
1756  Lane[J] = Agg;
1757  }
1758 
1759  // Use the regular scalar folding to simplify this column.
1760  Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1761  if (!Folded)
1762  return nullptr;
1763  Result[I] = Folded;
1764  }
1765 
1766  return ConstantVector::get(Result);
1767 }
1768 
1769 /// Attempt to constant fold a call to the specified function
1770 /// with the specified arguments, returning null if unsuccessful.
1771 Constant *
1773  const TargetLibraryInfo *TLI) {
1774  if (!F->hasName())
1775  return nullptr;
1776  StringRef Name = F->getName();
1777 
1778  Type *Ty = F->getReturnType();
1779 
1780  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1781  return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1782 
1783  return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1784 }
ConstantDataVector - A vector constant whose element type is a simple 1/2/4/8-byte integer or float/d...
Definition: Constants.h:742
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:679
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:236
static Constant * ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID, VectorType *VTy, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI)
ExtractValueInst - This instruction extracts a struct member or array element value from an aggregate...
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1327
Type * getSequentialElementType() const
Definition: Type.cpp:204
bool hasName() const
Definition: Value.h:228
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
static Constant * FoldReinterpretLoadFromConstPtr(Constant *C, const DataLayout &DL)
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a getelementptr constantexpr, return the constant value being addressed by the constant expression, or null if something is funny and we can't decide.
static const fltSemantics IEEEdouble
Definition: APFloat.h:133
bool canConstantFoldCallTo(const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
static Constant * ConstantFoldLoadThroughBitcast(ConstantExpr *CE, const DataLayout &DL)
unsigned getNumOperands() const
Definition: User.h:138
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:602
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2037
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:531
static PointerType * getInt32PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:291
void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1822
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1092
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2123
static Constant * ConstantFoldConvertToInt(const APFloat &Val, bool roundTowardZero, Type *Ty)
Attempt to fold an SSE floating point to integer conversion of a constant floating point...
opStatus
IEEE-754R 7: Default exception handling.
Definition: APFloat.h:166
bool isDoubleTy() const
isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:146
bool isPtrOrPtrVectorTy() const
isPtrOrPtrVectorTy - Return true if this is a pointer type or a vector of pointer types...
Definition: Type.h:222
Type * getReturnType() const
Definition: Function.cpp:233
F(f)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:472
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:61
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:240
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
Definition: Function.cpp:822
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:1990
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2269
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: Type.cpp:216
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:238
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Constant * ConstantFoldConstantExpression(const ConstantExpr *CE, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstantExpression - Attempt to fold the constant expression using the specified DataLayo...
APInt LLVM_ATTRIBUTE_UNUSED_RESULT zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1015
unsigned getOpcode() const
getOpcode - Return the opcode at the root of this constant expression
Definition: Constants.h:1144
op_iterator op_begin()
Definition: User.h:183
static Constant * ConstantFoldBinaryFP(double(*NativeFP)(double, double), double V, double W, Type *Ty)
static PointerType * getInt64PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:295
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2018
Type * getPointerElementType() const
Definition: Type.h:366
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2145
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:398
static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL)
If this constant is a constant offset from a global, return the global and the constant.
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:242
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:319
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:475
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1674
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...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:551
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"), clEnumValEnd))
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:308
bool has(LibFunc::Func F) const
Tests whether a library function is available.
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode, bool *) const
Definition: APFloat.cpp:2191
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2336
Constant * ConstantFoldLoadFromConstPtr(Constant *C, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1057
bool isSized(SmallPtrSetImpl< const Type * > *Visited=nullptr) const
isSized - Return true if it makes sense to take the size of this type.
Definition: Type.h:268
static PointerType * getInt16PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:287
uint64_t getIndexedOffset(Type *Ty, ArrayRef< Value * > Indices) const
Returns the offset from the beginning of the type for the specified indices.
Definition: DataLayout.cpp:721
static ConstantInt * ExtractElement(Constant *V, Constant *Idx)
Type * getVectorElementType() const
Definition: Type.h:364
static double getValueAsDouble(ConstantFP *Op)
void copySign(const APFloat &)
Definition: APFloat.cpp:1637
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:1868
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1727
static Constant * GetConstantFoldFPValue(double V, Type *Ty)
static Constant * StripPtrCastKeepAS(Constant *Ptr)
Strip the pointer casts, but preserve the address space information.
ConstantExpr - a constant value that is initialized with an expression using other constant values...
Definition: Constants.h:852
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
Definition: Type.h:125
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Definition: Operator.cpp:15
APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2025
bool isHalfTy() const
isHalfTy - Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:140
ArrayRef< T > slice(unsigned N) const
slice(n) - Chop off the first N elements of the array.
Definition: ArrayRef.h:165
ArrayType - Class to represent array types.
Definition: DerivedTypes.h:336
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:2012
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
static Constant * ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI)
double convertToDouble() const
Definition: APFloat.cpp:3116
bool isFloatingPointTy() const
isFloatingPointTy - Return true if this is one of the six floating point types
Definition: Type.h:159
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:217
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2047
unsigned getNumElements() const
Return the number of elements in the Vector type.
Definition: DerivedTypes.h:432
static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr, unsigned BytesLeft, const DataLayout &DL)
Recursive helper to read bits out of global.
Type * getElementType() const
Definition: DerivedTypes.h:323
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
PointerType - Class to represent pointers.
Definition: DerivedTypes.h:449
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:491
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1835
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
Definition: APFloat.h:122
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2191
bool isX86_MMXTy() const
isX86_MMXTy - Return true if this is X86 MMX.
Definition: Type.h:179
Constant * stripPointerCasts()
Definition: Constant.h:170
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isFloatTy() const
isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:143
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2317
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1895
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:233
opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode)
Definition: APFloat.cpp:1805
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:264
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2168
op_iterator op_end()
Definition: User.h:185
static Constant * ConstantFoldFP(double(*NativeFP)(double), double V, Type *Ty)
opStatus convert(const fltSemantics &, roundingMode, bool *)
APFloat::convert - convert a value of one floating point type to another.
Definition: APFloat.cpp:1972
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1137
Value * getOperand(unsigned i) const
Definition: User.h:118
SI Fold Operands
Class to represent integer types.
Definition: DerivedTypes.h:37
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1008
Constant * getAggregateElement(unsigned Elt) const
getAggregateElement - For aggregates (struct/array/vector) return the constant that corresponds to th...
Definition: Constants.cpp:250
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
Definition: Constants.cpp:230
unsigned getPredicate() const
getPredicate - Return the ICMP or FCMP predicate value.
Definition: Constants.cpp:1223
uint64_t getElementAsInteger(unsigned i) const
getElementAsInteger - If this is a sequential container of integers (of any size), return the specified element in the low bits of a uint64_t.
Definition: Constants.cpp:2723
bool isPointerTy() const
isPointerTy - True if this is an instance of PointerType.
Definition: Type.h:217
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1473
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:519
PointerType * getPointerTo(unsigned AddrSpace=0)
getPointerTo - Return a pointer to the current type.
Definition: Type.cpp:764
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
GetUnderlyingObject - This method strips off any GEP address adjustments and pointer casts from the s...
static const fltSemantics IEEEhalf
Definition: APFloat.h:131
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
Definition: APFloat.h:670
const T & back() const
back - Get the last element.
Definition: ArrayRef.h:143
bool isCompare() const
Return true if this is a compare constant expression.
Definition: Constants.cpp:1181
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:694
SequentialType - This is the superclass of the array, pointer and vector type classes.
Definition: DerivedTypes.h:310
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1648
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:304
static Constant * ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL)
roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition: APFloat.h:155
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
unsigned getIntegerBitWidth() const
Definition: Type.cpp:176
This is the shared class of boolean and integer constants.
Definition: Constants.h:47
static Constant * FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL)
Constant fold bitcast, symbolically evaluating it with DataLayout.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:388
unsigned getVectorNumElements() const
Definition: Type.cpp:212
unsigned getScalarSizeInBits() const LLVM_READONLY
getScalarSizeInBits - If this is a vector type, return the getPrimitiveSizeInBits value for the eleme...
Definition: Type.cpp:139
double Log2(double Value)
Log2 - This function returns the log base 2 of the specified value.
Definition: MathExtras.h:457
static Constant * SymbolicallyEvaluateGEP(Type *SrcTy, ArrayRef< Constant * > Ops, Type *ResultTy, const DataLayout &DL, const TargetLibraryInfo *TLI)
If we can symbolically evaluate the GEP constant expression, do so.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Constant * ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
Provides information about what library functions are available for the current target.
bool isVolatile() const
isVolatile - Return true if this is a load from a volatile memory location.
Definition: Instructions.h:232
uint64_t getSizeInBytes() const
Definition: DataLayout.h:481
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:243
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Definition: DataLayout.cpp:74
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1699
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:582
static Constant * get(Type *Ty, double V)
get() - This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in the specified type.
Definition: Constants.cpp:652
const fltSemantics & getFltSemantics() const
Definition: Type.h:166
bool isNullValue() const
isNullValue - Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:75
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:159
static Constant * SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1, const DataLayout &DL)
One of Op0/Op1 is a constant expression.
bool isAllOnesValue() const
isAllOnesValue - Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:88
VectorType - Class to represent vector types.
Definition: DerivedTypes.h:362
Class for arbitrary precision integers.
Definition: APInt.h:73
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool isIntegerTy() const
isIntegerTy - True if this is an instance of IntegerType.
Definition: Type.h:193
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1591
LLVM_ATTRIBUTE_UNUSED_RESULT 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:285
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2012
const Type * getScalarType() const LLVM_READONLY
getScalarType - If this is a vector type, return the element type, otherwise return 'this'...
Definition: Type.cpp:51
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1890
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
getIndexedType - Returns the type of the element that would be loaded with a load instruction with th...
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:185
bool isAggregateType() const
isAggregateType - Return true if the type is an aggregate type.
Definition: Type.h:260
APInt LLVM_ATTRIBUTE_UNUSED_RESULT udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1839
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
opStatus roundToIntegral(roundingMode)
Definition: APFloat.cpp:1849
bool isBinaryOp() const
Definition: Instruction.h:116
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1809
#define I(x, y, z)
Definition: MD5.cpp:54
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2321
float convertToFloat() const
Definition: APFloat.cpp:3107
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2329
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2005
static PointerType * getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS=0)
Definition: Type.cpp:275
const APFloat & getValueAPF() const
Definition: Constants.h:270
bool getConstantStringInfo(const Value *V, StringRef &Str, uint64_t Offset=0, bool TrimAtNul=true)
getConstantStringInfo - This function computes the length of a null-terminated C string pointed to by...
static Constant * CastGEPIndices(Type *SrcTy, ArrayRef< Constant * > Ops, Type *ResultTy, const DataLayout &DL, const TargetLibraryInfo *TLI)
If array indices are not pointer-sized integers, explicitly cast them so that they aren't implicitly ...
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
getPrimitiveSizeInBits - Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:121
LLVM Value Representation.
Definition: Value.h:69
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:112
static VectorType * get(Type *ElementType, unsigned NumElements)
VectorType::get - This static method is the primary way to construct an VectorType.
Definition: Type.cpp:713
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:507
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2215
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
Constant * ConstantFoldLoadThroughGEPIndices(Constant *C, ArrayRef< Constant * > Indices)
ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr indices (with an implied zero ...
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
const T * data() const
Definition: ArrayRef.h:131
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
Definition: APFloat.h:659
static Constant * ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL, const TargetLibraryInfo *TLI, SmallPtrSetImpl< ConstantExpr * > &FoldedOps)
Constant * ConstantFoldCall(Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
InsertValueInst - This instruction inserts a struct field of array element value into an aggregate va...
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110