blob: 7b3d81577802d1b48f4f4a75740863404e29693d [file] [log] [blame]
Dan Gohman91d598d2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswell970af112005-10-27 16:00:10 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
John Criswell970af112005-10-27 16:00:10 +00006//
7//===----------------------------------------------------------------------===//
8//
Dan Gohman91d598d2009-09-10 23:07:18 +00009// This file defines routines for folding instructions into constants.
10//
Chandler Carruthef860a22013-01-02 09:10:48 +000011// Also, to supplement the basic IR ConstantExpr simplifications,
Dan Gohman91d598d2009-09-10 23:07:18 +000012// this file defines some additional folding routines that can make use of
Chandler Carruthef860a22013-01-02 09:10:48 +000013// DataLayout information. These functions cannot go in IR due to library
Dan Gohman91d598d2009-09-10 23:07:18 +000014// dependency issues.
John Criswell970af112005-10-27 16:00:10 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Analysis/ConstantFolding.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000019#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
David Majnemere61e4bf2016-06-21 05:10:24 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/StringRef.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ValueTracking.h"
Bjorn Pettersson485a4212019-06-24 12:07:17 +000028#include "llvm/Analysis/VectorUtils.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000029#include "llvm/Config/config.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-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 Zelenko1804a772016-08-25 00:45:04 +000035#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000045#include "llvm/Support/KnownBits.h"
John Criswell970af112005-10-27 16:00:10 +000046#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000047#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000048#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000049#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000050#include <cmath>
Eugene Zelenko1804a772016-08-25 00:45:04 +000051#include <cstddef>
52#include <cstdint>
Alp Tokerc817d6a2014-06-09 18:28:53 +000053
John Criswell970af112005-10-27 16:00:10 +000054using namespace llvm;
55
Eugene Zelenko35623fb2016-03-28 17:40:08 +000056namespace {
57
Chris Lattner44d68b92007-01-31 00:51:48 +000058//===----------------------------------------------------------------------===//
59// Constant Folding internal helper functions
60//===----------------------------------------------------------------------===//
61
Matt Arsenault47a4b392016-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 Arsenault624e1b32016-12-07 20:56:11 +000092/// Constant fold bitcast, symbolically evaluating it with DataLayout.
Sanjay Patel0d7dee62014-10-02 15:13:22 +000093/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000094/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000095Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-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 Lopesc29520c2014-10-22 12:18:48 +000099 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +0000101 return Constant::getAllOnesValue(DestTy);
102
Matt Arsenault624e1b32016-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 Espindolabb893fe2012-01-27 23:33:07 +0000108
Matt Arsenault624e1b32016-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 Takumidce89992012-11-05 00:11:11 +0000118
Matt Arsenault624e1b32016-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 Espindolabb893fe2012-01-27 23:33:07 +0000129 }
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000130 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000131
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000132 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000133 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000134 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000135 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000136
Chris Lattnerd8e8fb42009-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 Aminia28d91d2015-03-10 02:37:25 +0000141 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000142 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000143
Chris Lattner9d051242009-10-25 06:08:26 +0000144 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000145 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000146 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000147
Chandler Carruthef860a22013-01-02 09:10:48 +0000148 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000149 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000150 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000151 if (NumDstElt == NumSrcElt)
152 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000153
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000154 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000155 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000156
157 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-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 Takumidce89992012-11-05 00:11:11 +0000164
Chris Lattner9d051242009-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 Sands9dff9be2010-02-15 16:12:20 +0000167 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-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 Lattner229907c2011-07-18 04:54:35 +0000170 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000171 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000174
Chandler Carruthef860a22013-01-02 09:10:48 +0000175 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000176 return ConstantExpr::getBitCast(C, DestTy);
177 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000178
Chris Lattner9d051242009-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 Sands9dff9be2010-02-15 16:12:20 +0000181 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000182 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000183 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000184 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000185 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000186 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000187 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000188 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
189 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000190 return C;
191 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000192
Chris Lattner9d051242009-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 Aminia28d91d2015-03-10 02:37:25 +0000197 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000198
Chris Lattner9d051242009-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 Majnemere4218cf2016-07-29 04:06:09 +0000211 Constant *Src = C->getAggregateElement(SrcElt++);
212 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000213 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000214 else
215 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000216 if (!Src) // Reject constantexpr elements.
217 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000218
Chris Lattner9d051242009-10-25 06:08:26 +0000219 // Zero extend the element to the right size.
220 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000221
Chris Lattner9d051242009-10-25 06:08:26 +0000222 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000223 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000224 ConstantInt::get(Src->getType(), ShiftAmt));
225 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000226
Chris Lattner9d051242009-10-25 06:08:26 +0000227 // Mix it in.
228 Elt = ConstantExpr::getOr(Elt, Src);
229 }
230 Result.push_back(Elt);
231 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000232 return ConstantVector::get(Result);
233 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000234
Chris Lattner61a1d6c2012-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 Aminia28d91d2015-03-10 02:37:25 +0000237 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000238
Chris Lattner61a1d6c2012-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 Biagio7277afe2016-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 Lattner61a1d6c2012-01-26 21:37:55 +0000254 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000255
Chris Lattner61a1d6c2012-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 Takumidce89992012-11-05 00:11:11 +0000260 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000261 ConstantInt::get(Src->getType(), ShiftAmt));
262 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263
Bruno Cardoso Lopesc29520c2014-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 Lattner61a1d6c2012-01-26 21:37:55 +0000273 // Truncate and remember this piece.
274 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000275 }
276 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000277
Chris Lattner69229312011-02-15 00:14:00 +0000278 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000279}
280
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000281} // end anonymous namespace
282
Sanjay Patel0d7dee62014-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 Collingbourne265ebd72016-04-22 20:40:10 +0000285bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
286 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000287 // Trivial case, constant is the global.
288 if ((GV = dyn_cast<GlobalValue>(C))) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000289 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000290 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000291 return true;
292 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000293
Chris Lattner44d68b92007-01-31 00:51:48 +0000294 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000295 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000296 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000297
Chris Lattner44d68b92007-01-31 00:51:48 +0000298 // Look through ptr->int and ptr->ptr casts.
299 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000300 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000302
303 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000304 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000305 if (!GEP)
306 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000307
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000308 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000309 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000310
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000311 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000313 return false;
314
315 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000317 return false;
318
319 Offset = TmpOffset;
320 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000321}
322
Eugene Leviant6f42a2c2018-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 Popov79c994d2018-12-11 20:29:16 +0000350 // elements of an aggregate to see if some part of the aggregate is
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000351 // castable to implement the "load" semantic model.
Nikita Popov79c994d2018-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 Leviant6f42a2c2018-03-13 10:19:50 +0000364 } while (C);
365
366 return nullptr;
367}
368
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000369namespace {
370
Sanjay Patel0d7dee62014-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 Aminia28d91d2015-03-10 02:37:25 +0000374/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000375bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
376 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000377 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000378 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000379
Chris Lattner3db7bd22009-10-24 05:27:19 +0000380 // If this element is zero or undefined, we can just return since *CurPtr is
381 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000382 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
383 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000384
David Majnemer90a97042016-07-13 04:22:12 +0000385 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000386 if (CI->getBitWidth() > 64 ||
387 (CI->getBitWidth() & 7) != 0)
388 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000389
Chris Lattnered00b802009-10-23 06:23:49 +0000390 uint64_t Val = CI->getZExtValue();
391 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000392
Chris Lattnered00b802009-10-23 06:23:49 +0000393 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000394 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000396 n = IntBytes - n - 1;
397 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000398 ++ByteOffset;
399 }
400 return true;
401 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000402
David Majnemer90a97042016-07-13 04:22:12 +0000403 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000404 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
406 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000407 }
408 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000409 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
410 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000411 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000412 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
414 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000415 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000416 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000417 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000418
David Majnemer90a97042016-07-13 04:22:12 +0000419 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000420 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000421 unsigned Index = SL->getElementContainingOffset(ByteOffset);
422 uint64_t CurEltOffset = SL->getElementOffset(Index);
423 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000424
Eugene Zelenko1804a772016-08-25 00:45:04 +0000425 while (true) {
Chris Lattnered00b802009-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 Aminia28d91d2015-03-10 02:37:25 +0000428 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000429
430 if (ByteOffset < EltSize &&
431 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000433 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000434
Chris Lattnered00b802009-10-23 06:23:49 +0000435 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000436
Chris Lattnered00b802009-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 Arsenault8c789092013-08-12 23:15:58 +0000444 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000445 return true;
446
447 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000448 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
449 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000450 ByteOffset = 0;
451 CurEltOffset = NextEltOffset;
452 }
453 // not reached.
454 }
455
Chris Lattner67058832012-01-25 06:48:06 +0000456 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
457 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000458 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000460 uint64_t Index = ByteOffset / EltSize;
461 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000462 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000463 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000464 NumElts = AT->getNumElements();
465 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000466 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000467
Chris Lattner67058832012-01-25 06:48:06 +0000468 for (; Index != NumElts; ++Index) {
469 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000470 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000471 return false;
Duncan Sands0b875a02012-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 Lattner67058832012-01-25 06:48:06 +0000476 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000477
Chris Lattner67058832012-01-25 06:48:06 +0000478 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000479 BytesLeft -= BytesWritten;
480 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000481 }
482 return true;
483 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000484
David Majnemer90a97042016-07-13 04:22:12 +0000485 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000486 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000487 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000488 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000490 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000491 }
492
Chris Lattnered00b802009-10-23 06:23:49 +0000493 // Otherwise, unknown initializer type.
494 return false;
495}
496
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000497Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
498 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000499 auto *PTy = cast<PointerType>(C->getType());
500 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000501
Chris Lattnered00b802009-10-23 06:23:49 +0000502 // If this isn't an integer load we can't fold it directly.
503 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000504 unsigned AS = PTy->getAddressSpace();
505
Chris Lattnered00b802009-10-23 06:23:49 +0000506 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-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 Lattner229907c2011-07-18 04:54:35 +0000510 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000511 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000512 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000513 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000514 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000515 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000516 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000517 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000518 MapTy = PointerType::getIntNTy(C->getContext(),
Jay Foad45d19fb2019-06-19 10:28:48 +0000519 DL.getTypeSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000520 } else
Craig Topper9f008862014-04-15 04:59:12 +0000521 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000522
Eduard Burtescu14239212016-01-22 01:17:26 +0000523 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
524 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000525 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000526 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000527 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000528
Chris Lattnered00b802009-10-23 06:23:49 +0000529 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000530 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000531 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000532
Chris Lattnered00b802009-10-23 06:23:49 +0000533 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000534 APInt OffsetAI;
535 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000536 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000537
David Majnemer90a97042016-07-13 04:22:12 +0000538 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000539 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000540 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000541 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000542
David Majnemerf89660a2016-07-13 23:33:07 +0000543 int64_t Offset = OffsetAI.getSExtValue();
544 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000545
Chris Lattnered00b802009-10-23 06:23:49 +0000546 // If we're not accessing anything in this constant, the result is undefined.
Alina Sbirlea7153f272019-07-31 18:22:22 +0000547 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
David Majnemerf89660a2016-07-13 23:33:07 +0000548 return UndefValue::get(IntType);
549
550 // If we're not accessing anything in this constant, the result is undefined.
551 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000552 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000553
Chris Lattner59f94c02009-10-23 06:50:36 +0000554 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-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 Topper9f008862014-04-15 04:59:12 +0000566 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000567
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000568 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000569 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000570 ResultVal = RawBytes[BytesLoaded - 1];
571 for (unsigned i = 1; i != BytesLoaded; ++i) {
572 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000573 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-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 Lattner59f94c02009-10-23 06:50:36 +0000581 }
Chris Lattnered00b802009-10-23 06:23:49 +0000582
Chris Lattner59f94c02009-10-23 06:50:36 +0000583 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000584}
585
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000586Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
587 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000588 auto *SrcPtr = CE->getOperand(0);
589 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
590 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000591 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000592 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000593
Eduard Burtescu14239212016-01-22 01:17:26 +0000594 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000595 if (!C)
596 return nullptr;
597
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000598 return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000599}
600
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000601} // end anonymous namespace
602
Eduard Burtescu14239212016-01-22 01:17:26 +0000603Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000605 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000606 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000607 if (GV->isConstant() && GV->hasDefinitiveInitializer())
608 return GV->getInitializer();
609
David Majnemered9abe12015-07-22 22:29:30 +0000610 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000611 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000612 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000613
Chris Lattnercf7e8942009-10-22 06:44:07 +0000614 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000615 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000616 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000617 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000618
Chris Lattnercf7e8942009-10-22 06:44:07 +0000619 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000620 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000621 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000622 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000623 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
624 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000625 }
626 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000627 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000628
Chandler Carrutha0e56952014-05-15 09:56:28 +0000629 if (CE->getOpcode() == Instruction::BitCast)
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000630 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000631 return LoadedC;
632
Chris Lattnercf7e8942009-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 Lattnercf9e8f62012-02-05 02:29:43 +0000635 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000637 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000638 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-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 Carruth57041d82010-07-12 06:47:05 +0000642 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000643 APInt StrVal(NumBits, 0);
644 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000646 for (unsigned char C : reverse(Str.bytes())) {
647 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000648 StrVal = (StrVal << 8) | SingleChar;
649 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000650 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000651 for (unsigned char C : Str.bytes()) {
652 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-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 Lattner51d2f702009-10-22 06:38:35 +0000658 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000659
Chris Lattnerfd4a09f2010-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 Lattner51d2f702009-10-22 06:38:35 +0000664 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000665 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000666
Chris Lattnercf7e8942009-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 Majnemer90a97042016-07-13 04:22:12 +0000669 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000670 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000671 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000672 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000673 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000674 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000675 }
676 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000677
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000678 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000679 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000680}
681
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000682namespace {
683
684Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000685 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000686
David Majnemer90a97042016-07-13 04:22:12 +0000687 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000688 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000689
Craig Topper9f008862014-04-15 04:59:12 +0000690 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000691}
Chris Lattner44d68b92007-01-31 00:51:48 +0000692
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000693/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000694/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-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 Zelenko35623fb2016-03-28 17:40:08 +0000697Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
698 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000699 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000700
Chris Lattner44d68b92007-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 Takumidce89992012-11-05 00:11:11 +0000704
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000705 if (Opc == Instruction::And) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000706 KnownBits Known0 = computeKnownBits(Op0, DL);
707 KnownBits Known1 = computeKnownBits(Op1, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000708 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-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 Topperb45eabc2017-04-26 16:39:58 +0000712 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-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 Topper8189a872017-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 Lewycky06417742013-02-14 03:23:37 +0000721 }
722
Chris Lattner44d68b92007-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 Aminia28d91d2015-03-10 02:37:25 +0000725 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000726 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000727 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000728
Mehdi Aminia28d91d2015-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 Arsenaultbed5bf22013-09-12 01:07:58 +0000732
Chris Lattner44d68b92007-01-31 00:51:48 +0000733 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-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 Lattner44d68b92007-01-31 00:51:48 +0000738 }
739 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000740
Craig Topper9f008862014-04-15 04:59:12 +0000741 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000742}
743
Sanjay Patel0d7dee62014-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 Zelenko35623fb2016-03-28 17:40:08 +0000746Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourned93620b2016-11-10 22:34:55 +0000747 Type *ResultTy, Optional<unsigned> InRangeIndex,
748 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000749 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischerdc091192016-12-08 17:22:35 +0000750 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000751
752 bool Any = false;
753 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000754 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000755 if ((i == 1 ||
Keno Fischerdc091192016-12-08 17:22:35 +0000756 !isa<StructType>(GetElementPtrInst::getIndexedType(
757 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kupersteindd92c782016-12-21 17:34:21 +0000758 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000759 Any = true;
Michael Kupersteindd92c782016-12-21 17:34:21 +0000760 Type *NewType = Ops[i]->getType()->isVectorTy()
761 ? IntPtrTy
762 : IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000763 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
764 true,
Michael Kupersteindd92c782016-12-21 17:34:21 +0000765 NewType,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000766 true),
Michael Kupersteindd92c782016-12-21 17:34:21 +0000767 Ops[i], NewType));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000768 } else
769 NewIdxs.push_back(Ops[i]);
770 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000771
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000772 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000773 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000774
Peter Collingbourned93620b2016-11-10 22:34:55 +0000775 Constant *C = ConstantExpr::getGetElementPtr(
776 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemerd536f232016-07-29 03:27:26 +0000777 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
778 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000779
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000780 return C;
781}
782
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000783/// Strip the pointer casts, but preserve the address space information.
Peter Collingbourne2452d702019-08-22 19:56:14 +0000784Constant *StripPtrCastKeepAS(Constant *Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000785 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000786 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Peter Collingbourne2452d702019-08-22 19:56:14 +0000787 Ptr = cast<Constant>(Ptr->stripPointerCasts());
David Majnemer90a97042016-07-13 04:22:12 +0000788 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000789
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000790 ElemTy = NewPtrTy->getPointerElementType();
791
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000792 // Preserve the address space number of the pointer.
793 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000794 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000795 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000796 }
797 return Ptr;
798}
799
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000800/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000801Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
802 ArrayRef<Constant *> Ops,
803 const DataLayout &DL,
804 const TargetLibraryInfo *TLI) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000805 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000806 bool InBounds = GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000807
Eduard Burtescu2f4758b2016-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 Collingbourned93620b2016-11-10 22:34:55 +0000814 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
815 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000816 return C;
817
Chris Lattner44d68b92007-01-31 00:51:48 +0000818 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000819 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000820 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000821
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000822 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-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 Foadf4b14a22011-07-19 13:32:40 +0000826 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000827 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000828
Elena Demikhovsky945b7e52018-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 Lattner5858e092011-01-06 06:19:46 +0000844 }
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000845 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000846 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000847
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000848 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000849 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000850 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000851 DL.getIndexedOffsetInType(
852 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000853 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000854 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000855
856 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000857 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000858 InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000859 InBounds &= GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000860
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000861 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-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 Majnemer90a97042016-07-13 04:22:12 +0000865 for (Value *NestedOp : NestedOps)
866 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000867 AllConstantInt = false;
868 break;
869 }
870 if (!AllConstantInt)
871 break;
872
Dan Gohman474e488c2010-03-10 19:31:51 +0000873 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000874 SrcElemTy = GEP->getSourceElementType();
875 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000876 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000877 }
878
Dan Gohman81ce8422009-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 Gohmana5ca5782010-03-18 19:34:33 +0000881 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000882 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000883 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000884 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000885 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000886 }
887 }
888
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000889 auto *PTy = cast<PointerType>(Ptr->getType());
890 if ((Ptr->isNullValue() || BasePtr != 0) &&
891 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000892 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000893 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-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 Das6fa08aa2016-08-05 19:23:29 +0000900 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000901 SmallVector<Constant *, 32> NewIdxs;
902
Dan Gohmanc59ba422009-08-19 22:46:59 +0000903 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000904 if (!Ty->isStructTy()) {
905 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-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 Takumidce89992012-11-05 00:11:11 +0000909
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000910 Ty = SrcElemTy;
911
Chris Lattner77c36d62009-12-03 01:05:45 +0000912 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000913 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000914 return nullptr;
Eduard Burtescu2f4758b2016-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 Lattner77c36d62009-12-03 01:05:45 +0000920 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000921
Dan Gohman81ce8422009-08-19 18:18:36 +0000922 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000923 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000924 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000925 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-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 Lattner6ce03802010-11-21 08:39:01 +0000928 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000929 } else {
Chris Lattner6ce03802010-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 Majnemer4cff2f82016-07-13 15:53:46 +0000932 bool Overflow;
933 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
934 if (Overflow)
935 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000936 Offset -= NewIdx * ElemSize;
937 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
938 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000939 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000940 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-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 Aminia28d91d2015-03-10 02:37:25 +0000945 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000946 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-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 Gohman23e62c52009-08-21 16:52:54 +0000952 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000953 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
954 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000955 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000956 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000957 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000958 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-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 Topper9f008862014-04-15 04:59:12 +0000964 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000965
Peter Collingbourned93620b2016-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 Collingbournec7d28192018-09-11 01:53:36 +0000974 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
975 return nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +0000976 }
977
Dan Gohman21c62162009-09-11 00:04:14 +0000978 // Create a GEP.
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000979 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
980 InBounds, InRangeIndex);
Matt Arsenault8c789092013-08-12 23:15:58 +0000981 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000982 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000983
Dan Gohmanc59ba422009-08-19 22:46:59 +0000984 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000985 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000986 if (Ty != ResElemTy)
987 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000988
989 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000990}
991
Manuel Jacobe9024592016-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 Majnemera926b3e2016-07-29 03:27:33 +0000997Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000998 ArrayRef<Constant *> Ops,
999 const DataLayout &DL,
1000 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001001 Type *DestTy = InstOrCE->getType();
1002
Cameron McInally1d0c8452019-05-05 16:07:09 +00001003 if (Instruction::isUnaryOp(Opcode))
1004 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1005
Manuel Jacobe9024592016-01-21 06:33:22 +00001006 if (Instruction::isBinaryOp(Opcode))
1007 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1008
1009 if (Instruction::isCast(Opcode))
1010 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1011
David Majnemer17bdf442016-07-13 03:42:38 +00001012 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001013 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1014 return C;
1015
Peter Collingbourned93620b2016-11-10 22:34:55 +00001016 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1017 Ops.slice(1), GEP->isInBounds(),
1018 GEP->getInRangeIndex());
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001019 }
1020
David Majnemer57b94c82016-07-29 03:27:31 +00001021 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1022 return CE->getWithOperands(Ops);
1023
Manuel Jacobe9024592016-01-21 06:33:22 +00001024 switch (Opcode) {
1025 default: return nullptr;
1026 case Instruction::ICmp:
1027 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1028 case Instruction::Call:
Andrew Kaylor647025f2017-06-09 23:18:11 +00001029 if (auto *F = dyn_cast<Function>(Ops.back())) {
Chandler Carruth751d95f2019-02-11 07:51:44 +00001030 const auto *Call = cast<CallBase>(InstOrCE);
1031 if (canConstantFoldCallTo(Call, F))
1032 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
Andrew Kaylor647025f2017-06-09 23:18:11 +00001033 }
Manuel Jacobe9024592016-01-21 06:33:22 +00001034 return nullptr;
1035 case Instruction::Select:
1036 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1037 case Instruction::ExtractElement:
1038 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chen Zheng627095e2019-07-11 02:18:22 +00001039 case Instruction::ExtractValue:
1040 return ConstantExpr::getExtractValue(
1041 Ops[0], dyn_cast<ExtractValueInst>(InstOrCE)->getIndices());
Manuel Jacobe9024592016-01-21 06:33:22 +00001042 case Instruction::InsertElement:
1043 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1044 case Instruction::ShuffleVector:
1045 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +00001046 }
1047}
1048
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001049} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +00001050
1051//===----------------------------------------------------------------------===//
1052// Constant Folding public APIs
1053//===----------------------------------------------------------------------===//
1054
David Majnemerd536f232016-07-29 03:27:26 +00001055namespace {
1056
1057Constant *
1058ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1059 const TargetLibraryInfo *TLI,
1060 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1061 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1062 return nullptr;
1063
1064 SmallVector<Constant *, 8> Ops;
1065 for (const Use &NewU : C->operands()) {
1066 auto *NewC = cast<Constant>(&NewU);
1067 // Recursively fold the ConstantExpr's operands. If we have already folded
1068 // a ConstantExpr, we don't have to process it again.
1069 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1070 auto It = FoldedOps.find(NewC);
1071 if (It == FoldedOps.end()) {
1072 if (auto *FoldedC =
1073 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
David Majnemerd536f232016-07-29 03:27:26 +00001074 FoldedOps.insert({NewC, FoldedC});
David Greenda211702017-03-21 10:17:39 +00001075 NewC = FoldedC;
David Majnemerd536f232016-07-29 03:27:26 +00001076 } else {
1077 FoldedOps.insert({NewC, NewC});
1078 }
1079 } else {
1080 NewC = It->second;
1081 }
1082 }
1083 Ops.push_back(NewC);
1084 }
1085
1086 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1087 if (CE->isCompare())
1088 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1089 DL, TLI);
1090
David Majnemera926b3e2016-07-29 03:27:33 +00001091 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001092 }
1093
1094 assert(isa<ConstantVector>(C));
1095 return ConstantVector::get(Ops);
1096}
1097
1098} // end anonymous namespace
1099
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001100Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001101 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001102 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001103 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001104 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001105
David Majnemerd536f232016-07-29 03:27:26 +00001106 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001107 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001108 // If the incoming value is undef then skip it. Note that while we could
1109 // skip the value if it is equal to the phi node itself we choose not to
1110 // because that would break the rule that constant folding only applies if
1111 // all operands are constants.
1112 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001113 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001114 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001115 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001116 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001117 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001118 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001119 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1120 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001121 // If the incoming value is a different constant to
1122 // the one we saw previously, then give up.
1123 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001124 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001125 CommonValue = C;
1126 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001127
Duncan Sands1d27f0122010-11-14 12:53:18 +00001128 // If we reach here, all incoming values are the same constant or undef.
1129 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001130 }
1131
1132 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001133 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001134 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1135 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001136
David Majnemerd536f232016-07-29 03:27:26 +00001137 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001138 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001139 for (const Use &OpU : I->operands()) {
1140 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001141 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001142 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1143 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001144
1145 Ops.push_back(Op);
1146 }
1147
David Majnemer90a97042016-07-13 04:22:12 +00001148 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001149 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001150 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001151
David Majnemer90a97042016-07-13 04:22:12 +00001152 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001153 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001154
David Majnemer90a97042016-07-13 04:22:12 +00001155 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001156 return ConstantExpr::getInsertValue(
1157 cast<Constant>(IVI->getAggregateOperand()),
1158 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001159 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001160 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001161
David Majnemer90a97042016-07-13 04:22:12 +00001162 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001163 return ConstantExpr::getExtractValue(
1164 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001165 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001166 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001167
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001168 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001169}
1170
David Majnemerd536f232016-07-29 03:27:26 +00001171Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1172 const TargetLibraryInfo *TLI) {
1173 SmallDenseMap<Constant *, Constant *> FoldedOps;
1174 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001175}
1176
Manuel Jacobe9024592016-01-21 06:33:22 +00001177Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001178 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001179 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001180 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001181 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001182}
1183
Chris Lattnerd2265b42007-12-10 22:53:04 +00001184Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001185 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001186 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001187 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001188 // fold: icmp (inttoptr x), null -> icmp x, 0
Craig Topperb23e7c72017-06-02 16:17:32 +00001189 // fold: icmp null, (inttoptr x) -> icmp 0, x
Chris Lattnerd2265b42007-12-10 22:53:04 +00001190 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Craig Topperb23e7c72017-06-02 16:17:32 +00001191 // fold: icmp 0, (ptrtoint x) -> icmp null, x
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001192 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001193 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1194 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001195 // FIXME: The following comment is out of data and the DataLayout is here now.
1196 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001197 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001198 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001200 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001201 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001202 // Convert the integer value to the right size to ensure we get the
1203 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001204 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001205 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001206 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001207 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001208 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001209
Chris Lattnerd2265b42007-12-10 22:53:04 +00001210 // Only do this transformation if the int is intptrty in size, otherwise
1211 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001212 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001213 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001214 if (CE0->getType() == IntPtrTy) {
1215 Constant *C = CE0->getOperand(0);
1216 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001217 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001218 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001219 }
1220 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001221
David Majnemer90a97042016-07-13 04:22:12 +00001222 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001223 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001224 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001225 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001226
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001227 // Convert the integer value to the right size to ensure we get the
1228 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001229 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001230 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001231 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001232 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001233 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001234 }
1235
Chandler Carruth7ec50852012-11-01 08:07:29 +00001236 // Only do this transformation if the int is intptrty in size, otherwise
1237 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001238 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001239 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001240 if (CE0->getType() == IntPtrTy &&
1241 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242 return ConstantFoldCompareInstOperands(
1243 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001244 }
1245 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001246 }
1247 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001248
Chris Lattner8fb74c62010-01-02 01:22:23 +00001249 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1250 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1251 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1252 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001253 Constant *LHS = ConstantFoldCompareInstOperands(
1254 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1255 Constant *RHS = ConstantFoldCompareInstOperands(
1256 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001257 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001258 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001259 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001260 }
Craig Topperb23e7c72017-06-02 16:17:32 +00001261 } else if (isa<ConstantExpr>(Ops1)) {
1262 // If RHS is a constant expression, but the left side isn't, swap the
1263 // operands and try again.
1264 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1265 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001266 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001267
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001268 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001269}
1270
Cameron McInally1d0c8452019-05-05 16:07:09 +00001271Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1272 const DataLayout &DL) {
1273 assert(Instruction::isUnaryOp(Opcode));
1274
1275 return ConstantExpr::get(Opcode, Op);
1276}
1277
Manuel Jacoba61ca372016-01-21 06:26:35 +00001278Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1279 Constant *RHS,
1280 const DataLayout &DL) {
1281 assert(Instruction::isBinaryOp(Opcode));
1282 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1283 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1284 return C;
1285
1286 return ConstantExpr::get(Opcode, LHS, RHS);
1287}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001288
Manuel Jacob925d0292016-01-21 06:31:08 +00001289Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1290 Type *DestTy, const DataLayout &DL) {
1291 assert(Instruction::isCast(Opcode));
1292 switch (Opcode) {
1293 default:
1294 llvm_unreachable("Missing case");
1295 case Instruction::PtrToInt:
1296 // If the input is a inttoptr, eliminate the pair. This requires knowing
1297 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001298 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001299 if (CE->getOpcode() == Instruction::IntToPtr) {
1300 Constant *Input = CE->getOperand(0);
1301 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1302 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1303 if (PtrWidth < InWidth) {
1304 Constant *Mask =
1305 ConstantInt::get(CE->getContext(),
1306 APInt::getLowBitsSet(InWidth, PtrWidth));
1307 Input = ConstantExpr::getAnd(Input, Mask);
1308 }
1309 // Do a zext or trunc to get to the dest size.
1310 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1311 }
1312 }
1313 return ConstantExpr::getCast(Opcode, C, DestTy);
1314 case Instruction::IntToPtr:
1315 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1316 // the int size is >= the ptr size and the address spaces are the same.
1317 // This requires knowing the width of a pointer, so it can't be done in
1318 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001319 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001320 if (CE->getOpcode() == Instruction::PtrToInt) {
1321 Constant *SrcPtr = CE->getOperand(0);
1322 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1323 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1324
1325 if (MidIntSize >= SrcPtrSize) {
1326 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1327 if (SrcAS == DestTy->getPointerAddressSpace())
1328 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1329 }
1330 }
1331 }
1332
1333 return ConstantExpr::getCast(Opcode, C, DestTy);
1334 case Instruction::Trunc:
1335 case Instruction::ZExt:
1336 case Instruction::SExt:
1337 case Instruction::FPTrunc:
1338 case Instruction::FPExt:
1339 case Instruction::UIToFP:
1340 case Instruction::SIToFP:
1341 case Instruction::FPToUI:
1342 case Instruction::FPToSI:
1343 case Instruction::AddrSpaceCast:
1344 return ConstantExpr::getCast(Opcode, C, DestTy);
1345 case Instruction::BitCast:
1346 return FoldBitCast(C, DestTy, DL);
1347 }
1348}
1349
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001350Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001351 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001352 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001353 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001354
1355 // Loop over all of the operands, tracking down which value we are
1356 // addressing.
1357 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1358 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001359 if (!C)
1360 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001361 }
1362 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001363}
1364
David Majnemer90a97042016-07-13 04:22:12 +00001365Constant *
1366llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1367 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001368 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001369 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001370 for (Constant *Index : Indices) {
1371 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001372 if (!C)
1373 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001374 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001375 return C;
1376}
1377
Chris Lattner2ae054a2007-01-30 23:45:45 +00001378//===----------------------------------------------------------------------===//
1379// Constant Folding for Calls
1380//
John Criswell970af112005-10-27 16:00:10 +00001381
Chandler Carruth751d95f2019-02-11 07:51:44 +00001382bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1383 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00001384 return false;
John Criswell970af112005-10-27 16:00:10 +00001385 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001386 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001387 case Intrinsic::minnum:
1388 case Intrinsic::maxnum:
Thomas Livelyfa54e562018-10-19 18:15:32 +00001389 case Intrinsic::minimum:
1390 case Intrinsic::maximum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001391 case Intrinsic::log:
1392 case Intrinsic::log2:
1393 case Intrinsic::log10:
1394 case Intrinsic::exp:
1395 case Intrinsic::exp2:
1396 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001397 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001398 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001399 case Intrinsic::sin:
1400 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001401 case Intrinsic::trunc:
1402 case Intrinsic::rint:
1403 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001404 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001405 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001406 case Intrinsic::bswap:
1407 case Intrinsic::ctpop:
1408 case Intrinsic::ctlz:
1409 case Intrinsic::cttz:
Sanjay Patel411b8602018-08-17 13:23:44 +00001410 case Intrinsic::fshl:
1411 case Intrinsic::fshr:
Matt Arsenault83778582014-03-05 00:02:00 +00001412 case Intrinsic::fma:
1413 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001414 case Intrinsic::copysign:
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001415 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001416 case Intrinsic::strip_invariant_group:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001417 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001418 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001419 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001420 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001421 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001422 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001423 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001424 case Intrinsic::umul_with_overflow:
Sanjay Patelefc3d1d2018-11-20 17:05:55 +00001425 case Intrinsic::sadd_sat:
1426 case Intrinsic::uadd_sat:
1427 case Intrinsic::ssub_sat:
1428 case Intrinsic::usub_sat:
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00001429 case Intrinsic::smul_fix:
1430 case Intrinsic::smul_fix_sat:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001431 case Intrinsic::convert_from_fp16:
1432 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001433 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001434 case Intrinsic::x86_sse_cvtss2si:
1435 case Intrinsic::x86_sse_cvtss2si64:
1436 case Intrinsic::x86_sse_cvttss2si:
1437 case Intrinsic::x86_sse_cvttss2si64:
1438 case Intrinsic::x86_sse2_cvtsd2si:
1439 case Intrinsic::x86_sse2_cvtsd2si64:
1440 case Intrinsic::x86_sse2_cvttsd2si:
1441 case Intrinsic::x86_sse2_cvttsd2si64:
Craig Topper484b3422018-08-12 22:09:54 +00001442 case Intrinsic::x86_avx512_vcvtss2si32:
1443 case Intrinsic::x86_avx512_vcvtss2si64:
1444 case Intrinsic::x86_avx512_cvttss2si:
1445 case Intrinsic::x86_avx512_cvttss2si64:
1446 case Intrinsic::x86_avx512_vcvtsd2si32:
1447 case Intrinsic::x86_avx512_vcvtsd2si64:
1448 case Intrinsic::x86_avx512_cvttsd2si:
1449 case Intrinsic::x86_avx512_cvttsd2si64:
1450 case Intrinsic::x86_avx512_vcvtss2usi32:
1451 case Intrinsic::x86_avx512_vcvtss2usi64:
1452 case Intrinsic::x86_avx512_cvttss2usi:
1453 case Intrinsic::x86_avx512_cvttss2usi64:
1454 case Intrinsic::x86_avx512_vcvtsd2usi32:
1455 case Intrinsic::x86_avx512_vcvtsd2usi64:
1456 case Intrinsic::x86_avx512_cvttsd2usi:
1457 case Intrinsic::x86_avx512_cvttsd2usi64:
James Y Knight72f76bf2018-11-07 15:24:12 +00001458 case Intrinsic::is_constant:
John Criswell970af112005-10-27 16:00:10 +00001459 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001460 default:
1461 return false;
Craig Topper492db482017-04-07 21:36:32 +00001462 case Intrinsic::not_intrinsic: break;
John Criswell970af112005-10-27 16:00:10 +00001463 }
1464
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001465 if (!F->hasName())
1466 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001467
Chris Lattner785f9982007-08-08 06:55:43 +00001468 // In these cases, the check of the length is required. We don't want to
1469 // return true for a name like "cos\0blah" which strcmp would return equal to
1470 // "cos", but has length 8.
Evandro Menezes6f136972019-09-06 16:49:49 +00001471 StringRef Name = F->getName();
Daniel Dunbarca414c72009-07-26 08:34:35 +00001472 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001473 default:
1474 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001475 case 'a':
Evandro Menezes6f136972019-09-06 16:49:49 +00001476 return Name == "acos" || Name == "acosf" ||
1477 Name == "asin" || Name == "asinf" ||
1478 Name == "atan" || Name == "atanf" ||
1479 Name == "atan2" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001480 case 'c':
Evandro Menezes6f136972019-09-06 16:49:49 +00001481 return Name == "ceil" || Name == "ceilf" ||
1482 Name == "cos" || Name == "cosf" ||
1483 Name == "cosh" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001484 case 'e':
Evandro Menezes6f136972019-09-06 16:49:49 +00001485 return Name == "exp" || Name == "expf" ||
1486 Name == "exp2" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001487 case 'f':
Evandro Menezes6f136972019-09-06 16:49:49 +00001488 return Name == "fabs" || Name == "fabsf" ||
1489 Name == "floor" || Name == "floorf" ||
1490 Name == "fmod" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001491 case 'l':
Evandro Menezes6f136972019-09-06 16:49:49 +00001492 return Name == "log" || Name == "logf" ||
1493 Name == "log10" || Name == "log10f";
Evandro Menezes08df6e62019-09-12 21:23:22 +00001494 case 'n':
1495 return Name == "nearbyint" || Name == "nearbyintf";
Chris Lattner785f9982007-08-08 06:55:43 +00001496 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001497 return Name == "pow" || Name == "powf";
Bryant Wongb5e03b62016-12-26 14:29:29 +00001498 case 'r':
Evandro Menezes08df6e62019-09-12 21:23:22 +00001499 return Name == "rint" || Name == "rintf" ||
1500 Name == "round" || Name == "roundf";
Chris Lattner785f9982007-08-08 06:55:43 +00001501 case 's':
Evandro Menezes6f136972019-09-06 16:49:49 +00001502 return Name == "sin" || Name == "sinf" ||
1503 Name == "sinh" || Name == "sinhf" ||
1504 Name == "sqrt" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001505 case 't':
Evandro Menezes6f136972019-09-06 16:49:49 +00001506 return Name == "tan" || Name == "tanf" ||
Evandro Menezes08df6e62019-09-12 21:23:22 +00001507 Name == "tanh" || Name == "tanhf" ||
1508 Name == "trunc" || Name == "truncf";
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001509 case '_':
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001510 // Check for various function names that get used for the math functions
1511 // when the header files are preprocessed with the macro
1512 // __FINITE_MATH_ONLY__ enabled.
1513 // The '12' here is the length of the shortest name that can match.
1514 // We need to check the size before looking at Name[1] and Name[2]
1515 // so we may as well check a limit that will eliminate mismatches.
1516 if (Name.size() < 12 || Name[1] != '_')
1517 return false;
1518 switch (Name[2]) {
1519 default:
1520 return false;
1521 case 'a':
1522 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1523 Name == "__asin_finite" || Name == "__asinf_finite" ||
1524 Name == "__atan2_finite" || Name == "__atan2f_finite";
1525 case 'c':
1526 return Name == "__cosh_finite" || Name == "__coshf_finite";
1527 case 'e':
1528 return Name == "__exp_finite" || Name == "__expf_finite" ||
1529 Name == "__exp2_finite" || Name == "__exp2f_finite";
1530 case 'l':
1531 return Name == "__log_finite" || Name == "__logf_finite" ||
1532 Name == "__log10_finite" || Name == "__log10f_finite";
1533 case 'p':
1534 return Name == "__pow_finite" || Name == "__powf_finite";
1535 case 's':
1536 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1537 }
John Criswell970af112005-10-27 16:00:10 +00001538 }
1539}
1540
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001541namespace {
1542
1543Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Bixia Zhengbdf02302019-03-22 16:37:37 +00001544 if (Ty->isHalfTy() || Ty->isFloatTy()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001545 APFloat APF(V);
1546 bool unused;
Bixia Zhengbdf02302019-03-22 16:37:37 +00001547 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001548 return ConstantFP::get(Ty->getContext(), APF);
1549 }
Chris Lattner351534f2009-10-05 05:06:24 +00001550 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001551 return ConstantFP::get(Ty->getContext(), APFloat(V));
Xin Tongc063c3f2017-10-01 00:09:53 +00001552 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001553}
1554
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001555/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001556inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001557#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001558 feclearexcept(FE_ALL_EXCEPT);
1559#endif
1560 errno = 0;
1561}
1562
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001563/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001564inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001565 int errno_val = errno;
1566 if (errno_val == ERANGE || errno_val == EDOM)
1567 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001568#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001569 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1570 return true;
1571#endif
1572 return false;
1573}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001574
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001575Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001576 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001577 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001578 if (llvm_fenv_testexcept()) {
1579 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001580 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001581 }
1582
1583 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001584}
1585
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001586Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1587 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001588 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001589 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001590 if (llvm_fenv_testexcept()) {
1591 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001592 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001593 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001594
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001595 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001596}
1597
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001598/// Attempt to fold an SSE floating point to integer conversion of a constant
1599/// floating point. If roundTowardZero is false, the default IEEE rounding is
1600/// used (toward nearest, ties to even). This matches the behavior of the
1601/// non-truncating SSE instructions in the default rounding mode. The desired
1602/// integer type Ty is used to select how many bits are available for the
1603/// result. Returns null if the conversion cannot be performed, otherwise
1604/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001605Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
Craig Topper484b3422018-08-12 22:09:54 +00001606 Type *Ty, bool IsSigned) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001607 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001608 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001609 assert(ResultWidth <= 64 &&
1610 "Can only constant fold conversions to 64 and 32 bit ints");
1611
1612 uint64_t UIntVal;
1613 bool isExact = false;
1614 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1615 : APFloat::rmNearestTiesToEven;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001616 APFloat::opStatus status =
1617 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
Craig Topper484b3422018-08-12 22:09:54 +00001618 IsSigned, mode, &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001619 if (status != APFloat::opOK &&
1620 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001621 return nullptr;
Craig Topper484b3422018-08-12 22:09:54 +00001622 return ConstantInt::get(Ty, UIntVal, IsSigned);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001623}
1624
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001625double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001626 Type *Ty = Op->getType();
1627
1628 if (Ty->isFloatTy())
1629 return Op->getValueAPF().convertToFloat();
1630
1631 if (Ty->isDoubleTy())
1632 return Op->getValueAPF().convertToDouble();
1633
1634 bool unused;
1635 APFloat APF = Op->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001636 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001637 return APF.convertToDouble();
1638}
1639
James Y Knight72f76bf2018-11-07 15:24:12 +00001640static bool isManifestConstant(const Constant *c) {
1641 if (isa<ConstantData>(c)) {
1642 return true;
1643 } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1644 for (const Value *subc : c->operand_values()) {
1645 if (!isManifestConstant(cast<Constant>(subc)))
1646 return false;
1647 }
1648 return true;
1649 }
1650 return false;
1651}
1652
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00001653static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1654 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1655 C = &CI->getValue();
1656 return true;
1657 }
1658 if (isa<UndefValue>(Op)) {
1659 C = nullptr;
1660 return true;
1661 }
1662 return false;
1663}
1664
Bjorn Pettersson485a4212019-06-24 12:07:17 +00001665static Constant *ConstantFoldScalarCall1(StringRef Name,
1666 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001667 Type *Ty,
1668 ArrayRef<Constant *> Operands,
1669 const TargetLibraryInfo *TLI,
1670 const CallBase *Call) {
1671 assert(Operands.size() == 1 && "Wrong number of operands.");
1672
1673 if (IntrinsicID == Intrinsic::is_constant) {
1674 // We know we have a "Constant" argument. But we want to only
1675 // return true for manifest constants, not those that depend on
1676 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1677 if (isManifestConstant(Operands[0]))
1678 return ConstantInt::getTrue(Ty->getContext());
1679 return nullptr;
1680 }
1681 if (isa<UndefValue>(Operands[0])) {
1682 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1683 // ctpop() is between 0 and bitwidth, pick 0 for undef.
1684 if (IntrinsicID == Intrinsic::cos ||
1685 IntrinsicID == Intrinsic::ctpop)
1686 return Constant::getNullValue(Ty);
1687 if (IntrinsicID == Intrinsic::bswap ||
1688 IntrinsicID == Intrinsic::bitreverse ||
1689 IntrinsicID == Intrinsic::launder_invariant_group ||
1690 IntrinsicID == Intrinsic::strip_invariant_group)
1691 return Operands[0];
1692 }
1693
1694 if (isa<ConstantPointerNull>(Operands[0])) {
1695 // launder(null) == null == strip(null) iff in addrspace 0
1696 if (IntrinsicID == Intrinsic::launder_invariant_group ||
1697 IntrinsicID == Intrinsic::strip_invariant_group) {
1698 // If instruction is not yet put in a basic block (e.g. when cloning
1699 // a function during inlining), Call's caller may not be available.
1700 // So check Call's BB first before querying Call->getCaller.
1701 const Function *Caller =
1702 Call->getParent() ? Call->getCaller() : nullptr;
1703 if (Caller &&
1704 !NullPointerIsDefined(
1705 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1706 return Operands[0];
1707 }
James Y Knight72f76bf2018-11-07 15:24:12 +00001708 return nullptr;
1709 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001710 }
1711
1712 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1713 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1714 APFloat Val(Op->getValueAPF());
1715
1716 bool lost = false;
1717 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1718
1719 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001720 }
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001721
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001722 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1723 return nullptr;
1724
Evandro Menezesed5f4522019-09-11 21:46:57 +00001725 // Use internal versions of these intrinsics.
1726 APFloat U = Op->getValueAPF();
1727
1728 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1729 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1730 return ConstantFP::get(Ty->getContext(), U);
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001731 }
1732
Evandro Menezesed5f4522019-09-11 21:46:57 +00001733 if (IntrinsicID == Intrinsic::round) {
1734 U.roundToIntegral(APFloat::rmNearestTiesToAway);
1735 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001736 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001737
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001738 if (IntrinsicID == Intrinsic::ceil) {
Evandro Menezesed5f4522019-09-11 21:46:57 +00001739 U.roundToIntegral(APFloat::rmTowardPositive);
1740 return ConstantFP::get(Ty->getContext(), U);
1741 }
1742
1743 if (IntrinsicID == Intrinsic::floor) {
1744 U.roundToIntegral(APFloat::rmTowardNegative);
1745 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001746 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001747
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001748 if (IntrinsicID == Intrinsic::trunc) {
Evandro Menezesed5f4522019-09-11 21:46:57 +00001749 U.roundToIntegral(APFloat::rmTowardZero);
1750 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001751 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001752
Evandro Menezesed5f4522019-09-11 21:46:57 +00001753 if (IntrinsicID == Intrinsic::fabs) {
1754 U.clearSign();
1755 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001756 }
1757
1758 /// We only fold functions with finite arguments. Folding NaN and inf is
1759 /// likely to be aborted with an exception anyway, and some host libms
1760 /// have known errors raising exceptions.
1761 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1762 return nullptr;
1763
1764 /// Currently APFloat versions of these functions do not exist, so we use
1765 /// the host native double versions. Float versions are not called
1766 /// directly but for all these it is true (float)(f((double)arg)) ==
1767 /// f(arg). Long double not supported yet.
1768 double V = getValueAsDouble(Op);
1769
1770 switch (IntrinsicID) {
1771 default: break;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001772 case Intrinsic::log:
1773 return ConstantFoldFP(log, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001774 case Intrinsic::log2:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001775 // TODO: What about hosts that lack a C99 library?
Evandro Menezes6f136972019-09-06 16:49:49 +00001776 return ConstantFoldFP(Log2, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001777 case Intrinsic::log10:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001778 // TODO: What about hosts that lack a C99 library?
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001779 return ConstantFoldFP(log10, V, Ty);
1780 case Intrinsic::exp:
1781 return ConstantFoldFP(exp, V, Ty);
1782 case Intrinsic::exp2:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001783 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
1784 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001785 case Intrinsic::sin:
1786 return ConstantFoldFP(sin, V, Ty);
1787 case Intrinsic::cos:
1788 return ConstantFoldFP(cos, V, Ty);
1789 case Intrinsic::sqrt:
1790 return ConstantFoldFP(sqrt, V, Ty);
1791 }
1792
1793 if (!TLI)
1794 return nullptr;
1795
Evandro Menezes6f136972019-09-06 16:49:49 +00001796 LibFunc Func = NotLibFunc;
1797 TLI->getLibFunc(Name, Func);
Evandro Menezes6f136972019-09-06 16:49:49 +00001798 switch (Func) {
1799 default:
1800 break;
1801 case LibFunc_acos:
1802 case LibFunc_acosf:
1803 case LibFunc_acos_finite:
1804 case LibFunc_acosf_finite:
1805 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001806 return ConstantFoldFP(acos, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001807 break;
1808 case LibFunc_asin:
1809 case LibFunc_asinf:
1810 case LibFunc_asin_finite:
1811 case LibFunc_asinf_finite:
1812 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001813 return ConstantFoldFP(asin, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001814 break;
1815 case LibFunc_atan:
1816 case LibFunc_atanf:
1817 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001818 return ConstantFoldFP(atan, V, Ty);
1819 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001820 case LibFunc_ceil:
1821 case LibFunc_ceilf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001822 if (TLI->has(Func)) {
1823 U.roundToIntegral(APFloat::rmTowardPositive);
1824 return ConstantFP::get(Ty->getContext(), U);
1825 }
Evandro Menezes6f136972019-09-06 16:49:49 +00001826 break;
1827 case LibFunc_cos:
1828 case LibFunc_cosf:
1829 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001830 return ConstantFoldFP(cos, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001831 break;
1832 case LibFunc_cosh:
1833 case LibFunc_coshf:
1834 case LibFunc_cosh_finite:
1835 case LibFunc_coshf_finite:
1836 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001837 return ConstantFoldFP(cosh, V, Ty);
1838 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001839 case LibFunc_exp:
1840 case LibFunc_expf:
1841 case LibFunc_exp_finite:
1842 case LibFunc_expf_finite:
1843 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001844 return ConstantFoldFP(exp, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001845 break;
1846 case LibFunc_exp2:
1847 case LibFunc_exp2f:
1848 case LibFunc_exp2_finite:
1849 case LibFunc_exp2f_finite:
1850 if (TLI->has(Func))
1851 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001852 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1853 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001854 case LibFunc_fabs:
1855 case LibFunc_fabsf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001856 if (TLI->has(Func)) {
1857 U.clearSign();
1858 return ConstantFP::get(Ty->getContext(), U);
1859 }
Evandro Menezes6f136972019-09-06 16:49:49 +00001860 break;
1861 case LibFunc_floor:
1862 case LibFunc_floorf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001863 if (TLI->has(Func)) {
1864 U.roundToIntegral(APFloat::rmTowardNegative);
1865 return ConstantFP::get(Ty->getContext(), U);
1866 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001867 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001868 case LibFunc_log:
1869 case LibFunc_logf:
1870 case LibFunc_log_finite:
1871 case LibFunc_logf_finite:
1872 if (V > 0.0 && TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001873 return ConstantFoldFP(log, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001874 break;
1875 case LibFunc_log10:
1876 case LibFunc_log10f:
1877 case LibFunc_log10_finite:
1878 case LibFunc_log10f_finite:
1879 if (V > 0.0 && TLI->has(Func))
Evandro Menezes7feb8122019-09-06 18:24:21 +00001880 // TODO: What about hosts that lack a C99 library?
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001881 return ConstantFoldFP(log10, V, Ty);
1882 break;
Evandro Menezes08df6e62019-09-12 21:23:22 +00001883 case LibFunc_nearbyint:
1884 case LibFunc_nearbyintf:
1885 case LibFunc_rint:
1886 case LibFunc_rintf:
1887 if (TLI->has(Func)) {
1888 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1889 return ConstantFP::get(Ty->getContext(), U);
1890 }
1891 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001892 case LibFunc_round:
1893 case LibFunc_roundf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001894 if (TLI->has(Func)) {
1895 U.roundToIntegral(APFloat::rmNearestTiesToAway);
1896 return ConstantFP::get(Ty->getContext(), U);
1897 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001898 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001899 case LibFunc_sin:
1900 case LibFunc_sinf:
1901 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001902 return ConstantFoldFP(sin, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001903 break;
1904 case LibFunc_sinh:
1905 case LibFunc_sinhf:
1906 case LibFunc_sinh_finite:
1907 case LibFunc_sinhf_finite:
1908 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001909 return ConstantFoldFP(sinh, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001910 break;
1911 case LibFunc_sqrt:
1912 case LibFunc_sqrtf:
1913 if (V >= 0.0 && TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001914 return ConstantFoldFP(sqrt, V, Ty);
1915 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001916 case LibFunc_tan:
1917 case LibFunc_tanf:
1918 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001919 return ConstantFoldFP(tan, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001920 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001921 case LibFunc_tanh:
1922 case LibFunc_tanhf:
1923 if (TLI->has(Func))
1924 return ConstantFoldFP(tanh, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001925 break;
Evandro Menezes08df6e62019-09-12 21:23:22 +00001926 case LibFunc_trunc:
1927 case LibFunc_truncf:
1928 if (TLI->has(Func)) {
1929 U.roundToIntegral(APFloat::rmTowardZero);
1930 return ConstantFP::get(Ty->getContext(), U);
1931 }
1932 break;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001933 }
1934 return nullptr;
1935 }
1936
1937 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
1938 switch (IntrinsicID) {
1939 case Intrinsic::bswap:
1940 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1941 case Intrinsic::ctpop:
1942 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1943 case Intrinsic::bitreverse:
1944 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1945 case Intrinsic::convert_from_fp16: {
1946 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
1947
1948 bool lost = false;
1949 APFloat::opStatus status = Val.convert(
1950 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1951
1952 // Conversion is always precise.
1953 (void)status;
1954 assert(status == APFloat::opOK && !lost &&
1955 "Precision lost during fp16 constfolding");
1956
1957 return ConstantFP::get(Ty->getContext(), Val);
1958 }
1959 default:
1960 return nullptr;
1961 }
1962 }
1963
1964 // Support ConstantVector in case we have an Undef in the top.
1965 if (isa<ConstantVector>(Operands[0]) ||
1966 isa<ConstantDataVector>(Operands[0])) {
1967 auto *Op = cast<Constant>(Operands[0]);
1968 switch (IntrinsicID) {
1969 default: break;
1970 case Intrinsic::x86_sse_cvtss2si:
1971 case Intrinsic::x86_sse_cvtss2si64:
1972 case Intrinsic::x86_sse2_cvtsd2si:
1973 case Intrinsic::x86_sse2_cvtsd2si64:
1974 if (ConstantFP *FPOp =
1975 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1976 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1977 /*roundTowardZero=*/false, Ty,
1978 /*IsSigned*/true);
1979 break;
1980 case Intrinsic::x86_sse_cvttss2si:
1981 case Intrinsic::x86_sse_cvttss2si64:
1982 case Intrinsic::x86_sse2_cvttsd2si:
1983 case Intrinsic::x86_sse2_cvttsd2si64:
1984 if (ConstantFP *FPOp =
1985 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1986 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1987 /*roundTowardZero=*/true, Ty,
1988 /*IsSigned*/true);
1989 break;
1990 }
1991 }
1992
1993 return nullptr;
1994}
1995
Bjorn Pettersson485a4212019-06-24 12:07:17 +00001996static Constant *ConstantFoldScalarCall2(StringRef Name,
1997 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001998 Type *Ty,
1999 ArrayRef<Constant *> Operands,
2000 const TargetLibraryInfo *TLI,
2001 const CallBase *Call) {
2002 assert(Operands.size() == 2 && "Wrong number of operands.");
2003
2004 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2005 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2006 return nullptr;
2007 double Op1V = getValueAsDouble(Op1);
2008
2009 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2010 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00002011 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00002012
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002013 double Op2V = getValueAsDouble(Op2);
2014 if (IntrinsicID == Intrinsic::pow) {
2015 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2016 }
2017 if (IntrinsicID == Intrinsic::copysign) {
2018 APFloat V1 = Op1->getValueAPF();
2019 const APFloat &V2 = Op2->getValueAPF();
2020 V1.copySign(V2);
2021 return ConstantFP::get(Ty->getContext(), V1);
Karthik Bhatb67688a2014-03-07 04:36:21 +00002022 }
2023
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002024 if (IntrinsicID == Intrinsic::minnum) {
2025 const APFloat &C1 = Op1->getValueAPF();
2026 const APFloat &C2 = Op2->getValueAPF();
2027 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002028 }
2029
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002030 if (IntrinsicID == Intrinsic::maxnum) {
2031 const APFloat &C1 = Op1->getValueAPF();
2032 const APFloat &C2 = Op2->getValueAPF();
2033 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002034 }
2035
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002036 if (IntrinsicID == Intrinsic::minimum) {
2037 const APFloat &C1 = Op1->getValueAPF();
2038 const APFloat &C2 = Op2->getValueAPF();
2039 return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002040 }
2041
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002042 if (IntrinsicID == Intrinsic::maximum) {
2043 const APFloat &C1 = Op1->getValueAPF();
2044 const APFloat &C2 = Op2->getValueAPF();
2045 return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
Owen Andersond4ebfd82013-02-06 22:43:31 +00002046 }
2047
Benjamin Kramer061d1472014-03-05 19:41:48 +00002048 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00002049 return nullptr;
Evandro Menezes6f136972019-09-06 16:49:49 +00002050
2051 LibFunc Func = NotLibFunc;
2052 TLI->getLibFunc(Name, Func);
2053 switch (Func) {
2054 default:
2055 break;
2056 case LibFunc_pow:
2057 case LibFunc_powf:
2058 case LibFunc_pow_finite:
2059 case LibFunc_powf_finite:
2060 if (TLI->has(Func))
2061 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2062 break;
2063 case LibFunc_fmod:
2064 case LibFunc_fmodf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00002065 if (TLI->has(Func)) {
2066 APFloat V = Op1->getValueAPF();
2067 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2068 return ConstantFP::get(Ty->getContext(), V);
2069 }
Evandro Menezes6f136972019-09-06 16:49:49 +00002070 break;
2071 case LibFunc_atan2:
2072 case LibFunc_atan2f:
2073 case LibFunc_atan2_finite:
2074 case LibFunc_atan2f_finite:
2075 if (TLI->has(Func))
2076 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2077 break;
2078 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002079 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2080 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2081 return ConstantFP::get(Ty->getContext(),
2082 APFloat((float)std::pow((float)Op1V,
2083 (int)Op2C->getZExtValue())));
2084 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2085 return ConstantFP::get(Ty->getContext(),
2086 APFloat((float)std::pow((float)Op1V,
2087 (int)Op2C->getZExtValue())));
2088 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2089 return ConstantFP::get(Ty->getContext(),
2090 APFloat((double)std::pow((double)Op1V,
2091 (int)Op2C->getZExtValue())));
Chris Lattner9ca7c092009-10-05 05:00:35 +00002092 }
Craig Topper9f008862014-04-15 04:59:12 +00002093 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00002094 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00002095
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002096 if (Operands[0]->getType()->isIntegerTy() &&
2097 Operands[1]->getType()->isIntegerTy()) {
2098 const APInt *C0, *C1;
2099 if (!getConstIntOrUndef(Operands[0], C0) ||
2100 !getConstIntOrUndef(Operands[1], C1))
Craig Topper9f008862014-04-15 04:59:12 +00002101 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00002102
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002103 switch (IntrinsicID) {
2104 default: break;
Roman Lebedevff21e3f2019-09-01 11:56:52 +00002105 case Intrinsic::usub_with_overflow:
2106 case Intrinsic::ssub_with_overflow:
2107 case Intrinsic::uadd_with_overflow:
2108 case Intrinsic::sadd_with_overflow:
2109 // X - undef -> { undef, false }
2110 // undef - X -> { undef, false }
2111 // X + undef -> { undef, false }
2112 // undef + x -> { undef, false }
2113 if (!C0 || !C1) {
2114 return ConstantStruct::get(
2115 cast<StructType>(Ty),
2116 {UndefValue::get(Ty->getStructElementType(0)),
2117 Constant::getNullValue(Ty->getStructElementType(1))});
2118 }
2119 LLVM_FALLTHROUGH;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002120 case Intrinsic::smul_with_overflow:
Roman Lebedevff21e3f2019-09-01 11:56:52 +00002121 case Intrinsic::umul_with_overflow: {
2122 // undef * X -> { 0, false }
2123 // X * undef -> { 0, false }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002124 if (!C0 || !C1)
2125 return Constant::getNullValue(Ty);
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002126
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002127 APInt Res;
2128 bool Overflow;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002129 switch (IntrinsicID) {
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002130 default: llvm_unreachable("Invalid case");
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002131 case Intrinsic::sadd_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002132 Res = C0->sadd_ov(*C1, Overflow);
2133 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002134 case Intrinsic::uadd_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002135 Res = C0->uadd_ov(*C1, Overflow);
2136 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002137 case Intrinsic::ssub_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002138 Res = C0->ssub_ov(*C1, Overflow);
2139 break;
2140 case Intrinsic::usub_with_overflow:
2141 Res = C0->usub_ov(*C1, Overflow);
2142 break;
2143 case Intrinsic::smul_with_overflow:
2144 Res = C0->smul_ov(*C1, Overflow);
2145 break;
2146 case Intrinsic::umul_with_overflow:
2147 Res = C0->umul_ov(*C1, Overflow);
2148 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002149 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002150 Constant *Ops[] = {
2151 ConstantInt::get(Ty->getContext(), Res),
2152 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2153 };
2154 return ConstantStruct::get(cast<StructType>(Ty), Ops);
2155 }
2156 case Intrinsic::uadd_sat:
2157 case Intrinsic::sadd_sat:
2158 if (!C0 && !C1)
2159 return UndefValue::get(Ty);
2160 if (!C0 || !C1)
2161 return Constant::getAllOnesValue(Ty);
2162 if (IntrinsicID == Intrinsic::uadd_sat)
2163 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2164 else
2165 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2166 case Intrinsic::usub_sat:
2167 case Intrinsic::ssub_sat:
2168 if (!C0 && !C1)
2169 return UndefValue::get(Ty);
2170 if (!C0 || !C1)
2171 return Constant::getNullValue(Ty);
2172 if (IntrinsicID == Intrinsic::usub_sat)
2173 return ConstantInt::get(Ty, C0->usub_sat(*C1));
2174 else
2175 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2176 case Intrinsic::cttz:
2177 case Intrinsic::ctlz:
2178 assert(C1 && "Must be constant int");
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002179
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002180 // cttz(0, 1) and ctlz(0, 1) are undef.
2181 if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2182 return UndefValue::get(Ty);
2183 if (!C0)
2184 return Constant::getNullValue(Ty);
2185 if (IntrinsicID == Intrinsic::cttz)
2186 return ConstantInt::get(Ty, C0->countTrailingZeros());
2187 else
2188 return ConstantInt::get(Ty, C0->countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00002189 }
Craig Topper484b3422018-08-12 22:09:54 +00002190
Craig Topper9f008862014-04-15 04:59:12 +00002191 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002192 }
Matt Arsenault83778582014-03-05 00:02:00 +00002193
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002194 // Support ConstantVector in case we have an Undef in the top.
2195 if ((isa<ConstantVector>(Operands[0]) ||
2196 isa<ConstantDataVector>(Operands[0])) &&
2197 // Check for default rounding mode.
2198 // FIXME: Support other rounding modes?
2199 isa<ConstantInt>(Operands[1]) &&
2200 cast<ConstantInt>(Operands[1])->getValue() == 4) {
2201 auto *Op = cast<Constant>(Operands[0]);
2202 switch (IntrinsicID) {
2203 default: break;
2204 case Intrinsic::x86_avx512_vcvtss2si32:
2205 case Intrinsic::x86_avx512_vcvtss2si64:
2206 case Intrinsic::x86_avx512_vcvtsd2si32:
2207 case Intrinsic::x86_avx512_vcvtsd2si64:
2208 if (ConstantFP *FPOp =
2209 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2210 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2211 /*roundTowardZero=*/false, Ty,
2212 /*IsSigned*/true);
2213 break;
2214 case Intrinsic::x86_avx512_vcvtss2usi32:
2215 case Intrinsic::x86_avx512_vcvtss2usi64:
2216 case Intrinsic::x86_avx512_vcvtsd2usi32:
2217 case Intrinsic::x86_avx512_vcvtsd2usi64:
2218 if (ConstantFP *FPOp =
2219 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2220 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2221 /*roundTowardZero=*/false, Ty,
2222 /*IsSigned*/false);
2223 break;
2224 case Intrinsic::x86_avx512_cvttss2si:
2225 case Intrinsic::x86_avx512_cvttss2si64:
2226 case Intrinsic::x86_avx512_cvttsd2si:
2227 case Intrinsic::x86_avx512_cvttsd2si64:
2228 if (ConstantFP *FPOp =
2229 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2230 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2231 /*roundTowardZero=*/true, Ty,
2232 /*IsSigned*/true);
2233 break;
2234 case Intrinsic::x86_avx512_cvttss2usi:
2235 case Intrinsic::x86_avx512_cvttss2usi64:
2236 case Intrinsic::x86_avx512_cvttsd2usi:
2237 case Intrinsic::x86_avx512_cvttsd2usi64:
2238 if (ConstantFP *FPOp =
2239 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2240 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2241 /*roundTowardZero=*/true, Ty,
2242 /*IsSigned*/false);
2243 break;
2244 }
2245 }
2246 return nullptr;
2247}
2248
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002249static Constant *ConstantFoldScalarCall3(StringRef Name,
2250 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002251 Type *Ty,
2252 ArrayRef<Constant *> Operands,
2253 const TargetLibraryInfo *TLI,
2254 const CallBase *Call) {
2255 assert(Operands.size() == 3 && "Wrong number of operands.");
Matt Arsenault83778582014-03-05 00:02:00 +00002256
David Majnemer90a97042016-07-13 04:22:12 +00002257 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2258 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2259 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002260 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00002261 default: break;
2262 case Intrinsic::fma:
2263 case Intrinsic::fmuladd: {
2264 APFloat V = Op1->getValueAPF();
Sanjay Patel3f5a8082019-09-12 14:10:50 +00002265 V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(),
2266 APFloat::rmNearestTiesToEven);
2267 return ConstantFP::get(Ty->getContext(), V);
Matt Arsenault83778582014-03-05 00:02:00 +00002268 }
2269 }
2270 }
2271 }
2272 }
2273
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00002274 if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
2275 if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
2276 if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) {
2277 switch (IntrinsicID) {
2278 default: break;
2279 case Intrinsic::smul_fix:
2280 case Intrinsic::smul_fix_sat: {
2281 // This code performs rounding towards negative infinity in case the
2282 // result cannot be represented exactly for the given scale. Targets
2283 // that do care about rounding should use a target hook for specifying
2284 // how rounding should be done, and provide their own folding to be
2285 // consistent with rounding. This is the same approach as used by
2286 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2287 APInt Lhs = Op1->getValue();
2288 APInt Rhs = Op2->getValue();
2289 unsigned Scale = Op3->getValue().getZExtValue();
2290 unsigned Width = Lhs.getBitWidth();
2291 assert(Scale < Width && "Illegal scale.");
2292 unsigned ExtendedWidth = Width * 2;
2293 APInt Product = (Lhs.sextOrSelf(ExtendedWidth) *
2294 Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale);
2295 if (IntrinsicID == Intrinsic::smul_fix_sat) {
2296 APInt MaxValue =
2297 APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2298 APInt MinValue =
2299 APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2300 Product = APIntOps::smin(Product, MaxValue);
2301 Product = APIntOps::smax(Product, MinValue);
2302 }
2303 return ConstantInt::get(Ty->getContext(),
2304 Product.sextOrTrunc(Width));
2305 }
2306 }
2307 }
2308 }
2309 }
2310
Sanjay Patel411b8602018-08-17 13:23:44 +00002311 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002312 const APInt *C0, *C1, *C2;
2313 if (!getConstIntOrUndef(Operands[0], C0) ||
2314 !getConstIntOrUndef(Operands[1], C1) ||
2315 !getConstIntOrUndef(Operands[2], C2))
Sanjay Patel411b8602018-08-17 13:23:44 +00002316 return nullptr;
2317
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002318 bool IsRight = IntrinsicID == Intrinsic::fshr;
2319 if (!C2)
2320 return Operands[IsRight ? 1 : 0];
2321 if (!C0 && !C1)
2322 return UndefValue::get(Ty);
2323
Sanjay Patel411b8602018-08-17 13:23:44 +00002324 // The shift amount is interpreted as modulo the bitwidth. If the shift
2325 // amount is effectively 0, avoid UB due to oversized inverse shift below.
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002326 unsigned BitWidth = C2->getBitWidth();
2327 unsigned ShAmt = C2->urem(BitWidth);
Sanjay Patel411b8602018-08-17 13:23:44 +00002328 if (!ShAmt)
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002329 return Operands[IsRight ? 1 : 0];
Sanjay Patel411b8602018-08-17 13:23:44 +00002330
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002331 // (C0 << ShlAmt) | (C1 >> LshrAmt)
Sanjay Patel411b8602018-08-17 13:23:44 +00002332 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2333 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002334 if (!C0)
2335 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2336 if (!C1)
2337 return ConstantInt::get(Ty, C0->shl(ShlAmt));
2338 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
Sanjay Patel411b8602018-08-17 13:23:44 +00002339 }
2340
Craig Topper9f008862014-04-15 04:59:12 +00002341 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002342}
Benjamin Kramer061d1472014-03-05 19:41:48 +00002343
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002344static Constant *ConstantFoldScalarCall(StringRef Name,
2345 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002346 Type *Ty,
2347 ArrayRef<Constant *> Operands,
2348 const TargetLibraryInfo *TLI,
2349 const CallBase *Call) {
2350 if (Operands.size() == 1)
2351 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2352
2353 if (Operands.size() == 2)
2354 return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2355
2356 if (Operands.size() == 3)
2357 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2358
2359 return nullptr;
2360}
2361
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002362static Constant *ConstantFoldVectorCall(StringRef Name,
2363 Intrinsic::ID IntrinsicID,
Joerg Sonnenbergerb2e96162019-06-07 13:28:52 +00002364 VectorType *VTy,
2365 ArrayRef<Constant *> Operands,
2366 const DataLayout &DL,
2367 const TargetLibraryInfo *TLI,
2368 const CallBase *Call) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002369 SmallVector<Constant *, 4> Result(VTy->getNumElements());
2370 SmallVector<Constant *, 4> Lane(Operands.size());
2371 Type *Ty = VTy->getElementType();
2372
David Majnemer7f781ab2016-07-14 00:29:50 +00002373 if (IntrinsicID == Intrinsic::masked_load) {
2374 auto *SrcPtr = Operands[0];
2375 auto *Mask = Operands[2];
2376 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00002377
David Majnemer7f781ab2016-07-14 00:29:50 +00002378 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00002379
2380 SmallVector<Constant *, 32> NewElements;
2381 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00002382 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00002383 if (!MaskElt)
2384 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00002385 auto *PassthruElt = Passthru->getAggregateElement(I);
2386 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2387 if (isa<UndefValue>(MaskElt)) {
2388 if (PassthruElt)
2389 NewElements.push_back(PassthruElt);
2390 else if (VecElt)
2391 NewElements.push_back(VecElt);
2392 else
2393 return nullptr;
2394 }
2395 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002396 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002397 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002398 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002399 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002400 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002401 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002402 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002403 } else {
2404 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002405 }
2406 }
David Majnemer17a95aa2016-07-14 06:58:37 +00002407 if (NewElements.size() != VTy->getNumElements())
2408 return nullptr;
2409 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00002410 }
2411
Benjamin Kramer061d1472014-03-05 19:41:48 +00002412 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2413 // Gather a column of constants.
2414 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002415 // Some intrinsics use a scalar type for certain arguments.
2416 if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00002417 Lane[J] = Operands[J];
2418 continue;
2419 }
Craig Topper7c553ed2017-06-03 18:50:29 +00002420
Benjamin Kramer061d1472014-03-05 19:41:48 +00002421 Constant *Agg = Operands[J]->getAggregateElement(I);
2422 if (!Agg)
2423 return nullptr;
2424
2425 Lane[J] = Agg;
2426 }
2427
2428 // Use the regular scalar folding to simplify this column.
Chandler Carruth751d95f2019-02-11 07:51:44 +00002429 Constant *Folded =
2430 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002431 if (!Folded)
2432 return nullptr;
2433 Result[I] = Folded;
2434 }
2435
2436 return ConstantVector::get(Result);
2437}
2438
Eugene Zelenko35623fb2016-03-28 17:40:08 +00002439} // end anonymous namespace
2440
Chandler Carruth751d95f2019-02-11 07:51:44 +00002441Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
2442 ArrayRef<Constant *> Operands,
2443 const TargetLibraryInfo *TLI) {
2444 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002445 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002446 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00002447 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002448 StringRef Name = F->getName();
2449
2450 Type *Ty = F->getReturnType();
2451
David Majnemer90a97042016-07-13 04:22:12 +00002452 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00002453 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
Chandler Carruth751d95f2019-02-11 07:51:44 +00002454 F->getParent()->getDataLayout(), TLI, Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002455
Chandler Carruth751d95f2019-02-11 07:51:44 +00002456 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
2457 Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002458}
Eli Friedmanb6befc32016-11-02 20:48:11 +00002459
Chandler Carruth751d95f2019-02-11 07:51:44 +00002460bool llvm::isMathLibCallNoop(const CallBase *Call,
2461 const TargetLibraryInfo *TLI) {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002462 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2463 // (and to some extent ConstantFoldScalarCall).
Chandler Carruth751d95f2019-02-11 07:51:44 +00002464 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002465 return false;
Chandler Carruth751d95f2019-02-11 07:51:44 +00002466 Function *F = Call->getCalledFunction();
Eli Friedmanb6befc32016-11-02 20:48:11 +00002467 if (!F)
2468 return false;
2469
David L. Jonesd21529f2017-01-23 23:16:46 +00002470 LibFunc Func;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002471 if (!TLI || !TLI->getLibFunc(*F, Func))
2472 return false;
2473
Chandler Carruth751d95f2019-02-11 07:51:44 +00002474 if (Call->getNumArgOperands() == 1) {
2475 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002476 const APFloat &Op = OpC->getValueAPF();
2477 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002478 case LibFunc_logl:
2479 case LibFunc_log:
2480 case LibFunc_logf:
2481 case LibFunc_log2l:
2482 case LibFunc_log2:
2483 case LibFunc_log2f:
2484 case LibFunc_log10l:
2485 case LibFunc_log10:
2486 case LibFunc_log10f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002487 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2488
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_expl:
2490 case LibFunc_exp:
2491 case LibFunc_expf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002492 // FIXME: These boundaries are slightly conservative.
2493 if (OpC->getType()->isDoubleTy())
2494 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2495 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2496 if (OpC->getType()->isFloatTy())
2497 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2498 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2499 break;
2500
David L. Jonesd21529f2017-01-23 23:16:46 +00002501 case LibFunc_exp2l:
2502 case LibFunc_exp2:
2503 case LibFunc_exp2f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002504 // FIXME: These boundaries are slightly conservative.
2505 if (OpC->getType()->isDoubleTy())
2506 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2507 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2508 if (OpC->getType()->isFloatTy())
2509 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2510 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2511 break;
2512
David L. Jonesd21529f2017-01-23 23:16:46 +00002513 case LibFunc_sinl:
2514 case LibFunc_sin:
2515 case LibFunc_sinf:
2516 case LibFunc_cosl:
2517 case LibFunc_cos:
2518 case LibFunc_cosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002519 return !Op.isInfinity();
2520
David L. Jonesd21529f2017-01-23 23:16:46 +00002521 case LibFunc_tanl:
2522 case LibFunc_tan:
2523 case LibFunc_tanf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002524 // FIXME: Stop using the host math library.
2525 // FIXME: The computation isn't done in the right precision.
2526 Type *Ty = OpC->getType();
2527 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2528 double OpV = getValueAsDouble(OpC);
2529 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2530 }
2531 break;
2532 }
2533
David L. Jonesd21529f2017-01-23 23:16:46 +00002534 case LibFunc_asinl:
2535 case LibFunc_asin:
2536 case LibFunc_asinf:
2537 case LibFunc_acosl:
2538 case LibFunc_acos:
2539 case LibFunc_acosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002540 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2541 APFloat::cmpLessThan &&
2542 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2543 APFloat::cmpGreaterThan;
2544
David L. Jonesd21529f2017-01-23 23:16:46 +00002545 case LibFunc_sinh:
2546 case LibFunc_cosh:
2547 case LibFunc_sinhf:
2548 case LibFunc_coshf:
2549 case LibFunc_sinhl:
2550 case LibFunc_coshl:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002551 // FIXME: These boundaries are slightly conservative.
2552 if (OpC->getType()->isDoubleTy())
2553 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2554 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2555 if (OpC->getType()->isFloatTy())
2556 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2557 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2558 break;
2559
David L. Jonesd21529f2017-01-23 23:16:46 +00002560 case LibFunc_sqrtl:
2561 case LibFunc_sqrt:
2562 case LibFunc_sqrtf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002563 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2564
2565 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2566 // maybe others?
2567 default:
2568 break;
2569 }
2570 }
2571 }
2572
Chandler Carruth751d95f2019-02-11 07:51:44 +00002573 if (Call->getNumArgOperands() == 2) {
2574 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
2575 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
Eli Friedmanb6befc32016-11-02 20:48:11 +00002576 if (Op0C && Op1C) {
2577 const APFloat &Op0 = Op0C->getValueAPF();
2578 const APFloat &Op1 = Op1C->getValueAPF();
2579
2580 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002581 case LibFunc_powl:
2582 case LibFunc_pow:
2583 case LibFunc_powf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002584 // FIXME: Stop using the host math library.
2585 // FIXME: The computation isn't done in the right precision.
2586 Type *Ty = Op0C->getType();
2587 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2588 if (Ty == Op1C->getType()) {
2589 double Op0V = getValueAsDouble(Op0C);
2590 double Op1V = getValueAsDouble(Op1C);
2591 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2592 }
2593 }
2594 break;
2595 }
2596
David L. Jonesd21529f2017-01-23 23:16:46 +00002597 case LibFunc_fmodl:
2598 case LibFunc_fmod:
2599 case LibFunc_fmodf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002600 return Op0.isNaN() || Op1.isNaN() ||
2601 (!Op0.isInfinity() && !Op1.isZero());
2602
2603 default:
2604 break;
2605 }
2606 }
2607 }
2608
2609 return false;
2610}