blob: 5da29d6d2372624d1e94797360895b11315fa84d [file] [log] [blame]
Dan Gohman83e3c4f2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswellbd9d3702005-10-27 16:00:10 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswellbd9d3702005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman83e3c4f2009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
Chandler Carruthc2c50cd2013-01-02 09:10:48 +000012// Also, to supplement the basic IR ConstantExpr simplifications,
Dan Gohman83e3c4f2009-09-10 23:07:18 +000013// this file defines some additional folding routines that can make use of
Chandler Carruthc2c50cd2013-01-02 09:10:48 +000014// DataLayout information. These functions cannot go in IR due to library
Dan Gohman83e3c4f2009-09-10 23:07:18 +000015// dependency issues.
John Criswellbd9d3702005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000020#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
David Majnemerc1362812016-06-21 05:10:24 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/ADT/SmallVector.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000026#include "llvm/ADT/StringRef.h"
Chandler Carruthbda13492015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Analysis/ValueTracking.h"
Alp Tokerf4cf4042014-06-09 18:28:53 +000029#include "llvm/Config/config.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000030#include "llvm/IR/Constant.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000035#include "llvm/IR/GlobalValue.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000036#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000037#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
Craig Topper58c7fe62017-04-26 16:39:58 +000045#include "llvm/Support/KnownBits.h"
John Criswellbd9d3702005-10-27 16:00:10 +000046#include "llvm/Support/MathExtras.h"
Eugene Zelenkod0a33c42016-03-28 17:40:08 +000047#include <cassert>
John Criswellbd9d3702005-10-27 16:00:10 +000048#include <cerrno>
Eugene Zelenkod0a33c42016-03-28 17:40:08 +000049#include <cfenv>
Jeff Cohen97af7512006-12-02 02:22:01 +000050#include <cmath>
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000051#include <cstddef>
52#include <cstdint>
Alp Tokerf4cf4042014-06-09 18:28:53 +000053
John Criswellbd9d3702005-10-27 16:00:10 +000054using namespace llvm;
55
Eugene Zelenkod0a33c42016-03-28 17:40:08 +000056namespace {
57
Chris Lattner03dd25c2007-01-31 00:51:48 +000058//===----------------------------------------------------------------------===//
59// Constant Folding internal helper functions
60//===----------------------------------------------------------------------===//
61
Matt Arsenault749e5832016-12-02 02:26:02 +000062static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
63 Constant *C, Type *SrcEltTy,
64 unsigned NumSrcElts,
65 const DataLayout &DL) {
66 // Now that we know that the input value is a vector of integers, just shift
67 // and insert them into our result.
68 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
69 for (unsigned i = 0; i != NumSrcElts; ++i) {
70 Constant *Element;
71 if (DL.isLittleEndian())
72 Element = C->getAggregateElement(NumSrcElts - i - 1);
73 else
74 Element = C->getAggregateElement(i);
75
76 if (Element && isa<UndefValue>(Element)) {
77 Result <<= BitShift;
78 continue;
79 }
80
81 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
82 if (!ElementCI)
83 return ConstantExpr::getBitCast(C, DestTy);
84
85 Result <<= BitShift;
86 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
87 }
88
89 return nullptr;
90}
91
Matt Arsenault98b1edd2016-12-07 20:56:11 +000092/// Constant fold bitcast, symbolically evaluating it with DataLayout.
Sanjay Patele1656932014-10-02 15:13:22 +000093/// This always returns a non-null constant, but it may be a
Chris Lattner6333c392009-10-25 06:08:26 +000094/// ConstantExpr if unfoldable.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +000095Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000096 // Catch the obvious splat cases.
97 if (C->isNullValue() && !DestTy->isX86_MMXTy())
98 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopes5165ff92014-10-22 12:18:48 +000099 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000101 return Constant::getAllOnesValue(DestTy);
102
Matt Arsenault98b1edd2016-12-07 20:56:11 +0000103 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
104 // Handle a vector->scalar integer/fp cast.
105 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
106 unsigned NumSrcElts = VTy->getNumElements();
107 Type *SrcEltTy = VTy->getElementType();
Rafael Espindola04594ae2012-01-27 23:33:07 +0000108
Matt Arsenault98b1edd2016-12-07 20:56:11 +0000109 // If the vector is a vector of floating point, convert it to vector of int
110 // to simplify things.
111 if (SrcEltTy->isFloatingPointTy()) {
112 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
113 Type *SrcIVTy =
114 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
115 // Ask IR to do the conversion now that #elts line up.
116 C = ConstantExpr::getBitCast(C, SrcIVTy);
117 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000118
Matt Arsenault98b1edd2016-12-07 20:56:11 +0000119 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
120 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
121 SrcEltTy, NumSrcElts, DL))
122 return CE;
123
124 if (isa<IntegerType>(DestTy))
125 return ConstantInt::get(DestTy, Result);
126
127 APFloat FP(DestTy->getFltSemantics(), Result);
128 return ConstantFP::get(DestTy->getContext(), FP);
Rafael Espindola04594ae2012-01-27 23:33:07 +0000129 }
Rafael Espindola04594ae2012-01-27 23:33:07 +0000130 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000131
Nadav Rotem1c9fe032011-08-20 14:02:29 +0000132 // The code below only handles casts to vectors currently.
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000133 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper570e52c2014-04-15 04:59:12 +0000134 if (!DestVTy)
Chris Lattner93798da2009-10-25 06:15:37 +0000135 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000136
Chris Lattner93798da2009-10-25 06:15:37 +0000137 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
138 // vector so the code below can handle it uniformly.
139 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
140 Constant *Ops = C; // don't take the address of C!
Mehdi Amini529919f2015-03-10 02:37:25 +0000141 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattner93798da2009-10-25 06:15:37 +0000142 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000143
Chris Lattner6333c392009-10-25 06:08:26 +0000144 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner6b0dc922012-01-26 21:37:55 +0000145 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner6333c392009-10-25 06:08:26 +0000146 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000147
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000148 // If the element types match, IR can fold it.
Chris Lattner6333c392009-10-25 06:08:26 +0000149 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner6b0dc922012-01-26 21:37:55 +0000150 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner6333c392009-10-25 06:08:26 +0000151 if (NumDstElt == NumSrcElt)
152 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000153
Chris Lattner6b0dc922012-01-26 21:37:55 +0000154 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000155 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000156
157 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner6333c392009-10-25 06:08:26 +0000158 // requires endianness information to do the right thing. For example,
159 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
160 // folds to (little endian):
161 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
162 // and to (big endian):
163 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000164
Chris Lattner6333c392009-10-25 06:08:26 +0000165 // First thing is first. We only want to think about integer here, so if
166 // we have something in FP form, recast it as integer.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000167 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner6333c392009-10-25 06:08:26 +0000168 // Fold to an vector of integers with same size as our FP type.
169 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000170 Type *DestIVTy =
Chris Lattner6333c392009-10-25 06:08:26 +0000171 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172 // Recursively handle this integer conversion, if possible.
Mehdi Amini529919f2015-03-10 02:37:25 +0000173 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000174
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000175 // Finally, IR can handle this now that #elts line up.
Chris Lattner6333c392009-10-25 06:08:26 +0000176 return ConstantExpr::getBitCast(C, DestTy);
177 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000178
Chris Lattner6333c392009-10-25 06:08:26 +0000179 // Okay, we know the destination is integer, if the input is FP, convert
180 // it to integer first.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000181 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner6333c392009-10-25 06:08:26 +0000182 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 Type *SrcIVTy =
Chris Lattner6333c392009-10-25 06:08:26 +0000184 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000185 // Ask IR to do the conversion now that #elts line up.
Chris Lattner6333c392009-10-25 06:08:26 +0000186 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000187 // If IR wasn't able to fold it, bail out.
Chris Lattner6b0dc922012-01-26 21:37:55 +0000188 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
189 !isa<ConstantDataVector>(C))
Chris Lattner6333c392009-10-25 06:08:26 +0000190 return C;
191 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000192
Chris Lattner6333c392009-10-25 06:08:26 +0000193 // Now we know that the input and output vectors are both integer vectors
194 // of the same size, and that their #elements is not the same. Do the
195 // conversion here, which depends on whether the input or output has
196 // more elements.
Mehdi Amini529919f2015-03-10 02:37:25 +0000197 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000198
Chris Lattner6333c392009-10-25 06:08:26 +0000199 SmallVector<Constant*, 32> Result;
200 if (NumDstElt < NumSrcElt) {
201 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
202 Constant *Zero = Constant::getNullValue(DstEltTy);
203 unsigned Ratio = NumSrcElt/NumDstElt;
204 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
205 unsigned SrcElt = 0;
206 for (unsigned i = 0; i != NumDstElt; ++i) {
207 // Build each element of the result.
208 Constant *Elt = Zero;
209 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
210 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemerb9bd76d2016-07-29 04:06:09 +0000211 Constant *Src = C->getAggregateElement(SrcElt++);
212 if (Src && isa<UndefValue>(Src))
David Majnemer7e8508b2016-07-29 18:48:27 +0000213 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemerb9bd76d2016-07-29 04:06:09 +0000214 else
215 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner6333c392009-10-25 06:08:26 +0000216 if (!Src) // Reject constantexpr elements.
217 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000218
Chris Lattner6333c392009-10-25 06:08:26 +0000219 // Zero extend the element to the right size.
220 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000221
Chris Lattner6333c392009-10-25 06:08:26 +0000222 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000223 Src = ConstantExpr::getShl(Src,
Chris Lattner6333c392009-10-25 06:08:26 +0000224 ConstantInt::get(Src->getType(), ShiftAmt));
225 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000226
Chris Lattner6333c392009-10-25 06:08:26 +0000227 // Mix it in.
228 Elt = ConstantExpr::getOr(Elt, Src);
229 }
230 Result.push_back(Elt);
231 }
Chris Lattner6b0dc922012-01-26 21:37:55 +0000232 return ConstantVector::get(Result);
233 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000234
Chris Lattner6b0dc922012-01-26 21:37:55 +0000235 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
236 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Amini529919f2015-03-10 02:37:25 +0000237 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000238
Chris Lattner6b0dc922012-01-26 21:37:55 +0000239 // Loop over each source value, expanding into multiple results.
240 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagiod9dffbd2016-09-13 14:50:47 +0000241 auto *Element = C->getAggregateElement(i);
242
243 if (!Element) // Reject constantexpr elements.
244 return ConstantExpr::getBitCast(C, DestTy);
245
246 if (isa<UndefValue>(Element)) {
247 // Correctly Propagate undef values.
248 Result.append(Ratio, UndefValue::get(DstEltTy));
249 continue;
250 }
251
252 auto *Src = dyn_cast<ConstantInt>(Element);
253 if (!Src)
Chris Lattner6b0dc922012-01-26 21:37:55 +0000254 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000255
Chris Lattner6b0dc922012-01-26 21:37:55 +0000256 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
257 for (unsigned j = 0; j != Ratio; ++j) {
258 // Shift the piece of the value into the right place, depending on
259 // endianness.
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000260 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner6b0dc922012-01-26 21:37:55 +0000261 ConstantInt::get(Src->getType(), ShiftAmt));
262 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000263
Bruno Cardoso Lopes5165ff92014-10-22 12:18:48 +0000264 // Truncate the element to an integer with the same pointer size and
265 // convert the element back to a pointer using a inttoptr.
266 if (DstEltTy->isPointerTy()) {
267 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
268 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
269 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
270 continue;
271 }
272
Chris Lattner6b0dc922012-01-26 21:37:55 +0000273 // Truncate and remember this piece.
274 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner6333c392009-10-25 06:08:26 +0000275 }
276 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000277
Chris Lattner2ca5c862011-02-15 00:14:00 +0000278 return ConstantVector::get(Result);
Chris Lattner6333c392009-10-25 06:08:26 +0000279}
280
Peter Collingbourne50119132016-04-22 20:40:10 +0000281} // end anonymous namespace
282
Sanjay Patele1656932014-10-02 15:13:22 +0000283/// If this constant is a constant offset from a global, return the global and
284/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne50119132016-04-22 20:40:10 +0000285bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
286 APInt &Offset, const DataLayout &DL) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000287 // Trivial case, constant is the global.
288 if ((GV = dyn_cast<GlobalValue>(C))) {
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000289 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
Matt Arsenault896a8852013-11-04 20:46:52 +0000290 Offset = APInt(BitWidth, 0);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000291 return true;
292 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000293
Chris Lattner03dd25c2007-01-31 00:51:48 +0000294 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000295 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000296 if (!CE) return false;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000297
Chris Lattner03dd25c2007-01-31 00:51:48 +0000298 // Look through ptr->int and ptr->ptr casts.
299 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenaultfd8928d2015-07-27 18:31:03 +0000300 CE->getOpcode() == Instruction::BitCast)
Mehdi Amini529919f2015-03-10 02:37:25 +0000301 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000302
303 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000304 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenault896a8852013-11-04 20:46:52 +0000305 if (!GEP)
306 return false;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000307
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000308 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
Matt Arsenault896a8852013-11-04 20:46:52 +0000309 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000310
Matt Arsenault896a8852013-11-04 20:46:52 +0000311 // If the base isn't a global+constant, we aren't either.
Mehdi Amini529919f2015-03-10 02:37:25 +0000312 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenault896a8852013-11-04 20:46:52 +0000313 return false;
314
315 // Otherwise, add any offset that our operands provide.
Mehdi Amini529919f2015-03-10 02:37:25 +0000316 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenault896a8852013-11-04 20:46:52 +0000317 return false;
318
319 Offset = TmpOffset;
320 return true;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000321}
322
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000323Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
324 const DataLayout &DL) {
325 do {
326 Type *SrcTy = C->getType();
327
328 // If the type sizes are the same and a cast is legal, just directly
329 // cast the constant.
330 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
331 Instruction::CastOps Cast = Instruction::BitCast;
332 // If we are going from a pointer to int or vice versa, we spell the cast
333 // differently.
334 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
335 Cast = Instruction::IntToPtr;
336 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
337 Cast = Instruction::PtrToInt;
338
339 if (CastInst::castIsValid(Cast, C, DestTy))
340 return ConstantExpr::getCast(Cast, C, DestTy);
341 }
342
343 // If this isn't an aggregate type, there is nothing we can do to drill down
344 // and find a bitcastable constant.
345 if (!SrcTy->isAggregateType())
346 return nullptr;
347
348 // We're simulating a load through a pointer that was bitcast to point to
349 // a different type, so we can try to walk down through the initial
Nikita Popov2070fbd2018-12-11 20:29:16 +0000350 // elements of an aggregate to see if some part of the aggregate is
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000351 // castable to implement the "load" semantic model.
Nikita Popov2070fbd2018-12-11 20:29:16 +0000352 if (SrcTy->isStructTy()) {
353 // Struct types might have leading zero-length elements like [0 x i32],
354 // which are certainly not what we are looking for, so skip them.
355 unsigned Elem = 0;
356 Constant *ElemC;
357 do {
358 ElemC = C->getAggregateElement(Elem++);
359 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()) == 0);
360 C = ElemC;
361 } else {
362 C = C->getAggregateElement(0u);
363 }
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000364 } while (C);
365
366 return nullptr;
367}
368
Peter Collingbourne50119132016-04-22 20:40:10 +0000369namespace {
370
Sanjay Patele1656932014-10-02 15:13:22 +0000371/// Recursive helper to read bits out of global. C is the constant being copied
372/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
373/// results into and BytesLeft is the number of bytes left in
Mehdi Amini529919f2015-03-10 02:37:25 +0000374/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000375bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
376 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000377 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000378 "Out of range access");
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000379
Chris Lattnerc7b13822009-10-24 05:27:19 +0000380 // If this element is zero or undefined, we can just return since *CurPtr is
381 // zero initialized.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000382 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
383 return true;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000384
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000385 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000386 if (CI->getBitWidth() > 64 ||
387 (CI->getBitWidth() & 7) != 0)
388 return false;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000389
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000390 uint64_t Val = CI->getZExtValue();
391 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000392
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000393 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000394 int n = ByteOffset;
Mehdi Amini529919f2015-03-10 02:37:25 +0000395 if (!DL.isLittleEndian())
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000396 n = IntBytes - n - 1;
397 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000398 ++ByteOffset;
399 }
400 return true;
401 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000402
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000403 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000404 if (CFP->getType()->isDoubleTy()) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000405 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
406 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000407 }
408 if (CFP->getType()->isFloatTy()){
Mehdi Amini529919f2015-03-10 02:37:25 +0000409 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
410 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000411 }
Owen Anderson42258e02013-02-06 22:43:31 +0000412 if (CFP->getType()->isHalfTy()){
Mehdi Amini529919f2015-03-10 02:37:25 +0000413 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
414 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Anderson42258e02013-02-06 22:43:31 +0000415 }
Chris Lattnerc7b13822009-10-24 05:27:19 +0000416 return false;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000417 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000418
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000419 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000420 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000421 unsigned Index = SL->getElementContainingOffset(ByteOffset);
422 uint64_t CurEltOffset = SL->getElementOffset(Index);
423 ByteOffset -= CurEltOffset;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000424
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +0000425 while (true) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000426 // If the element access is to the element itself and not to tail padding,
427 // read the bytes from the element.
Mehdi Amini529919f2015-03-10 02:37:25 +0000428 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000429
430 if (ByteOffset < EltSize &&
431 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Amini529919f2015-03-10 02:37:25 +0000432 BytesLeft, DL))
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000433 return false;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000434
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000435 ++Index;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000436
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000437 // Check to see if we read from the last struct element, if so we're done.
438 if (Index == CS->getType()->getNumElements())
439 return true;
440
441 // If we read all of the bytes we needed from this element we're done.
442 uint64_t NextEltOffset = SL->getElementOffset(Index);
443
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000444 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000445 return true;
446
447 // Move to the next element of the struct.
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000448 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
449 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000450 ByteOffset = 0;
451 CurEltOffset = NextEltOffset;
452 }
453 // not reached.
454 }
455
Chris Lattnera1f00f42012-01-25 06:48:06 +0000456 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
457 isa<ConstantDataSequential>(C)) {
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000458 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Amini529919f2015-03-10 02:37:25 +0000459 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000460 uint64_t Index = ByteOffset / EltSize;
461 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattnera1f00f42012-01-25 06:48:06 +0000462 uint64_t NumElts;
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000463 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattnera1f00f42012-01-25 06:48:06 +0000464 NumElts = AT->getNumElements();
465 else
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000466 NumElts = C->getType()->getVectorNumElements();
Duncan Sandsf2124cc2012-07-25 09:14:54 +0000467
Chris Lattnera1f00f42012-01-25 06:48:06 +0000468 for (; Index != NumElts; ++Index) {
469 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Amini529919f2015-03-10 02:37:25 +0000470 BytesLeft, DL))
Chris Lattnera1f00f42012-01-25 06:48:06 +0000471 return false;
Duncan Sandsf2124cc2012-07-25 09:14:54 +0000472
473 uint64_t BytesWritten = EltSize - Offset;
474 assert(BytesWritten <= EltSize && "Not indexing into this element?");
475 if (BytesWritten >= BytesLeft)
Chris Lattnera1f00f42012-01-25 06:48:06 +0000476 return true;
Duncan Sandsf2124cc2012-07-25 09:14:54 +0000477
Chris Lattnera1f00f42012-01-25 06:48:06 +0000478 Offset = 0;
Duncan Sandsf2124cc2012-07-25 09:14:54 +0000479 BytesLeft -= BytesWritten;
480 CurPtr += BytesWritten;
Chris Lattnera1f00f42012-01-25 06:48:06 +0000481 }
482 return true;
483 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000484
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000485 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlsson5d43ff42011-02-06 20:22:49 +0000486 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Amini529919f2015-03-10 02:37:25 +0000487 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000488 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Amini529919f2015-03-10 02:37:25 +0000489 BytesLeft, DL);
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000490 }
Anders Carlsson6475d942011-02-06 20:11:56 +0000491 }
492
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000493 // Otherwise, unknown initializer type.
494 return false;
495}
496
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000497Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
498 const DataLayout &DL) {
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000499 auto *PTy = cast<PointerType>(C->getType());
500 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000501
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000502 // If this isn't an integer load we can't fold it directly.
503 if (!IntType) {
Matt Arsenault80f495a2013-08-20 21:20:04 +0000504 unsigned AS = PTy->getAddressSpace();
505
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000506 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattner17f0cd32009-10-23 06:57:37 +0000507 // and then bitcast the result. This can be useful for union cases. Note
508 // that address spaces don't matter here since we're not going to result in
509 // an actual new load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000510 Type *MapTy;
Owen Anderson42258e02013-02-06 22:43:31 +0000511 if (LoadTy->isHalfTy())
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000512 MapTy = Type::getInt16Ty(C->getContext());
Owen Anderson42258e02013-02-06 22:43:31 +0000513 else if (LoadTy->isFloatTy())
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000514 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattner17f0cd32009-10-23 06:57:37 +0000515 else if (LoadTy->isDoubleTy())
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000516 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands1df98592010-02-16 11:11:14 +0000517 else if (LoadTy->isVectorTy()) {
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000518 MapTy = PointerType::getIntNTy(C->getContext(),
519 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattner17f0cd32009-10-23 06:57:37 +0000520 } else
Craig Topper570e52c2014-04-15 04:59:12 +0000521 return nullptr;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000522
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000523 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
524 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Amini529919f2015-03-10 02:37:25 +0000525 return FoldBitCast(Res, LoadTy, DL);
Craig Topper570e52c2014-04-15 04:59:12 +0000526 return nullptr;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000527 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000528
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000529 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000530 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper570e52c2014-04-15 04:59:12 +0000531 return nullptr;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000532
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000533 GlobalValue *GVal;
David Majnemer46fef912016-07-13 23:33:07 +0000534 APInt OffsetAI;
535 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper570e52c2014-04-15 04:59:12 +0000536 return nullptr;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000537
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000538 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattnerc7b13822009-10-24 05:27:19 +0000539 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000540 !GV->getInitializer()->getType()->isSized())
Craig Topper570e52c2014-04-15 04:59:12 +0000541 return nullptr;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000542
David Majnemer46fef912016-07-13 23:33:07 +0000543 int64_t Offset = OffsetAI.getSExtValue();
544 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000545
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000546 // If we're not accessing anything in this constant, the result is undefined.
David Majnemer46fef912016-07-13 23:33:07 +0000547 if (Offset + BytesLoaded <= 0)
548 return UndefValue::get(IntType);
549
550 // If we're not accessing anything in this constant, the result is undefined.
551 if (Offset >= InitializerSize)
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000552 return UndefValue::get(IntType);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000553
Chris Lattner739208a2009-10-23 06:50:36 +0000554 unsigned char RawBytes[32] = {0};
David Majnemer46fef912016-07-13 23:33:07 +0000555 unsigned char *CurPtr = RawBytes;
556 unsigned BytesLeft = BytesLoaded;
557
558 // If we're loading off the beginning of the global, some bytes may be valid.
559 if (Offset < 0) {
560 CurPtr += -Offset;
561 BytesLeft += Offset;
562 Offset = 0;
563 }
564
565 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper570e52c2014-04-15 04:59:12 +0000566 return nullptr;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000567
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000568 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Amini529919f2015-03-10 02:37:25 +0000569 if (DL.isLittleEndian()) {
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000570 ResultVal = RawBytes[BytesLoaded - 1];
571 for (unsigned i = 1; i != BytesLoaded; ++i) {
572 ResultVal <<= 8;
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000573 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000574 }
575 } else {
576 ResultVal = RawBytes[0];
577 for (unsigned i = 1; i != BytesLoaded; ++i) {
578 ResultVal <<= 8;
579 ResultVal |= RawBytes[i];
580 }
Chris Lattner739208a2009-10-23 06:50:36 +0000581 }
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000582
Chris Lattner739208a2009-10-23 06:50:36 +0000583 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000584}
585
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000586Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
587 const DataLayout &DL) {
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000588 auto *SrcPtr = CE->getOperand(0);
589 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
590 if (!SrcPtrTy)
Chandler Carruthca323cf2014-05-15 09:56:28 +0000591 return nullptr;
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000592 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carruthca323cf2014-05-15 09:56:28 +0000593
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000594 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carruthca323cf2014-05-15 09:56:28 +0000595 if (!C)
596 return nullptr;
597
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000598 return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
Chandler Carruthca323cf2014-05-15 09:56:28 +0000599}
600
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000601} // end anonymous namespace
602
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000603Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Amini529919f2015-03-10 02:37:25 +0000604 const DataLayout &DL) {
Chris Lattner878e4942009-10-22 06:25:11 +0000605 // First, try the easy cases:
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000606 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner878e4942009-10-22 06:25:11 +0000607 if (GV->isConstant() && GV->hasDefinitiveInitializer())
608 return GV->getInitializer();
609
David Majnemer1b072f22015-07-22 22:29:30 +0000610 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Dasc9e3e3c2016-04-08 00:48:30 +0000611 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000612 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemer1b072f22015-07-22 22:29:30 +0000613
Chris Lattnere00c43f2009-10-22 06:44:07 +0000614 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000615 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000616 if (!CE)
Craig Topper570e52c2014-04-15 04:59:12 +0000617 return nullptr;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000618
Chris Lattnere00c43f2009-10-22 06:44:07 +0000619 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000620 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000621 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000622 if (Constant *V =
Chris Lattnere00c43f2009-10-22 06:44:07 +0000623 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
624 return V;
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000625 }
626 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000627 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000628
Chandler Carruthca323cf2014-05-15 09:56:28 +0000629 if (CE->getOpcode() == Instruction::BitCast)
Eugene Leviant0cfc08d2018-03-13 10:19:50 +0000630 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
Chandler Carruthca323cf2014-05-15 09:56:28 +0000631 return LoadedC;
632
Chris Lattnere00c43f2009-10-22 06:44:07 +0000633 // Instead of loading constant c string, use corresponding integer value
634 // directly if string length is small enough.
Chris Lattner18c7f802012-02-05 02:29:43 +0000635 StringRef Str;
Mehdi Amini529919f2015-03-10 02:37:25 +0000636 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemerc1362812016-06-21 05:10:24 +0000637 size_t StrLen = Str.size();
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000638 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnereae28952010-07-12 00:22:51 +0000639 // Replace load with immediate integer if the result is an integer or fp
640 // value.
641 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth490b8f52010-07-12 06:47:05 +0000642 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000643 APInt StrVal(NumBits, 0);
644 APInt SingleChar(NumBits, 0);
Mehdi Amini529919f2015-03-10 02:37:25 +0000645 if (DL.isLittleEndian()) {
David Majnemerc1362812016-06-21 05:10:24 +0000646 for (unsigned char C : reverse(Str.bytes())) {
647 SingleChar = static_cast<uint64_t>(C);
Chris Lattner62d327e2009-10-22 06:38:35 +0000648 StrVal = (StrVal << 8) | SingleChar;
649 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000650 } else {
David Majnemerc1362812016-06-21 05:10:24 +0000651 for (unsigned char C : Str.bytes()) {
652 SingleChar = static_cast<uint64_t>(C);
Chris Lattnere00c43f2009-10-22 06:44:07 +0000653 StrVal = (StrVal << 8) | SingleChar;
654 }
655 // Append NULL at the end.
656 SingleChar = 0;
657 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner62d327e2009-10-22 06:38:35 +0000658 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000659
Chris Lattnereae28952010-07-12 00:22:51 +0000660 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
661 if (Ty->isFloatingPointTy())
662 Res = ConstantExpr::getBitCast(Res, Ty);
663 return Res;
Chris Lattner62d327e2009-10-22 06:38:35 +0000664 }
Chris Lattner878e4942009-10-22 06:25:11 +0000665 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000666
Chris Lattnere00c43f2009-10-22 06:44:07 +0000667 // If this load comes from anywhere in a constant global, and if the global
668 // is all undef or zero, we know what it loads.
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000669 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000670 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000671 if (GV->getInitializer()->isNullValue())
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000672 return Constant::getNullValue(Ty);
Chris Lattnere00c43f2009-10-22 06:44:07 +0000673 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000674 return UndefValue::get(Ty);
Chris Lattnere00c43f2009-10-22 06:44:07 +0000675 }
676 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000677
NAKAMURA Takumi562b1d82012-11-08 20:34:25 +0000678 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000679 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner878e4942009-10-22 06:25:11 +0000680}
681
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000682namespace {
683
684Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper570e52c2014-04-15 04:59:12 +0000685 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000686
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000687 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu0aa1a482016-01-22 01:17:26 +0000688 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000689
Craig Topper570e52c2014-04-15 04:59:12 +0000690 return nullptr;
Chris Lattner878e4942009-10-22 06:25:11 +0000691}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000692
Sanjay Patele1656932014-10-02 15:13:22 +0000693/// One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000694/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky9d901632013-02-14 03:23:37 +0000695/// these together. If target data info is available, it is provided as DL,
696/// otherwise DL is null.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000697Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
698 const DataLayout &DL) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000699 // SROA
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000700
Chris Lattner03dd25c2007-01-31 00:51:48 +0000701 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
702 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
703 // bits.
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000704
Mehdi Amini529919f2015-03-10 02:37:25 +0000705 if (Opc == Instruction::And) {
Craig Toppere3a11162017-05-24 16:53:07 +0000706 KnownBits Known0 = computeKnownBits(Op0, DL);
707 KnownBits Known1 = computeKnownBits(Op1, DL);
Craig Topper58c7fe62017-04-26 16:39:58 +0000708 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
Nick Lewycky9d901632013-02-14 03:23:37 +0000709 // All the bits of Op0 that the 'and' could be masking are already zero.
710 return Op0;
711 }
Craig Topper58c7fe62017-04-26 16:39:58 +0000712 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
Nick Lewycky9d901632013-02-14 03:23:37 +0000713 // All the bits of Op1 that the 'and' could be masking are already zero.
714 return Op1;
715 }
716
Craig Topper64c8cdf2017-05-03 23:12:29 +0000717 Known0.Zero |= Known1.Zero;
718 Known0.One &= Known1.One;
719 if (Known0.isConstant())
720 return ConstantInt::get(Op0->getType(), Known0.getConstant());
Nick Lewycky9d901632013-02-14 03:23:37 +0000721 }
722
Chris Lattner03dd25c2007-01-31 00:51:48 +0000723 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
724 // constant. This happens frequently when iterating over a global array.
Mehdi Amini529919f2015-03-10 02:37:25 +0000725 if (Opc == Instruction::Sub) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000726 GlobalValue *GV1, *GV2;
Matt Arsenault896a8852013-11-04 20:46:52 +0000727 APInt Offs1, Offs2;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000728
Mehdi Amini529919f2015-03-10 02:37:25 +0000729 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
730 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
731 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenault180df812013-09-12 01:07:58 +0000732
Chris Lattner03dd25c2007-01-31 00:51:48 +0000733 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramerfaf601e2013-02-05 19:04:36 +0000734 // PtrToInt may change the bitwidth so we have convert to the right size
735 // first.
736 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
737 Offs2.zextOrTrunc(OpSize));
Chris Lattner03dd25c2007-01-31 00:51:48 +0000738 }
739 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000740
Craig Topper570e52c2014-04-15 04:59:12 +0000741 return nullptr;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000742}
743
Sanjay Patele1656932014-10-02 15:13:22 +0000744/// If array indices are not pointer-sized integers, explicitly cast them so
745/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000746Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourneca668e12016-11-10 22:34:55 +0000747 Type *ResultTy, Optional<unsigned> InRangeIndex,
748 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000749 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischer83dc0632016-12-08 17:22:35 +0000750 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohman4f8eea82010-02-01 18:27:38 +0000751
752 bool Any = false;
753 SmallVector<Constant*, 32> NewIdxs;
Jay Foad1d2f5692011-07-19 13:32:40 +0000754 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000755 if ((i == 1 ||
Keno Fischer83dc0632016-12-08 17:22:35 +0000756 !isa<StructType>(GetElementPtrInst::getIndexedType(
757 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kuperstein57ab8272016-12-21 17:34:21 +0000758 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000759 Any = true;
Michael Kuperstein57ab8272016-12-21 17:34:21 +0000760 Type *NewType = Ops[i]->getType()->isVectorTy()
761 ? IntPtrTy
762 : IntPtrTy->getScalarType();
Dan Gohman4f8eea82010-02-01 18:27:38 +0000763 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
764 true,
Michael Kuperstein57ab8272016-12-21 17:34:21 +0000765 NewType,
Dan Gohman4f8eea82010-02-01 18:27:38 +0000766 true),
Michael Kuperstein57ab8272016-12-21 17:34:21 +0000767 Ops[i], NewType));
Dan Gohman4f8eea82010-02-01 18:27:38 +0000768 } else
769 NewIdxs.push_back(Ops[i]);
770 }
Dan Gohman4f8eea82010-02-01 18:27:38 +0000771
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000772 if (!Any)
Craig Topper570e52c2014-04-15 04:59:12 +0000773 return nullptr;
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000774
Peter Collingbourneca668e12016-11-10 22:34:55 +0000775 Constant *C = ConstantExpr::getGetElementPtr(
776 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemere43ff142016-07-29 03:27:26 +0000777 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
778 C = Folded;
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000779
Dan Gohman4f8eea82010-02-01 18:27:38 +0000780 return C;
781}
782
Nadav Rotem97baaea2012-07-30 07:25:20 +0000783/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000784Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem97baaea2012-07-30 07:25:20 +0000785 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000786 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindolacfee6c42014-06-04 19:01:48 +0000787 Ptr = Ptr->stripPointerCasts();
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000788 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem97baaea2012-07-30 07:25:20 +0000789
Eduard Burtescu47506352016-01-21 23:42:06 +0000790 ElemTy = NewPtrTy->getPointerElementType();
791
Nadav Rotem97baaea2012-07-30 07:25:20 +0000792 // Preserve the address space number of the pointer.
793 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu47506352016-01-21 23:42:06 +0000794 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenault59d3ae62013-11-15 01:34:59 +0000795 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem97baaea2012-07-30 07:25:20 +0000796 }
797 return Ptr;
798}
799
Sanjay Patele1656932014-10-02 15:13:22 +0000800/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000801Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
802 ArrayRef<Constant *> Ops,
803 const DataLayout &DL,
804 const TargetLibraryInfo *TLI) {
Peter Collingbourneca668e12016-11-10 22:34:55 +0000805 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourned703e442016-11-22 01:03:40 +0000806 bool InBounds = GEP->isInBounds();
Peter Collingbourneca668e12016-11-10 22:34:55 +0000807
Eduard Burtescu47506352016-01-21 23:42:06 +0000808 Type *SrcElemTy = GEP->getSourceElementType();
809 Type *ResElemTy = GEP->getResultElementType();
810 Type *ResTy = GEP->getType();
811 if (!SrcElemTy->isSized())
812 return nullptr;
813
Peter Collingbourneca668e12016-11-10 22:34:55 +0000814 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
815 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu47506352016-01-21 23:42:06 +0000816 return C;
817
Chris Lattner03dd25c2007-01-31 00:51:48 +0000818 Constant *Ptr = Ops[0];
Eduard Burtescu47506352016-01-21 23:42:06 +0000819 if (!Ptr->getType()->isPointerTy())
Craig Topper570e52c2014-04-15 04:59:12 +0000820 return nullptr;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000821
Mehdi Amini529919f2015-03-10 02:37:25 +0000822 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattner268e7d72008-05-08 04:54:43 +0000823
824 // If this is a constant expr gep that is effectively computing an
825 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foad1d2f5692011-07-19 13:32:40 +0000826 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000827 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000828
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000829 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
830 // "inttoptr (sub (ptrtoint Ptr), V)"
831 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
832 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
833 assert((!CE || CE->getType() == IntPtrTy) &&
834 "CastGEPIndices didn't canonicalize index types!");
835 if (CE && CE->getOpcode() == Instruction::Sub &&
836 CE->getOperand(0)->isNullValue()) {
837 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
838 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
839 Res = ConstantExpr::getIntToPtr(Res, ResTy);
840 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
841 Res = FoldedRes;
842 return Res;
843 }
Chris Lattner8cd4efb2011-01-06 06:19:46 +0000844 }
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000845 return nullptr;
Chris Lattner8cd4efb2011-01-06 06:19:46 +0000846 }
Nadav Rotem97baaea2012-07-30 07:25:20 +0000847
Mehdi Amini529919f2015-03-10 02:37:25 +0000848 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foad8fbbb392011-07-19 14:01:37 +0000849 APInt Offset =
Mehdi Amini529919f2015-03-10 02:37:25 +0000850 APInt(BitWidth,
Eduard Burtescua2694782016-01-22 03:08:27 +0000851 DL.getIndexedOffsetInType(
852 SrcElemTy,
Mehdi Amini529919f2015-03-10 02:37:25 +0000853 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu47506352016-01-21 23:42:06 +0000854 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman0891d752010-03-10 19:31:51 +0000855
856 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000857 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourneca668e12016-11-10 22:34:55 +0000858 InnermostGEP = GEP;
Peter Collingbourned703e442016-11-22 01:03:40 +0000859 InBounds &= GEP->isInBounds();
Peter Collingbourneca668e12016-11-10 22:34:55 +0000860
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000861 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands890edda2010-03-12 17:55:20 +0000862
863 // Do not try the incorporate the sub-GEP if some index is not a number.
864 bool AllConstantInt = true;
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000865 for (Value *NestedOp : NestedOps)
866 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands890edda2010-03-12 17:55:20 +0000867 AllConstantInt = false;
868 break;
869 }
870 if (!AllConstantInt)
871 break;
872
Dan Gohman0891d752010-03-10 19:31:51 +0000873 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescua2694782016-01-22 03:08:27 +0000874 SrcElemTy = GEP->getSourceElementType();
875 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu47506352016-01-21 23:42:06 +0000876 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman0891d752010-03-10 19:31:51 +0000877 }
878
Dan Gohmande0e5872009-08-19 18:18:36 +0000879 // If the base value for this address is a literal integer value, fold the
880 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohman40b037e2010-03-18 19:34:33 +0000881 APInt BasePtr(BitWidth, 0);
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000882 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000883 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000884 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad40f8f622010-12-07 08:25:19 +0000885 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000886 }
887 }
888
Sanjoy Dasc5201e32016-08-05 19:23:29 +0000889 auto *PTy = cast<PointerType>(Ptr->getType());
890 if ((Ptr->isNullValue() || BasePtr != 0) &&
891 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaultb36f2f72013-08-12 22:56:15 +0000892 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu47506352016-01-21 23:42:06 +0000893 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohmande0e5872009-08-19 18:18:36 +0000894 }
895
896 // Otherwise form a regular getelementptr. Recompute the indices so that
897 // we eliminate over-indexing of the notional static type array bounds.
898 // This makes it easy to determine if the getelementptr is "inbounds".
899 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Dasc5201e32016-08-05 19:23:29 +0000900 Type *Ty = PTy;
Matt Arsenault80f495a2013-08-20 21:20:04 +0000901 SmallVector<Constant *, 32> NewIdxs;
902
Dan Gohman3d013342009-08-19 22:46:59 +0000903 do {
Eduard Burtescu47506352016-01-21 23:42:06 +0000904 if (!Ty->isStructTy()) {
905 if (Ty->isPointerTy()) {
Chris Lattnere568fa22009-12-03 01:05:45 +0000906 // The only pointer indexing we'll do is on the first index of the GEP.
907 if (!NewIdxs.empty())
908 break;
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000909
Eduard Burtescu47506352016-01-21 23:42:06 +0000910 Ty = SrcElemTy;
911
Chris Lattnere568fa22009-12-03 01:05:45 +0000912 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu47506352016-01-21 23:42:06 +0000913 if (!Ty->isSized())
Craig Topper570e52c2014-04-15 04:59:12 +0000914 return nullptr;
Eduard Burtescu47506352016-01-21 23:42:06 +0000915 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
916 Ty = ATy->getElementType();
917 } else {
918 // We've reached some non-indexable type.
919 break;
Chris Lattnere568fa22009-12-03 01:05:45 +0000920 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +0000921
Dan Gohmande0e5872009-08-19 18:18:36 +0000922 // Determine which element of the array the offset points into.
Eduard Burtescu47506352016-01-21 23:42:06 +0000923 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer671faaf2016-07-13 05:16:16 +0000924 if (ElemSize == 0) {
Chris Lattnerc1da2042010-11-21 08:39:01 +0000925 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sandse5839102010-11-21 12:43:13 +0000926 // index for this level and proceed to the next level to see if it can
927 // accommodate the offset.
Chris Lattnerc1da2042010-11-21 08:39:01 +0000928 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer671faaf2016-07-13 05:16:16 +0000929 } else {
Chris Lattnerc1da2042010-11-21 08:39:01 +0000930 // The element size is non-zero divide the offset by the element
931 // size (rounding down), to compute the index at this level.
David Majnemer549def02016-07-13 15:53:46 +0000932 bool Overflow;
933 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
934 if (Overflow)
935 break;
Chris Lattnerc1da2042010-11-21 08:39:01 +0000936 Offset -= NewIdx * ElemSize;
937 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
938 }
Eduard Burtescu47506352016-01-21 23:42:06 +0000939 } else {
David Majnemer0c6dbcc2016-07-13 04:22:12 +0000940 auto *STy = cast<StructType>(Ty);
Chandler Carruth7362ac72012-04-24 18:42:47 +0000941 // If we end up with an offset that isn't valid for this struct type, we
942 // can't re-form this GEP in a regular form, so bail out. The pointer
943 // operand likely went through casts that are necessary to make the GEP
944 // sensible.
Mehdi Amini529919f2015-03-10 02:37:25 +0000945 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer671faaf2016-07-13 05:16:16 +0000946 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruth7362ac72012-04-24 18:42:47 +0000947 break;
948
949 // Determine which field of the struct the offset points into. The
950 // getZExtValue is fine as we've already ensured that the offset is
951 // within the range representable by the StructLayout API.
Dan Gohmancda97062009-08-21 16:52:54 +0000952 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner7b550cc2009-11-06 04:27:31 +0000953 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
954 ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000955 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000956 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohmande0e5872009-08-19 18:18:36 +0000957 }
Eduard Burtescu47506352016-01-21 23:42:06 +0000958 } while (Ty != ResElemTy);
Dan Gohman3d013342009-08-19 22:46:59 +0000959
960 // If we haven't used up the entire offset by descending the static
961 // type, then the offset is pointing into the middle of an indivisible
962 // member, so we can't simplify it.
963 if (Offset != 0)
Craig Topper570e52c2014-04-15 04:59:12 +0000964 return nullptr;
Dan Gohmande0e5872009-08-19 18:18:36 +0000965
Peter Collingbourneca668e12016-11-10 22:34:55 +0000966 // Preserve the inrange index from the innermost GEP if possible. We must
967 // have calculated the same indices up to and including the inrange index.
968 Optional<unsigned> InRangeIndex;
969 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
970 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
971 NewIdxs.size() > *LastIRIndex) {
972 InRangeIndex = LastIRIndex;
973 for (unsigned I = 0; I <= *LastIRIndex; ++I)
Peter Collingbourneb5966202018-09-11 01:53:36 +0000974 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
975 return nullptr;
Peter Collingbourneca668e12016-11-10 22:34:55 +0000976 }
977
Dan Gohman3bfbc452009-09-11 00:04:14 +0000978 // Create a GEP.
Peter Collingbourned703e442016-11-22 01:03:40 +0000979 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
980 InBounds, InRangeIndex);
Matt Arsenault89fa38e2013-08-12 23:15:58 +0000981 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohman6e7ad952009-09-03 23:34:49 +0000982 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000983
Dan Gohman3d013342009-08-19 22:46:59 +0000984 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000985 // the type of what the original indices indexed, add a cast.
Eduard Burtescu47506352016-01-21 23:42:06 +0000986 if (Ty != ResElemTy)
987 C = FoldBitCast(C, ResTy, DL);
Dan Gohman3d013342009-08-19 22:46:59 +0000988
989 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000990}
991
Manuel Jacob6a931592016-01-21 06:33:22 +0000992/// Attempt to constant fold an instruction with the
993/// specified opcode and operands. If successful, the constant result is
994/// returned, if not, null is returned. Note that this function can fail when
995/// attempting to fold instructions like loads and stores, which have no
996/// constant expression form.
David Majnemer6b87ada2016-07-29 03:27:33 +0000997Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenkod0a33c42016-03-28 17:40:08 +0000998 ArrayRef<Constant *> Ops,
999 const DataLayout &DL,
1000 const TargetLibraryInfo *TLI) {
David Majnemer6b87ada2016-07-29 03:27:33 +00001001 Type *DestTy = InstOrCE->getType();
1002
Manuel Jacob6a931592016-01-21 06:33:22 +00001003 // Handle easy binops first.
1004 if (Instruction::isBinaryOp(Opcode))
1005 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1006
1007 if (Instruction::isCast(Opcode))
1008 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1009
David Majnemer17c5ce912016-07-13 03:42:38 +00001010 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu47506352016-01-21 23:42:06 +00001011 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1012 return C;
1013
Peter Collingbourneca668e12016-11-10 22:34:55 +00001014 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1015 Ops.slice(1), GEP->isInBounds(),
1016 GEP->getInRangeIndex());
Eduard Burtescu47506352016-01-21 23:42:06 +00001017 }
1018
David Majnemer8065d772016-07-29 03:27:31 +00001019 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1020 return CE->getWithOperands(Ops);
1021
Manuel Jacob6a931592016-01-21 06:33:22 +00001022 switch (Opcode) {
1023 default: return nullptr;
1024 case Instruction::ICmp:
1025 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1026 case Instruction::Call:
Andrew Kaylorb8e91642017-06-09 23:18:11 +00001027 if (auto *F = dyn_cast<Function>(Ops.back())) {
1028 ImmutableCallSite CS(cast<CallInst>(InstOrCE));
1029 if (canConstantFoldCallTo(CS, F))
1030 return ConstantFoldCall(CS, F, Ops.slice(0, Ops.size() - 1), TLI);
1031 }
Manuel Jacob6a931592016-01-21 06:33:22 +00001032 return nullptr;
1033 case Instruction::Select:
1034 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1035 case Instruction::ExtractElement:
1036 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1037 case Instruction::InsertElement:
1038 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1039 case Instruction::ShuffleVector:
1040 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacob6a931592016-01-21 06:33:22 +00001041 }
1042}
1043
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001044} // end anonymous namespace
Chris Lattner03dd25c2007-01-31 00:51:48 +00001045
1046//===----------------------------------------------------------------------===//
1047// Constant Folding public APIs
1048//===----------------------------------------------------------------------===//
1049
David Majnemere43ff142016-07-29 03:27:26 +00001050namespace {
1051
1052Constant *
1053ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1054 const TargetLibraryInfo *TLI,
1055 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1056 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1057 return nullptr;
1058
1059 SmallVector<Constant *, 8> Ops;
1060 for (const Use &NewU : C->operands()) {
1061 auto *NewC = cast<Constant>(&NewU);
1062 // Recursively fold the ConstantExpr's operands. If we have already folded
1063 // a ConstantExpr, we don't have to process it again.
1064 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1065 auto It = FoldedOps.find(NewC);
1066 if (It == FoldedOps.end()) {
1067 if (auto *FoldedC =
1068 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
David Majnemere43ff142016-07-29 03:27:26 +00001069 FoldedOps.insert({NewC, FoldedC});
David Green8b2132a2017-03-21 10:17:39 +00001070 NewC = FoldedC;
David Majnemere43ff142016-07-29 03:27:26 +00001071 } else {
1072 FoldedOps.insert({NewC, NewC});
1073 }
1074 } else {
1075 NewC = It->second;
1076 }
1077 }
1078 Ops.push_back(NewC);
1079 }
1080
1081 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1082 if (CE->isCompare())
1083 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1084 DL, TLI);
1085
David Majnemer6b87ada2016-07-29 03:27:33 +00001086 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemere43ff142016-07-29 03:27:26 +00001087 }
1088
1089 assert(isa<ConstantVector>(C));
1090 return ConstantVector::get(Ops);
1091}
1092
1093} // end anonymous namespace
1094
Mehdi Amini529919f2015-03-10 02:37:25 +00001095Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosier618c1db2011-12-01 03:08:23 +00001096 const TargetLibraryInfo *TLI) {
Duncan Sandsb9b369f2010-11-23 10:16:18 +00001097 // Handle PHI nodes quickly here...
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001098 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper570e52c2014-04-15 04:59:12 +00001099 Constant *CommonValue = nullptr;
John Criswellbd9d3702005-10-27 16:00:10 +00001100
David Majnemere43ff142016-07-29 03:27:26 +00001101 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooperf23c6af2015-05-12 20:05:31 +00001102 for (Value *Incoming : PN->incoming_values()) {
Duncan Sandsb9b369f2010-11-23 10:16:18 +00001103 // If the incoming value is undef then skip it. Note that while we could
1104 // skip the value if it is equal to the phi node itself we choose not to
1105 // because that would break the rule that constant folding only applies if
1106 // all operands are constants.
1107 if (isa<UndefValue>(Incoming))
Duncan Sandsc0362d52010-11-14 12:53:18 +00001108 continue;
Dan Gohman03e091f2012-04-27 17:50:22 +00001109 // If the incoming value is not a constant, then give up.
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001110 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman03e091f2012-04-27 17:50:22 +00001111 if (!C)
Craig Topper570e52c2014-04-15 04:59:12 +00001112 return nullptr;
Dan Gohman03e091f2012-04-27 17:50:22 +00001113 // Fold the PHI's operands.
David Majnemere43ff142016-07-29 03:27:26 +00001114 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1115 C = FoldedC;
Dan Gohman03e091f2012-04-27 17:50:22 +00001116 // If the incoming value is a different constant to
1117 // the one we saw previously, then give up.
1118 if (CommonValue && C != CommonValue)
Craig Topper570e52c2014-04-15 04:59:12 +00001119 return nullptr;
Duncan Sandsc0362d52010-11-14 12:53:18 +00001120 CommonValue = C;
1121 }
Chris Lattner55207322007-01-30 23:45:45 +00001122
Duncan Sandsc0362d52010-11-14 12:53:18 +00001123 // If we reach here, all incoming values are the same constant or undef.
1124 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner55207322007-01-30 23:45:45 +00001125 }
1126
1127 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacob6a931592016-01-21 06:33:22 +00001128 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaserb704b7a2016-03-13 05:36:15 +00001129 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1130 return nullptr;
Chris Lattner55207322007-01-30 23:45:45 +00001131
David Majnemere43ff142016-07-29 03:27:26 +00001132 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaserb704b7a2016-03-13 05:36:15 +00001133 SmallVector<Constant *, 8> Ops;
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001134 for (const Use &OpU : I->operands()) {
1135 auto *Op = cast<Constant>(&OpU);
Dan Gohman03e091f2012-04-27 17:50:22 +00001136 // Fold the Instruction's operands.
David Majnemere43ff142016-07-29 03:27:26 +00001137 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1138 Op = FoldedOp;
Dan Gohman03e091f2012-04-27 17:50:22 +00001139
1140 Ops.push_back(Op);
1141 }
1142
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001143 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00001144 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Amini529919f2015-03-10 02:37:25 +00001145 DL, TLI);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001146
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001147 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Amini529919f2015-03-10 02:37:25 +00001148 return ConstantFoldLoadInst(LI, DL);
Frits van Bommel3ee0af32010-11-29 20:36:52 +00001149
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001150 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommel3ee0af32010-11-29 20:36:52 +00001151 return ConstantExpr::getInsertValue(
1152 cast<Constant>(IVI->getAggregateOperand()),
1153 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001154 IVI->getIndices());
Matt Arsenaultb36f2f72013-08-12 22:56:15 +00001155 }
Frits van Bommel3ee0af32010-11-29 20:36:52 +00001156
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001157 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommel3ee0af32010-11-29 20:36:52 +00001158 return ConstantExpr::getExtractValue(
1159 cast<Constant>(EVI->getAggregateOperand()),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001160 EVI->getIndices());
Matt Arsenaultb36f2f72013-08-12 22:56:15 +00001161 }
Frits van Bommel3ee0af32010-11-29 20:36:52 +00001162
Eduard Burtescu47506352016-01-21 23:42:06 +00001163 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner55207322007-01-30 23:45:45 +00001164}
1165
David Majnemere43ff142016-07-29 03:27:26 +00001166Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1167 const TargetLibraryInfo *TLI) {
1168 SmallDenseMap<Constant *, Constant *> FoldedOps;
1169 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer88486802013-04-13 12:53:18 +00001170}
1171
Manuel Jacob6a931592016-01-21 06:33:22 +00001172Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foad1d2f5692011-07-19 13:32:40 +00001173 ArrayRef<Constant *> Ops,
Mehdi Amini529919f2015-03-10 02:37:25 +00001174 const DataLayout &DL,
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001175 const TargetLibraryInfo *TLI) {
David Majnemer6b87ada2016-07-29 03:27:33 +00001176 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner55207322007-01-30 23:45:45 +00001177}
1178
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001179Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001180 Constant *Ops0, Constant *Ops1,
Mehdi Amini529919f2015-03-10 02:37:25 +00001181 const DataLayout &DL,
Chad Rosier618c1db2011-12-01 03:08:23 +00001182 const TargetLibraryInfo *TLI) {
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001183 // fold: icmp (inttoptr x), null -> icmp x, 0
Craig Toppercbb8bc92017-06-02 16:17:32 +00001184 // fold: icmp null, (inttoptr x) -> icmp 0, x
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001185 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Craig Toppercbb8bc92017-06-02 16:17:32 +00001186 // fold: icmp 0, (ptrtoint x) -> icmp null, x
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001187 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001188 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1189 //
Mehdi Amini529919f2015-03-10 02:37:25 +00001190 // FIXME: The following comment is out of data and the DataLayout is here now.
1191 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001192 // around to know if bit truncation is happening.
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001193 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001194 if (Ops1->isNullValue()) {
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001195 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001196 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001197 // Convert the integer value to the right size to ensure we get the
1198 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001199 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001200 IntPtrTy, false);
Chris Lattner8f73dea2009-11-09 23:06:58 +00001201 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Amini529919f2015-03-10 02:37:25 +00001202 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001203 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001204
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001205 // Only do this transformation if the int is intptrty in size, otherwise
1206 // there is a truncation or extension that we aren't modeling.
Matt Arsenault80f495a2013-08-20 21:20:04 +00001207 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001208 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault80f495a2013-08-20 21:20:04 +00001209 if (CE0->getType() == IntPtrTy) {
1210 Constant *C = CE0->getOperand(0);
1211 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Amini529919f2015-03-10 02:37:25 +00001212 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault80f495a2013-08-20 21:20:04 +00001213 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001214 }
1215 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001216
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001217 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001218 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001219 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001220 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault80f495a2013-08-20 21:20:04 +00001221
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001222 // Convert the integer value to the right size to ensure we get the
1223 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001224 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001225 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001226 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001227 IntPtrTy, false);
Mehdi Amini529919f2015-03-10 02:37:25 +00001228 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +00001229 }
1230
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001231 // Only do this transformation if the int is intptrty in size, otherwise
1232 // there is a truncation or extension that we aren't modeling.
Matt Arsenault80f495a2013-08-20 21:20:04 +00001233 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001234 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault80f495a2013-08-20 21:20:04 +00001235 if (CE0->getType() == IntPtrTy &&
1236 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001237 return ConstantFoldCompareInstOperands(
1238 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault80f495a2013-08-20 21:20:04 +00001239 }
1240 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001241 }
1242 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001243
Chris Lattner79fa3cf2010-01-02 01:22:23 +00001244 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1245 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1246 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1247 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Amini529919f2015-03-10 02:37:25 +00001248 Constant *LHS = ConstantFoldCompareInstOperands(
1249 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1250 Constant *RHS = ConstantFoldCompareInstOperands(
1251 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001252 unsigned OpC =
Chris Lattner79fa3cf2010-01-02 01:22:23 +00001253 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacob80413412016-01-21 06:26:35 +00001254 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner79fa3cf2010-01-02 01:22:23 +00001255 }
Craig Toppercbb8bc92017-06-02 16:17:32 +00001256 } else if (isa<ConstantExpr>(Ops1)) {
1257 // If RHS is a constant expression, but the left side isn't, swap the
1258 // operands and try again.
1259 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1260 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001261 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001262
Chris Lattner8f73dea2009-11-09 23:06:58 +00001263 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001264}
1265
Manuel Jacob80413412016-01-21 06:26:35 +00001266Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1267 Constant *RHS,
1268 const DataLayout &DL) {
1269 assert(Instruction::isBinaryOp(Opcode));
1270 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1271 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1272 return C;
1273
1274 return ConstantExpr::get(Opcode, LHS, RHS);
1275}
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001276
Manuel Jacob9b455a82016-01-21 06:31:08 +00001277Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1278 Type *DestTy, const DataLayout &DL) {
1279 assert(Instruction::isCast(Opcode));
1280 switch (Opcode) {
1281 default:
1282 llvm_unreachable("Missing case");
1283 case Instruction::PtrToInt:
1284 // If the input is a inttoptr, eliminate the pair. This requires knowing
1285 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001286 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob9b455a82016-01-21 06:31:08 +00001287 if (CE->getOpcode() == Instruction::IntToPtr) {
1288 Constant *Input = CE->getOperand(0);
1289 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1290 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1291 if (PtrWidth < InWidth) {
1292 Constant *Mask =
1293 ConstantInt::get(CE->getContext(),
1294 APInt::getLowBitsSet(InWidth, PtrWidth));
1295 Input = ConstantExpr::getAnd(Input, Mask);
1296 }
1297 // Do a zext or trunc to get to the dest size.
1298 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1299 }
1300 }
1301 return ConstantExpr::getCast(Opcode, C, DestTy);
1302 case Instruction::IntToPtr:
1303 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1304 // the int size is >= the ptr size and the address spaces are the same.
1305 // This requires knowing the width of a pointer, so it can't be done in
1306 // ConstantExpr::getCast.
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001307 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob9b455a82016-01-21 06:31:08 +00001308 if (CE->getOpcode() == Instruction::PtrToInt) {
1309 Constant *SrcPtr = CE->getOperand(0);
1310 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1311 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1312
1313 if (MidIntSize >= SrcPtrSize) {
1314 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1315 if (SrcAS == DestTy->getPointerAddressSpace())
1316 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1317 }
1318 }
1319 }
1320
1321 return ConstantExpr::getCast(Opcode, C, DestTy);
1322 case Instruction::Trunc:
1323 case Instruction::ZExt:
1324 case Instruction::SExt:
1325 case Instruction::FPTrunc:
1326 case Instruction::FPExt:
1327 case Instruction::UIToFP:
1328 case Instruction::SIToFP:
1329 case Instruction::FPToUI:
1330 case Instruction::FPToSI:
1331 case Instruction::AddrSpaceCast:
1332 return ConstantExpr::getCast(Opcode, C, DestTy);
1333 case Instruction::BitCast:
1334 return FoldBitCast(C, DestTy, DL);
1335 }
1336}
1337
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001338Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +00001339 ConstantExpr *CE) {
Chris Lattnera97ddd02012-01-24 05:43:50 +00001340 if (!CE->getOperand(1)->isNullValue())
Craig Topper570e52c2014-04-15 04:59:12 +00001341 return nullptr; // Do not allow stepping over the value!
Chris Lattnera1f00f42012-01-25 06:48:06 +00001342
1343 // Loop over all of the operands, tracking down which value we are
1344 // addressing.
1345 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1346 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper570e52c2014-04-15 04:59:12 +00001347 if (!C)
1348 return nullptr;
Chris Lattnera1f00f42012-01-25 06:48:06 +00001349 }
1350 return C;
Chris Lattnera97ddd02012-01-24 05:43:50 +00001351}
1352
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001353Constant *
1354llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1355 ArrayRef<Constant *> Indices) {
Chris Lattner55207322007-01-30 23:45:45 +00001356 // Loop over all of the operands, tracking down which value we are
Chris Lattnera97ddd02012-01-24 05:43:50 +00001357 // addressing.
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001358 for (Constant *Index : Indices) {
1359 C = C->getAggregateElement(Index);
Craig Topper570e52c2014-04-15 04:59:12 +00001360 if (!C)
1361 return nullptr;
Chris Lattnera97ddd02012-01-24 05:43:50 +00001362 }
Chris Lattner55207322007-01-30 23:45:45 +00001363 return C;
1364}
1365
Chris Lattner55207322007-01-30 23:45:45 +00001366//===----------------------------------------------------------------------===//
1367// Constant Folding for Calls
1368//
John Criswellbd9d3702005-10-27 16:00:10 +00001369
Andrew Kaylorb8e91642017-06-09 23:18:11 +00001370bool llvm::canConstantFoldCallTo(ImmutableCallSite CS, const Function *F) {
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00001371 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylorb8e91642017-06-09 23:18:11 +00001372 return false;
John Criswellbd9d3702005-10-27 16:00:10 +00001373 switch (F->getIntrinsicID()) {
Owen Anderson42258e02013-02-06 22:43:31 +00001374 case Intrinsic::fabs:
Matt Arsenault25213462014-10-21 23:00:20 +00001375 case Intrinsic::minnum:
1376 case Intrinsic::maxnum:
Thomas Livelyaff56dc2018-10-19 18:15:32 +00001377 case Intrinsic::minimum:
1378 case Intrinsic::maximum:
Owen Anderson42258e02013-02-06 22:43:31 +00001379 case Intrinsic::log:
1380 case Intrinsic::log2:
1381 case Intrinsic::log10:
1382 case Intrinsic::exp:
1383 case Intrinsic::exp2:
1384 case Intrinsic::floor:
Karthik Bhat07707e82014-03-24 04:36:06 +00001385 case Intrinsic::ceil:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00001386 case Intrinsic::sqrt:
Karthik Bhatd9dffa62015-07-08 03:55:47 +00001387 case Intrinsic::sin:
1388 case Intrinsic::cos:
Karthik Bhatc7213492015-07-21 08:52:23 +00001389 case Intrinsic::trunc:
1390 case Intrinsic::rint:
1391 case Intrinsic::nearbyint:
Chad Rosier24fbf2b2011-12-03 00:00:03 +00001392 case Intrinsic::pow:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00001393 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +00001394 case Intrinsic::bswap:
1395 case Intrinsic::ctpop:
1396 case Intrinsic::ctlz:
1397 case Intrinsic::cttz:
Sanjay Patel77ce59d2018-08-17 13:23:44 +00001398 case Intrinsic::fshl:
1399 case Intrinsic::fshr:
Matt Arsenault34fae3a2014-03-05 00:02:00 +00001400 case Intrinsic::fma:
1401 case Intrinsic::fmuladd:
Karthik Bhatdf95a942014-03-06 05:32:52 +00001402 case Intrinsic::copysign:
Piotr Padlewskida5cef72018-05-18 23:52:57 +00001403 case Intrinsic::launder_invariant_group:
Piotr Padlewskic2f24d92018-07-02 04:49:30 +00001404 case Intrinsic::strip_invariant_group:
Karthik Bhat70957b92014-03-07 04:36:21 +00001405 case Intrinsic::round:
David Majnemer3dc0c3e2016-07-14 00:29:50 +00001406 case Intrinsic::masked_load:
Evan Phoenix1614e502009-10-05 22:53:52 +00001407 case Intrinsic::sadd_with_overflow:
Frits van Bommel62086102011-03-27 14:26:13 +00001408 case Intrinsic::uadd_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +00001409 case Intrinsic::ssub_with_overflow:
Frits van Bommel62086102011-03-27 14:26:13 +00001410 case Intrinsic::usub_with_overflow:
Chris Lattnereafc5cb2010-10-14 00:05:07 +00001411 case Intrinsic::smul_with_overflow:
Frits van Bommel62086102011-03-27 14:26:13 +00001412 case Intrinsic::umul_with_overflow:
Sanjay Patel4f676c62018-11-20 17:05:55 +00001413 case Intrinsic::sadd_sat:
1414 case Intrinsic::uadd_sat:
1415 case Intrinsic::ssub_sat:
1416 case Intrinsic::usub_sat:
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001417 case Intrinsic::convert_from_fp16:
1418 case Intrinsic::convert_to_fp16:
Matt Arsenault23f7a822016-03-21 15:00:35 +00001419 case Intrinsic::bitreverse:
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001420 case Intrinsic::x86_sse_cvtss2si:
1421 case Intrinsic::x86_sse_cvtss2si64:
1422 case Intrinsic::x86_sse_cvttss2si:
1423 case Intrinsic::x86_sse_cvttss2si64:
1424 case Intrinsic::x86_sse2_cvtsd2si:
1425 case Intrinsic::x86_sse2_cvtsd2si64:
1426 case Intrinsic::x86_sse2_cvttsd2si:
1427 case Intrinsic::x86_sse2_cvttsd2si64:
Craig Topper3bc13522018-08-12 22:09:54 +00001428 case Intrinsic::x86_avx512_vcvtss2si32:
1429 case Intrinsic::x86_avx512_vcvtss2si64:
1430 case Intrinsic::x86_avx512_cvttss2si:
1431 case Intrinsic::x86_avx512_cvttss2si64:
1432 case Intrinsic::x86_avx512_vcvtsd2si32:
1433 case Intrinsic::x86_avx512_vcvtsd2si64:
1434 case Intrinsic::x86_avx512_cvttsd2si:
1435 case Intrinsic::x86_avx512_cvttsd2si64:
1436 case Intrinsic::x86_avx512_vcvtss2usi32:
1437 case Intrinsic::x86_avx512_vcvtss2usi64:
1438 case Intrinsic::x86_avx512_cvttss2usi:
1439 case Intrinsic::x86_avx512_cvttss2usi64:
1440 case Intrinsic::x86_avx512_vcvtsd2usi32:
1441 case Intrinsic::x86_avx512_vcvtsd2usi64:
1442 case Intrinsic::x86_avx512_cvttsd2usi:
1443 case Intrinsic::x86_avx512_cvttsd2usi64:
James Y Knight3125e352018-11-07 15:24:12 +00001444 case Intrinsic::is_constant:
John Criswellbd9d3702005-10-27 16:00:10 +00001445 return true;
Chris Lattner68a06032009-10-05 05:00:35 +00001446 default:
1447 return false;
Craig Topperfb99fcd2017-04-07 21:36:32 +00001448 case Intrinsic::not_intrinsic: break;
John Criswellbd9d3702005-10-27 16:00:10 +00001449 }
1450
Matt Arsenaultb36f2f72013-08-12 22:56:15 +00001451 if (!F->hasName())
1452 return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001453 StringRef Name = F->getName();
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001454
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001455 // In these cases, the check of the length is required. We don't want to
1456 // return true for a name like "cos\0blah" which strcmp would return equal to
1457 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001458 switch (Name[0]) {
Erik Schnetter742f5d82015-08-27 19:56:57 +00001459 default:
1460 return false;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001461 case 'a':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001462 return Name == "acos" || Name == "asin" || Name == "atan" ||
1463 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1464 Name == "atanf" || Name == "atan2f";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001465 case 'c':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001466 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1467 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001468 case 'e':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001469 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001470 case 'f':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001471 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1472 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001473 case 'l':
Xin Tong679bac52017-10-01 00:09:53 +00001474 return Name == "log" || Name == "log10" || Name == "logf" ||
Erik Schnetter742f5d82015-08-27 19:56:57 +00001475 Name == "log10f";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001476 case 'p':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001477 return Name == "pow" || Name == "powf";
Bryant Wong5825ccc2016-12-26 14:29:29 +00001478 case 'r':
1479 return Name == "round" || Name == "roundf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001480 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001481 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter742f5d82015-08-27 19:56:57 +00001482 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001483 case 't':
Erik Schnetter742f5d82015-08-27 19:56:57 +00001484 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
Andrew Kaylor09976352017-05-12 22:11:20 +00001485 case '_':
1486
1487 // Check for various function names that get used for the math functions
1488 // when the header files are preprocessed with the macro
1489 // __FINITE_MATH_ONLY__ enabled.
1490 // The '12' here is the length of the shortest name that can match.
1491 // We need to check the size before looking at Name[1] and Name[2]
1492 // so we may as well check a limit that will eliminate mismatches.
1493 if (Name.size() < 12 || Name[1] != '_')
1494 return false;
1495 switch (Name[2]) {
1496 default:
1497 return false;
1498 case 'a':
1499 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1500 Name == "__asin_finite" || Name == "__asinf_finite" ||
1501 Name == "__atan2_finite" || Name == "__atan2f_finite";
1502 case 'c':
1503 return Name == "__cosh_finite" || Name == "__coshf_finite";
1504 case 'e':
1505 return Name == "__exp_finite" || Name == "__expf_finite" ||
1506 Name == "__exp2_finite" || Name == "__exp2f_finite";
1507 case 'l':
1508 return Name == "__log_finite" || Name == "__logf_finite" ||
1509 Name == "__log10_finite" || Name == "__log10f_finite";
1510 case 'p':
1511 return Name == "__pow_finite" || Name == "__powf_finite";
1512 case 's':
1513 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1514 }
John Criswellbd9d3702005-10-27 16:00:10 +00001515 }
1516}
1517
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001518namespace {
1519
1520Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Anderson42258e02013-02-06 22:43:31 +00001521 if (Ty->isHalfTy()) {
1522 APFloat APF(V);
1523 bool unused;
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001524 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
Owen Anderson42258e02013-02-06 22:43:31 +00001525 return ConstantFP::get(Ty->getContext(), APF);
1526 }
Chris Lattnerd0806a12009-10-05 05:06:24 +00001527 if (Ty->isFloatTy())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001528 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +00001529 if (Ty->isDoubleTy())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001530 return ConstantFP::get(Ty->getContext(), APFloat(V));
Xin Tong679bac52017-10-01 00:09:53 +00001531 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenault175c6342014-03-05 00:01:58 +00001532}
1533
Sanjay Patele1656932014-10-02 15:13:22 +00001534/// Clear the floating-point exception state.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001535inline void llvm_fenv_clearexcept() {
Alp Toker53963702014-06-09 19:00:52 +00001536#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerf4cf4042014-06-09 18:28:53 +00001537 feclearexcept(FE_ALL_EXCEPT);
1538#endif
1539 errno = 0;
1540}
1541
Sanjay Patele1656932014-10-02 15:13:22 +00001542/// Test if a floating-point exception was raised.
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001543inline bool llvm_fenv_testexcept() {
Alp Tokerf4cf4042014-06-09 18:28:53 +00001544 int errno_val = errno;
1545 if (errno_val == ERANGE || errno_val == EDOM)
1546 return true;
Alp Toker53963702014-06-09 19:00:52 +00001547#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerf4cf4042014-06-09 18:28:53 +00001548 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1549 return true;
1550#endif
1551 return false;
1552}
Alp Tokerf4cf4042014-06-09 18:28:53 +00001553
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001554Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerf4cf4042014-06-09 18:28:53 +00001555 llvm_fenv_clearexcept();
Matt Arsenault175c6342014-03-05 00:01:58 +00001556 V = NativeFP(V);
Alp Tokerf4cf4042014-06-09 18:28:53 +00001557 if (llvm_fenv_testexcept()) {
1558 llvm_fenv_clearexcept();
Craig Topper570e52c2014-04-15 04:59:12 +00001559 return nullptr;
Matt Arsenault175c6342014-03-05 00:01:58 +00001560 }
1561
1562 return GetConstantFoldFPValue(V, Ty);
John Criswellbd9d3702005-10-27 16:00:10 +00001563}
1564
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001565Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1566 double W, Type *Ty) {
Alp Tokerf4cf4042014-06-09 18:28:53 +00001567 llvm_fenv_clearexcept();
Dan Gohman38415242007-07-16 15:26:22 +00001568 V = NativeFP(V, W);
Alp Tokerf4cf4042014-06-09 18:28:53 +00001569 if (llvm_fenv_testexcept()) {
1570 llvm_fenv_clearexcept();
Craig Topper570e52c2014-04-15 04:59:12 +00001571 return nullptr;
Dale Johannesen43421b32007-09-06 18:13:44 +00001572 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001573
Matt Arsenault175c6342014-03-05 00:01:58 +00001574 return GetConstantFoldFPValue(V, Ty);
Dan Gohman38415242007-07-16 15:26:22 +00001575}
1576
Sanjay Patele1656932014-10-02 15:13:22 +00001577/// Attempt to fold an SSE floating point to integer conversion of a constant
1578/// floating point. If roundTowardZero is false, the default IEEE rounding is
1579/// used (toward nearest, ties to even). This matches the behavior of the
1580/// non-truncating SSE instructions in the default rounding mode. The desired
1581/// integer type Ty is used to select how many bits are available for the
1582/// result. Returns null if the conversion cannot be performed, otherwise
1583/// returns the Constant value resulting from the conversion.
Simon Pilgrim0f9cdd22016-07-19 15:07:43 +00001584Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
Craig Topper3bc13522018-08-12 22:09:54 +00001585 Type *Ty, bool IsSigned) {
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001586 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault89fa38e2013-08-12 23:15:58 +00001587 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001588 assert(ResultWidth <= 64 &&
1589 "Can only constant fold conversions to 64 and 32 bit ints");
1590
1591 uint64_t UIntVal;
1592 bool isExact = false;
1593 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1594 : APFloat::rmNearestTiesToEven;
Simon Pilgrim957caa22017-03-20 14:40:12 +00001595 APFloat::opStatus status =
1596 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
Craig Topper3bc13522018-08-12 22:09:54 +00001597 IsSigned, mode, &isExact);
Simon Pilgrim0f9cdd22016-07-19 15:07:43 +00001598 if (status != APFloat::opOK &&
1599 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper570e52c2014-04-15 04:59:12 +00001600 return nullptr;
Craig Topper3bc13522018-08-12 22:09:54 +00001601 return ConstantInt::get(Ty, UIntVal, IsSigned);
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001602}
1603
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001604double getValueAsDouble(ConstantFP *Op) {
Matt Arsenault175c6342014-03-05 00:01:58 +00001605 Type *Ty = Op->getType();
1606
1607 if (Ty->isFloatTy())
1608 return Op->getValueAPF().convertToFloat();
1609
1610 if (Ty->isDoubleTy())
1611 return Op->getValueAPF().convertToDouble();
1612
1613 bool unused;
1614 APFloat APF = Op->getValueAPF();
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001615 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenault175c6342014-03-05 00:01:58 +00001616 return APF.convertToDouble();
1617}
1618
James Y Knight3125e352018-11-07 15:24:12 +00001619static bool isManifestConstant(const Constant *c) {
1620 if (isa<ConstantData>(c)) {
1621 return true;
1622 } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1623 for (const Value *subc : c->operand_values()) {
1624 if (!isManifestConstant(cast<Constant>(subc)))
1625 return false;
1626 }
1627 return true;
1628 }
1629 return false;
1630}
1631
Nikita Popov01f4bc22019-01-11 21:18:00 +00001632static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1633 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1634 C = &CI->getValue();
1635 return true;
1636 }
1637 if (isa<UndefValue>(Op)) {
1638 C = nullptr;
1639 return true;
1640 }
1641 return false;
1642}
1643
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00001644Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1645 ArrayRef<Constant *> Operands,
Manoj Guptac6da6862018-07-09 22:27:23 +00001646 const TargetLibraryInfo *TLI,
1647 ImmutableCallSite CS) {
Jay Foad1d2f5692011-07-19 13:32:40 +00001648 if (Operands.size() == 1) {
James Y Knight3125e352018-11-07 15:24:12 +00001649 if (IntrinsicID == Intrinsic::is_constant) {
1650 // We know we have a "Constant" argument. But we want to only
1651 // return true for manifest constants, not those that depend on
1652 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1653 if (isManifestConstant(Operands[0]))
1654 return ConstantInt::getTrue(Ty->getContext());
1655 return nullptr;
1656 }
Sanjoy Das87313362016-04-08 18:21:11 +00001657 if (isa<UndefValue>(Operands[0])) {
Nikita Popov01f4bc22019-01-11 21:18:00 +00001658 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1659 // ctpop() is between 0 and bitwidth, pick 0 for undef.
1660 if (IntrinsicID == Intrinsic::cos ||
1661 IntrinsicID == Intrinsic::ctpop)
Sanjoy Das87313362016-04-08 18:21:11 +00001662 return Constant::getNullValue(Ty);
Craig Toppercbcb0b42017-06-04 08:21:53 +00001663 if (IntrinsicID == Intrinsic::bswap ||
Piotr Padlewskida5cef72018-05-18 23:52:57 +00001664 IntrinsicID == Intrinsic::bitreverse ||
Piotr Padlewskic2f24d92018-07-02 04:49:30 +00001665 IntrinsicID == Intrinsic::launder_invariant_group ||
1666 IntrinsicID == Intrinsic::strip_invariant_group)
Craig Toppercbcb0b42017-06-04 08:21:53 +00001667 return Operands[0];
Sanjoy Das87313362016-04-08 18:21:11 +00001668 }
Piotr Padlewskida5cef72018-05-18 23:52:57 +00001669
Manoj Gupta7321ba22018-07-23 21:20:00 +00001670 if (isa<ConstantPointerNull>(Operands[0])) {
Piotr Padlewskic2f24d92018-07-02 04:49:30 +00001671 // launder(null) == null == strip(null) iff in addrspace 0
1672 if (IntrinsicID == Intrinsic::launder_invariant_group ||
Manoj Gupta7321ba22018-07-23 21:20:00 +00001673 IntrinsicID == Intrinsic::strip_invariant_group) {
1674 // If instruction is not yet put in a basic block (e.g. when cloning
1675 // a function during inlining), CS caller may not be available.
1676 // So check CS's BB first before querying CS.getCaller.
1677 const Function *Caller = CS.getParent() ? CS.getCaller() : nullptr;
1678 if (Caller &&
1679 !NullPointerIsDefined(
1680 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1681 return Operands[0];
1682 }
1683 return nullptr;
1684 }
Piotr Padlewskida5cef72018-05-18 23:52:57 +00001685 }
1686
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001687 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001688 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001689 APFloat Val(Op->getValueAPF());
1690
1691 bool lost = false;
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001692 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001693
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001694 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001695 }
1696
Xin Tong679bac52017-10-01 00:09:53 +00001697 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper570e52c2014-04-15 04:59:12 +00001698 return nullptr;
Jakob Stoklund Olesen1f386c42010-09-27 21:29:20 +00001699
Karthik Bhat70957b92014-03-07 04:36:21 +00001700 if (IntrinsicID == Intrinsic::round) {
1701 APFloat V = Op->getValueAPF();
1702 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1703 return ConstantFP::get(Ty->getContext(), V);
1704 }
1705
Karthik Bhatc7213492015-07-21 08:52:23 +00001706 if (IntrinsicID == Intrinsic::floor) {
1707 APFloat V = Op->getValueAPF();
1708 V.roundToIntegral(APFloat::rmTowardNegative);
1709 return ConstantFP::get(Ty->getContext(), V);
1710 }
1711
1712 if (IntrinsicID == Intrinsic::ceil) {
1713 APFloat V = Op->getValueAPF();
1714 V.roundToIntegral(APFloat::rmTowardPositive);
1715 return ConstantFP::get(Ty->getContext(), V);
1716 }
1717
1718 if (IntrinsicID == Intrinsic::trunc) {
1719 APFloat V = Op->getValueAPF();
1720 V.roundToIntegral(APFloat::rmTowardZero);
1721 return ConstantFP::get(Ty->getContext(), V);
1722 }
1723
1724 if (IntrinsicID == Intrinsic::rint) {
1725 APFloat V = Op->getValueAPF();
1726 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1727 return ConstantFP::get(Ty->getContext(), V);
1728 }
1729
1730 if (IntrinsicID == Intrinsic::nearbyint) {
1731 APFloat V = Op->getValueAPF();
1732 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1733 return ConstantFP::get(Ty->getContext(), V);
1734 }
1735
Jakob Stoklund Olesen1f386c42010-09-27 21:29:20 +00001736 /// We only fold functions with finite arguments. Folding NaN and inf is
1737 /// likely to be aborted with an exception anyway, and some host libms
1738 /// have known errors raising exceptions.
1739 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper570e52c2014-04-15 04:59:12 +00001740 return nullptr;
Jakob Stoklund Olesen1f386c42010-09-27 21:29:20 +00001741
Dale Johannesen43421b32007-09-06 18:13:44 +00001742 /// Currently APFloat versions of these functions do not exist, so we use
1743 /// the host native double versions. Float versions are not called
1744 /// directly but for all these it is true (float)(f((double)arg)) ==
1745 /// f(arg). Long double not supported yet.
Matt Arsenault175c6342014-03-05 00:01:58 +00001746 double V = getValueAsDouble(Op);
Owen Anderson42258e02013-02-06 22:43:31 +00001747
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001748 switch (IntrinsicID) {
Owen Anderson42258e02013-02-06 22:43:31 +00001749 default: break;
1750 case Intrinsic::fabs:
1751 return ConstantFoldFP(fabs, V, Ty);
1752 case Intrinsic::log2:
Vince Harrona94bd7a2015-05-07 00:05:26 +00001753 return ConstantFoldFP(Log2, V, Ty);
Owen Anderson42258e02013-02-06 22:43:31 +00001754 case Intrinsic::log:
1755 return ConstantFoldFP(log, V, Ty);
1756 case Intrinsic::log10:
1757 return ConstantFoldFP(log10, V, Ty);
1758 case Intrinsic::exp:
1759 return ConstantFoldFP(exp, V, Ty);
1760 case Intrinsic::exp2:
1761 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd9dffa62015-07-08 03:55:47 +00001762 case Intrinsic::sin:
1763 return ConstantFoldFP(sin, V, Ty);
1764 case Intrinsic::cos:
1765 return ConstantFoldFP(cos, V, Ty);
Justin Lebar12044b32017-01-21 00:59:57 +00001766 case Intrinsic::sqrt:
1767 return ConstantFoldFP(sqrt, V, Ty);
Owen Anderson42258e02013-02-06 22:43:31 +00001768 }
1769
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001770 if (!TLI)
Craig Topper570e52c2014-04-15 04:59:12 +00001771 return nullptr;
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001772
Andrew Kaylor09976352017-05-12 22:11:20 +00001773 char NameKeyChar = Name[0];
1774 if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_')
1775 NameKeyChar = Name[2];
1776
1777 switch (NameKeyChar) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001778 case 'a':
David L. Jones32028c82017-01-23 23:16:46 +00001779 if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001780 (Name == "acosf" && TLI->has(LibFunc_acosf)) ||
1781 (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) ||
1782 (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001783 return ConstantFoldFP(acos, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001784 else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001785 (Name == "asinf" && TLI->has(LibFunc_asinf)) ||
1786 (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) ||
1787 (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001788 return ConstantFoldFP(asin, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001789 else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1790 (Name == "atanf" && TLI->has(LibFunc_atanf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001791 return ConstantFoldFP(atan, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001792 break;
1793 case 'c':
David L. Jones32028c82017-01-23 23:16:46 +00001794 if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1795 (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001796 return ConstantFoldFP(ceil, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001797 else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1798 (Name == "cosf" && TLI->has(LibFunc_cosf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001799 return ConstantFoldFP(cos, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001800 else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001801 (Name == "coshf" && TLI->has(LibFunc_coshf)) ||
1802 (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) ||
1803 (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001804 return ConstantFoldFP(cosh, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001805 break;
1806 case 'e':
David L. Jones32028c82017-01-23 23:16:46 +00001807 if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001808 (Name == "expf" && TLI->has(LibFunc_expf)) ||
1809 (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) ||
1810 (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001811 return ConstantFoldFP(exp, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001812 if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001813 (Name == "exp2f" && TLI->has(LibFunc_exp2f)) ||
1814 (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) ||
1815 (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite)))
Chris Lattner805fa972011-05-22 22:22:35 +00001816 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1817 // C99 library.
1818 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001819 break;
1820 case 'f':
David L. Jones32028c82017-01-23 23:16:46 +00001821 if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1822 (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001823 return ConstantFoldFP(fabs, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001824 else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1825 (Name == "floorf" && TLI->has(LibFunc_floorf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001826 return ConstantFoldFP(floor, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001827 break;
1828 case 'l':
David L. Jones32028c82017-01-23 23:16:46 +00001829 if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001830 (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) ||
1831 (Name == "__log_finite" && V > 0 &&
1832 TLI->has(LibFunc_log_finite)) ||
1833 (Name == "__logf_finite" && V > 0 &&
1834 TLI->has(LibFunc_logf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001835 return ConstantFoldFP(log, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001836 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001837 (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) ||
1838 (Name == "__log10_finite" && V > 0 &&
1839 TLI->has(LibFunc_log10_finite)) ||
1840 (Name == "__log10f_finite" && V > 0 &&
1841 TLI->has(LibFunc_log10f_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001842 return ConstantFoldFP(log10, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001843 break;
Bryant Wong5825ccc2016-12-26 14:29:29 +00001844 case 'r':
David L. Jones32028c82017-01-23 23:16:46 +00001845 if ((Name == "round" && TLI->has(LibFunc_round)) ||
1846 (Name == "roundf" && TLI->has(LibFunc_roundf)))
Bryant Wong5825ccc2016-12-26 14:29:29 +00001847 return ConstantFoldFP(round, V, Ty);
Galina Kistanovaed2e12d2017-05-31 20:25:13 +00001848 break;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001849 case 's':
David L. Jones32028c82017-01-23 23:16:46 +00001850 if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1851 (Name == "sinf" && TLI->has(LibFunc_sinf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001852 return ConstantFoldFP(sin, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001853 else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001854 (Name == "sinhf" && TLI->has(LibFunc_sinhf)) ||
1855 (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) ||
1856 (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001857 return ConstantFoldFP(sinh, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001858 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1859 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001860 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001861 break;
1862 case 't':
David L. Jones32028c82017-01-23 23:16:46 +00001863 if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1864 (Name == "tanf" && TLI->has(LibFunc_tanf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001865 return ConstantFoldFP(tan, V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001866 else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1867 (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001868 return ConstantFoldFP(tanh, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001869 break;
1870 default:
1871 break;
John Criswellbd9d3702005-10-27 16:00:10 +00001872 }
Craig Topper570e52c2014-04-15 04:59:12 +00001873 return nullptr;
Chris Lattner68a06032009-10-05 05:00:35 +00001874 }
Chandler Carruthf4db8772011-01-10 09:02:58 +00001875
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001876 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001877 switch (IntrinsicID) {
Chandler Carruthf4db8772011-01-10 09:02:58 +00001878 case Intrinsic::bswap:
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001879 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruthf4db8772011-01-10 09:02:58 +00001880 case Intrinsic::ctpop:
Owen Andersoneed707b2009-07-24 23:12:02 +00001881 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault23f7a822016-03-21 15:00:35 +00001882 case Intrinsic::bitreverse:
1883 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruthf4db8772011-01-10 09:02:58 +00001884 case Intrinsic::convert_from_fp16: {
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001885 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001886
1887 bool lost = false;
Andrea Di Biagio56a56612015-05-14 18:01:48 +00001888 APFloat::opStatus status = Val.convert(
1889 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001890
1891 // Conversion is always precise.
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +00001892 (void)status;
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001893 assert(status == APFloat::opOK && !lost &&
1894 "Precision lost during fp16 constfolding");
1895
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001896 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikovfaa75f6e2010-03-19 00:36:35 +00001897 }
Chandler Carruthf4db8772011-01-10 09:02:58 +00001898 default:
Craig Topper570e52c2014-04-15 04:59:12 +00001899 return nullptr;
Chandler Carruthf4db8772011-01-10 09:02:58 +00001900 }
John Criswellbd9d3702005-10-27 16:00:10 +00001901 }
Chandler Carruthf4db8772011-01-10 09:02:58 +00001902
Chris Lattner6b0dc922012-01-26 21:37:55 +00001903 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001904 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner6b0dc922012-01-26 21:37:55 +00001905 isa<ConstantDataVector>(Operands[0])) {
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001906 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001907 switch (IntrinsicID) {
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001908 default: break;
1909 case Intrinsic::x86_sse_cvtss2si:
1910 case Intrinsic::x86_sse_cvtss2si64:
1911 case Intrinsic::x86_sse2_cvtsd2si:
1912 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner6b0dc922012-01-26 21:37:55 +00001913 if (ConstantFP *FPOp =
Simon Pilgrim0f9cdd22016-07-19 15:07:43 +00001914 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1915 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
Craig Topper3bc13522018-08-12 22:09:54 +00001916 /*roundTowardZero=*/false, Ty,
1917 /*IsSigned*/true);
Craig Topper54bf6032017-06-04 08:21:51 +00001918 break;
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001919 case Intrinsic::x86_sse_cvttss2si:
1920 case Intrinsic::x86_sse_cvttss2si64:
1921 case Intrinsic::x86_sse2_cvttsd2si:
1922 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner6b0dc922012-01-26 21:37:55 +00001923 if (ConstantFP *FPOp =
Simon Pilgrim0f9cdd22016-07-19 15:07:43 +00001924 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1925 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
Craig Topper3bc13522018-08-12 22:09:54 +00001926 /*roundTowardZero=*/true, Ty,
1927 /*IsSigned*/true);
Craig Topper54bf6032017-06-04 08:21:51 +00001928 break;
Chandler Carruth15ed90c2011-01-11 01:07:24 +00001929 }
1930 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00001931
Craig Topper570e52c2014-04-15 04:59:12 +00001932 return nullptr;
Chris Lattner68a06032009-10-05 05:00:35 +00001933 }
Chandler Carruthf4db8772011-01-10 09:02:58 +00001934
Jay Foad1d2f5692011-07-19 13:32:40 +00001935 if (Operands.size() == 2) {
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001936 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson42258e02013-02-06 22:43:31 +00001937 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper570e52c2014-04-15 04:59:12 +00001938 return nullptr;
Matt Arsenault175c6342014-03-05 00:01:58 +00001939 double Op1V = getValueAsDouble(Op1);
Owen Anderson42258e02013-02-06 22:43:31 +00001940
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001941 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001942 if (Op2->getType() != Op1->getType())
Craig Topper570e52c2014-04-15 04:59:12 +00001943 return nullptr;
Chad Rosier21646e82011-12-01 23:16:03 +00001944
Matt Arsenault175c6342014-03-05 00:01:58 +00001945 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001946 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier24fbf2b2011-12-03 00:00:03 +00001947 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1948 }
Karthik Bhatdf95a942014-03-06 05:32:52 +00001949 if (IntrinsicID == Intrinsic::copysign) {
1950 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer34ae7b52016-02-13 16:54:14 +00001951 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdf95a942014-03-06 05:32:52 +00001952 V1.copySign(V2);
1953 return ConstantFP::get(Ty->getContext(), V1);
1954 }
Matt Arsenault25213462014-10-21 23:00:20 +00001955
1956 if (IntrinsicID == Intrinsic::minnum) {
1957 const APFloat &C1 = Op1->getValueAPF();
1958 const APFloat &C2 = Op2->getValueAPF();
1959 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1960 }
1961
1962 if (IntrinsicID == Intrinsic::maxnum) {
1963 const APFloat &C1 = Op1->getValueAPF();
1964 const APFloat &C2 = Op2->getValueAPF();
1965 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1966 }
1967
Thomas Livelyaff56dc2018-10-19 18:15:32 +00001968 if (IntrinsicID == Intrinsic::minimum) {
1969 const APFloat &C1 = Op1->getValueAPF();
1970 const APFloat &C2 = Op2->getValueAPF();
1971 return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
1972 }
1973
1974 if (IntrinsicID == Intrinsic::maximum) {
1975 const APFloat &C1 = Op1->getValueAPF();
1976 const APFloat &C2 = Op2->getValueAPF();
1977 return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
1978 }
1979
Chad Rosier24fbf2b2011-12-03 00:00:03 +00001980 if (!TLI)
Craig Topper570e52c2014-04-15 04:59:12 +00001981 return nullptr;
David L. Jones32028c82017-01-23 23:16:46 +00001982 if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001983 (Name == "powf" && TLI->has(LibFunc_powf)) ||
1984 (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) ||
1985 (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001986 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001987 if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1988 (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001989 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
David L. Jones32028c82017-01-23 23:16:46 +00001990 if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
Andrew Kaylor09976352017-05-12 22:11:20 +00001991 (Name == "atan2f" && TLI->has(LibFunc_atan2f)) ||
1992 (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) ||
1993 (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001994 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer0c6dbcc2016-07-13 04:22:12 +00001995 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer4d36f912014-03-05 19:41:48 +00001996 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1997 return ConstantFP::get(Ty->getContext(),
Owen Anderson42258e02013-02-06 22:43:31 +00001998 APFloat((float)std::pow((float)Op1V,
1999 (int)Op2C->getZExtValue())));
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002000 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2001 return ConstantFP::get(Ty->getContext(),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002002 APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +00002003 (int)Op2C->getZExtValue())));
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002004 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2005 return ConstantFP::get(Ty->getContext(),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002006 APFloat((double)std::pow((double)Op1V,
2007 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +00002008 }
Craig Topper570e52c2014-04-15 04:59:12 +00002009 return nullptr;
John Criswellbd9d3702005-10-27 16:00:10 +00002010 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00002011
Nikita Popov01f4bc22019-01-11 21:18:00 +00002012 if (Operands[0]->getType()->isIntegerTy() &&
2013 Operands[1]->getType()->isIntegerTy()) {
2014 const APInt *C0, *C1;
2015 if (!getConstIntOrUndef(Operands[0], C0) ||
2016 !getConstIntOrUndef(Operands[1], C1))
2017 return nullptr;
2018
2019 switch (IntrinsicID) {
2020 default: break;
2021 case Intrinsic::smul_with_overflow:
2022 case Intrinsic::umul_with_overflow:
2023 // Even if both operands are undef, we cannot fold muls to undef
2024 // in the general case. For example, on i2 there are no inputs
2025 // that would produce { i2 -1, i1 true } as the result.
2026 if (!C0 || !C1)
2027 return Constant::getNullValue(Ty);
2028 LLVM_FALLTHROUGH;
2029 case Intrinsic::sadd_with_overflow:
2030 case Intrinsic::uadd_with_overflow:
2031 case Intrinsic::ssub_with_overflow:
2032 case Intrinsic::usub_with_overflow: {
2033 if (!C0 || !C1)
2034 return UndefValue::get(Ty);
2035
2036 APInt Res;
2037 bool Overflow;
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002038 switch (IntrinsicID) {
Nikita Popov01f4bc22019-01-11 21:18:00 +00002039 default: llvm_unreachable("Invalid case");
Chris Lattnereafc5cb2010-10-14 00:05:07 +00002040 case Intrinsic::sadd_with_overflow:
Nikita Popov01f4bc22019-01-11 21:18:00 +00002041 Res = C0->sadd_ov(*C1, Overflow);
2042 break;
Chris Lattnereafc5cb2010-10-14 00:05:07 +00002043 case Intrinsic::uadd_with_overflow:
Nikita Popov01f4bc22019-01-11 21:18:00 +00002044 Res = C0->uadd_ov(*C1, Overflow);
2045 break;
Chris Lattnereafc5cb2010-10-14 00:05:07 +00002046 case Intrinsic::ssub_with_overflow:
Nikita Popov01f4bc22019-01-11 21:18:00 +00002047 Res = C0->ssub_ov(*C1, Overflow);
2048 break;
Chris Lattnereafc5cb2010-10-14 00:05:07 +00002049 case Intrinsic::usub_with_overflow:
Nikita Popov01f4bc22019-01-11 21:18:00 +00002050 Res = C0->usub_ov(*C1, Overflow);
2051 break;
Frits van Bommel62086102011-03-27 14:26:13 +00002052 case Intrinsic::smul_with_overflow:
Nikita Popov01f4bc22019-01-11 21:18:00 +00002053 Res = C0->smul_ov(*C1, Overflow);
2054 break;
2055 case Intrinsic::umul_with_overflow:
2056 Res = C0->umul_ov(*C1, Overflow);
2057 break;
Chris Lattnere65cd402009-10-05 05:26:04 +00002058 }
Nikita Popov01f4bc22019-01-11 21:18:00 +00002059 Constant *Ops[] = {
2060 ConstantInt::get(Ty->getContext(), Res),
2061 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2062 };
2063 return ConstantStruct::get(cast<StructType>(Ty), Ops);
2064 }
2065 case Intrinsic::uadd_sat:
2066 case Intrinsic::sadd_sat:
2067 if (!C0 && !C1)
2068 return UndefValue::get(Ty);
2069 if (!C0 || !C1)
2070 return Constant::getAllOnesValue(Ty);
2071 if (IntrinsicID == Intrinsic::uadd_sat)
2072 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2073 else
2074 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2075 case Intrinsic::usub_sat:
2076 case Intrinsic::ssub_sat:
2077 if (!C0 && !C1)
2078 return UndefValue::get(Ty);
2079 if (!C0 || !C1)
2080 return Constant::getNullValue(Ty);
2081 if (IntrinsicID == Intrinsic::usub_sat)
2082 return ConstantInt::get(Ty, C0->usub_sat(*C1));
2083 else
2084 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2085 case Intrinsic::cttz:
2086 case Intrinsic::ctlz:
2087 assert(C1 && "Must be constant int");
2088
2089 // cttz(0, 1) and ctlz(0, 1) are undef.
2090 if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2091 return UndefValue::get(Ty);
2092 if (!C0)
2093 return Constant::getNullValue(Ty);
2094 if (IntrinsicID == Intrinsic::cttz)
2095 return ConstantInt::get(Ty, C0->countTrailingZeros());
2096 else
2097 return ConstantInt::get(Ty, C0->countLeadingZeros());
Chris Lattnere65cd402009-10-05 05:26:04 +00002098 }
NAKAMURA Takumidb2b2852012-11-05 00:11:11 +00002099
Craig Topper570e52c2014-04-15 04:59:12 +00002100 return nullptr;
Chris Lattnere65cd402009-10-05 05:26:04 +00002101 }
Craig Topper3bc13522018-08-12 22:09:54 +00002102
2103 // Support ConstantVector in case we have an Undef in the top.
2104 if ((isa<ConstantVector>(Operands[0]) ||
2105 isa<ConstantDataVector>(Operands[0])) &&
2106 // Check for default rounding mode.
2107 // FIXME: Support other rounding modes?
2108 isa<ConstantInt>(Operands[1]) &&
2109 cast<ConstantInt>(Operands[1])->getValue() == 4) {
2110 auto *Op = cast<Constant>(Operands[0]);
2111 switch (IntrinsicID) {
2112 default: break;
2113 case Intrinsic::x86_avx512_vcvtss2si32:
2114 case Intrinsic::x86_avx512_vcvtss2si64:
2115 case Intrinsic::x86_avx512_vcvtsd2si32:
2116 case Intrinsic::x86_avx512_vcvtsd2si64:
2117 if (ConstantFP *FPOp =
2118 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2119 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2120 /*roundTowardZero=*/false, Ty,
2121 /*IsSigned*/true);
2122 break;
2123 case Intrinsic::x86_avx512_vcvtss2usi32:
2124 case Intrinsic::x86_avx512_vcvtss2usi64:
2125 case Intrinsic::x86_avx512_vcvtsd2usi32:
2126 case Intrinsic::x86_avx512_vcvtsd2usi64:
2127 if (ConstantFP *FPOp =
2128 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2129 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2130 /*roundTowardZero=*/false, Ty,
2131 /*IsSigned*/false);
2132 break;
2133 case Intrinsic::x86_avx512_cvttss2si:
2134 case Intrinsic::x86_avx512_cvttss2si64:
2135 case Intrinsic::x86_avx512_cvttsd2si:
2136 case Intrinsic::x86_avx512_cvttsd2si64:
2137 if (ConstantFP *FPOp =
2138 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2139 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2140 /*roundTowardZero=*/true, Ty,
2141 /*IsSigned*/true);
2142 break;
2143 case Intrinsic::x86_avx512_cvttss2usi:
2144 case Intrinsic::x86_avx512_cvttss2usi64:
2145 case Intrinsic::x86_avx512_cvttsd2usi:
2146 case Intrinsic::x86_avx512_cvttsd2usi64:
2147 if (ConstantFP *FPOp =
2148 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2149 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2150 /*roundTowardZero=*/true, Ty,
2151 /*IsSigned*/false);
2152 break;
2153 }
2154 }
Craig Topper570e52c2014-04-15 04:59:12 +00002155 return nullptr;
John Criswellbd9d3702005-10-27 16:00:10 +00002156 }
Matt Arsenault34fae3a2014-03-05 00:02:00 +00002157
2158 if (Operands.size() != 3)
Craig Topper570e52c2014-04-15 04:59:12 +00002159 return nullptr;
Matt Arsenault34fae3a2014-03-05 00:02:00 +00002160
David Majnemer0c6dbcc2016-07-13 04:22:12 +00002161 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2162 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2163 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002164 switch (IntrinsicID) {
Matt Arsenault34fae3a2014-03-05 00:02:00 +00002165 default: break;
2166 case Intrinsic::fma:
2167 case Intrinsic::fmuladd: {
2168 APFloat V = Op1->getValueAPF();
2169 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
2170 Op3->getValueAPF(),
2171 APFloat::rmNearestTiesToEven);
2172 if (s != APFloat::opInvalidOp)
2173 return ConstantFP::get(Ty->getContext(), V);
2174
Craig Topper570e52c2014-04-15 04:59:12 +00002175 return nullptr;
Matt Arsenault34fae3a2014-03-05 00:02:00 +00002176 }
2177 }
2178 }
2179 }
2180 }
2181
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002182 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
Nikita Popov01f4bc22019-01-11 21:18:00 +00002183 const APInt *C0, *C1, *C2;
2184 if (!getConstIntOrUndef(Operands[0], C0) ||
2185 !getConstIntOrUndef(Operands[1], C1) ||
2186 !getConstIntOrUndef(Operands[2], C2))
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002187 return nullptr;
2188
Nikita Popov01f4bc22019-01-11 21:18:00 +00002189 bool IsRight = IntrinsicID == Intrinsic::fshr;
2190 if (!C2)
2191 return Operands[IsRight ? 1 : 0];
2192 if (!C0 && !C1)
2193 return UndefValue::get(Ty);
2194
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002195 // The shift amount is interpreted as modulo the bitwidth. If the shift
2196 // amount is effectively 0, avoid UB due to oversized inverse shift below.
Nikita Popov01f4bc22019-01-11 21:18:00 +00002197 unsigned BitWidth = C2->getBitWidth();
2198 unsigned ShAmt = C2->urem(BitWidth);
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002199 if (!ShAmt)
Nikita Popov01f4bc22019-01-11 21:18:00 +00002200 return Operands[IsRight ? 1 : 0];
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002201
Nikita Popov01f4bc22019-01-11 21:18:00 +00002202 // (C0 << ShlAmt) | (C1 >> LshrAmt)
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002203 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2204 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
Nikita Popov01f4bc22019-01-11 21:18:00 +00002205 if (!C0)
2206 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2207 if (!C1)
2208 return ConstantInt::get(Ty, C0->shl(ShlAmt));
2209 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
Sanjay Patel77ce59d2018-08-17 13:23:44 +00002210 }
2211
Craig Topper570e52c2014-04-15 04:59:12 +00002212 return nullptr;
John Criswellbd9d3702005-10-27 16:00:10 +00002213}
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002214
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00002215Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
2216 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002217 const DataLayout &DL,
Manoj Guptac6da6862018-07-09 22:27:23 +00002218 const TargetLibraryInfo *TLI,
2219 ImmutableCallSite CS) {
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002220 SmallVector<Constant *, 4> Result(VTy->getNumElements());
2221 SmallVector<Constant *, 4> Lane(Operands.size());
2222 Type *Ty = VTy->getElementType();
2223
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002224 if (IntrinsicID == Intrinsic::masked_load) {
2225 auto *SrcPtr = Operands[0];
2226 auto *Mask = Operands[2];
2227 auto *Passthru = Operands[3];
David Majnemer6d67ce12016-07-14 06:58:37 +00002228
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002229 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002230
2231 SmallVector<Constant *, 32> NewElements;
2232 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer6d67ce12016-07-14 06:58:37 +00002233 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002234 if (!MaskElt)
2235 break;
David Majnemer6d67ce12016-07-14 06:58:37 +00002236 auto *PassthruElt = Passthru->getAggregateElement(I);
2237 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2238 if (isa<UndefValue>(MaskElt)) {
2239 if (PassthruElt)
2240 NewElements.push_back(PassthruElt);
2241 else if (VecElt)
2242 NewElements.push_back(VecElt);
2243 else
2244 return nullptr;
2245 }
2246 if (MaskElt->isNullValue()) {
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002247 if (!PassthruElt)
David Majnemer6d67ce12016-07-14 06:58:37 +00002248 return nullptr;
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002249 NewElements.push_back(PassthruElt);
David Majnemer6d67ce12016-07-14 06:58:37 +00002250 } else if (MaskElt->isOneValue()) {
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002251 if (!VecElt)
David Majnemer6d67ce12016-07-14 06:58:37 +00002252 return nullptr;
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002253 NewElements.push_back(VecElt);
David Majnemer6d67ce12016-07-14 06:58:37 +00002254 } else {
2255 return nullptr;
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002256 }
2257 }
David Majnemer6d67ce12016-07-14 06:58:37 +00002258 if (NewElements.size() != VTy->getNumElements())
2259 return nullptr;
2260 return ConstantVector::get(NewElements);
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002261 }
2262
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002263 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2264 // Gather a column of constants.
2265 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
Craig Topper02c1af02017-06-03 18:50:29 +00002266 // These intrinsics use a scalar type for their second argument.
2267 if (J == 1 &&
Craig Topperd3818182017-06-04 07:30:28 +00002268 (IntrinsicID == Intrinsic::cttz || IntrinsicID == Intrinsic::ctlz ||
2269 IntrinsicID == Intrinsic::powi)) {
Craig Topper02c1af02017-06-03 18:50:29 +00002270 Lane[J] = Operands[J];
2271 continue;
2272 }
2273
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002274 Constant *Agg = Operands[J]->getAggregateElement(I);
2275 if (!Agg)
2276 return nullptr;
2277
2278 Lane[J] = Agg;
2279 }
2280
2281 // Use the regular scalar folding to simplify this column.
Manoj Guptac6da6862018-07-09 22:27:23 +00002282 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, CS);
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002283 if (!Folded)
2284 return nullptr;
2285 Result[I] = Folded;
2286 }
2287
2288 return ConstantVector::get(Result);
2289}
2290
Eugene Zelenkod0a33c42016-03-28 17:40:08 +00002291} // end anonymous namespace
2292
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002293Constant *
Andrew Kaylorb8e91642017-06-09 23:18:11 +00002294llvm::ConstantFoldCall(ImmutableCallSite CS, Function *F,
2295 ArrayRef<Constant *> Operands,
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002296 const TargetLibraryInfo *TLI) {
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00002297 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylorb8e91642017-06-09 23:18:11 +00002298 return nullptr;
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002299 if (!F->hasName())
Craig Topper570e52c2014-04-15 04:59:12 +00002300 return nullptr;
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002301 StringRef Name = F->getName();
2302
2303 Type *Ty = F->getReturnType();
2304
David Majnemer0c6dbcc2016-07-13 04:22:12 +00002305 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer3dc0c3e2016-07-14 00:29:50 +00002306 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
Manoj Guptac6da6862018-07-09 22:27:23 +00002307 F->getParent()->getDataLayout(), TLI, CS);
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002308
Manoj Guptac6da6862018-07-09 22:27:23 +00002309 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI, CS);
Benjamin Kramer4d36f912014-03-05 19:41:48 +00002310}
Eli Friedmana7bfb152016-11-02 20:48:11 +00002311
2312bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2313 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2314 // (and to some extent ConstantFoldScalarCall).
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00002315 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylorb8e91642017-06-09 23:18:11 +00002316 return false;
Eli Friedmana7bfb152016-11-02 20:48:11 +00002317 Function *F = CS.getCalledFunction();
2318 if (!F)
2319 return false;
2320
David L. Jones32028c82017-01-23 23:16:46 +00002321 LibFunc Func;
Eli Friedmana7bfb152016-11-02 20:48:11 +00002322 if (!TLI || !TLI->getLibFunc(*F, Func))
2323 return false;
2324
2325 if (CS.getNumArgOperands() == 1) {
2326 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2327 const APFloat &Op = OpC->getValueAPF();
2328 switch (Func) {
David L. Jones32028c82017-01-23 23:16:46 +00002329 case LibFunc_logl:
2330 case LibFunc_log:
2331 case LibFunc_logf:
2332 case LibFunc_log2l:
2333 case LibFunc_log2:
2334 case LibFunc_log2f:
2335 case LibFunc_log10l:
2336 case LibFunc_log10:
2337 case LibFunc_log10f:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002338 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2339
David L. Jones32028c82017-01-23 23:16:46 +00002340 case LibFunc_expl:
2341 case LibFunc_exp:
2342 case LibFunc_expf:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002343 // FIXME: These boundaries are slightly conservative.
2344 if (OpC->getType()->isDoubleTy())
2345 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2346 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2347 if (OpC->getType()->isFloatTy())
2348 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2349 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2350 break;
2351
David L. Jones32028c82017-01-23 23:16:46 +00002352 case LibFunc_exp2l:
2353 case LibFunc_exp2:
2354 case LibFunc_exp2f:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002355 // FIXME: These boundaries are slightly conservative.
2356 if (OpC->getType()->isDoubleTy())
2357 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2358 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2359 if (OpC->getType()->isFloatTy())
2360 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2361 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2362 break;
2363
David L. Jones32028c82017-01-23 23:16:46 +00002364 case LibFunc_sinl:
2365 case LibFunc_sin:
2366 case LibFunc_sinf:
2367 case LibFunc_cosl:
2368 case LibFunc_cos:
2369 case LibFunc_cosf:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002370 return !Op.isInfinity();
2371
David L. Jones32028c82017-01-23 23:16:46 +00002372 case LibFunc_tanl:
2373 case LibFunc_tan:
2374 case LibFunc_tanf: {
Eli Friedmana7bfb152016-11-02 20:48:11 +00002375 // FIXME: Stop using the host math library.
2376 // FIXME: The computation isn't done in the right precision.
2377 Type *Ty = OpC->getType();
2378 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2379 double OpV = getValueAsDouble(OpC);
2380 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2381 }
2382 break;
2383 }
2384
David L. Jones32028c82017-01-23 23:16:46 +00002385 case LibFunc_asinl:
2386 case LibFunc_asin:
2387 case LibFunc_asinf:
2388 case LibFunc_acosl:
2389 case LibFunc_acos:
2390 case LibFunc_acosf:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002391 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2392 APFloat::cmpLessThan &&
2393 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2394 APFloat::cmpGreaterThan;
2395
David L. Jones32028c82017-01-23 23:16:46 +00002396 case LibFunc_sinh:
2397 case LibFunc_cosh:
2398 case LibFunc_sinhf:
2399 case LibFunc_coshf:
2400 case LibFunc_sinhl:
2401 case LibFunc_coshl:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002402 // FIXME: These boundaries are slightly conservative.
2403 if (OpC->getType()->isDoubleTy())
2404 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2405 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2406 if (OpC->getType()->isFloatTy())
2407 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2408 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2409 break;
2410
David L. Jones32028c82017-01-23 23:16:46 +00002411 case LibFunc_sqrtl:
2412 case LibFunc_sqrt:
2413 case LibFunc_sqrtf:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002414 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2415
2416 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2417 // maybe others?
2418 default:
2419 break;
2420 }
2421 }
2422 }
2423
2424 if (CS.getNumArgOperands() == 2) {
2425 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2426 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2427 if (Op0C && Op1C) {
2428 const APFloat &Op0 = Op0C->getValueAPF();
2429 const APFloat &Op1 = Op1C->getValueAPF();
2430
2431 switch (Func) {
David L. Jones32028c82017-01-23 23:16:46 +00002432 case LibFunc_powl:
2433 case LibFunc_pow:
2434 case LibFunc_powf: {
Eli Friedmana7bfb152016-11-02 20:48:11 +00002435 // FIXME: Stop using the host math library.
2436 // FIXME: The computation isn't done in the right precision.
2437 Type *Ty = Op0C->getType();
2438 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2439 if (Ty == Op1C->getType()) {
2440 double Op0V = getValueAsDouble(Op0C);
2441 double Op1V = getValueAsDouble(Op1C);
2442 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2443 }
2444 }
2445 break;
2446 }
2447
David L. Jones32028c82017-01-23 23:16:46 +00002448 case LibFunc_fmodl:
2449 case LibFunc_fmod:
2450 case LibFunc_fmodf:
Eli Friedmana7bfb152016-11-02 20:48:11 +00002451 return Op0.isNaN() || Op1.isNaN() ||
2452 (!Op0.isInfinity() && !Op1.isZero());
2453
2454 default:
2455 break;
2456 }
2457 }
2458 }
2459
2460 return false;
2461}