blob: 8dbcf7034fdaff470b0b7ac535b0e8c7c6b4e04c [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) {
Keno Fischercea88822019-09-26 02:07:51 +000096 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
97 "Invalid constantexpr bitcast!");
98
Nadav Rotem365af6f2011-08-24 20:18:38 +000099 // Catch the obvious splat cases.
100 if (C->isNullValue() && !DestTy->isX86_MMXTy())
101 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000102 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
103 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +0000104 return Constant::getAllOnesValue(DestTy);
105
Matt Arsenault624e1b32016-12-07 20:56:11 +0000106 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
107 // Handle a vector->scalar integer/fp cast.
108 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
109 unsigned NumSrcElts = VTy->getNumElements();
110 Type *SrcEltTy = VTy->getElementType();
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000111
Matt Arsenault624e1b32016-12-07 20:56:11 +0000112 // If the vector is a vector of floating point, convert it to vector of int
113 // to simplify things.
114 if (SrcEltTy->isFloatingPointTy()) {
115 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
116 Type *SrcIVTy =
117 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
118 // Ask IR to do the conversion now that #elts line up.
119 C = ConstantExpr::getBitCast(C, SrcIVTy);
120 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000121
Matt Arsenault624e1b32016-12-07 20:56:11 +0000122 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
123 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
124 SrcEltTy, NumSrcElts, DL))
125 return CE;
126
127 if (isa<IntegerType>(DestTy))
128 return ConstantInt::get(DestTy, Result);
129
130 APFloat FP(DestTy->getFltSemantics(), Result);
131 return ConstantFP::get(DestTy->getContext(), FP);
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000132 }
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000133 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000134
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000135 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000136 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000137 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000138 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000139
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000140 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
141 // vector so the code below can handle it uniformly.
142 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
143 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000144 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000145 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000146
Chris Lattner9d051242009-10-25 06:08:26 +0000147 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000148 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000149 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000150
Chandler Carruthef860a22013-01-02 09:10:48 +0000151 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000152 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000153 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000154 if (NumDstElt == NumSrcElt)
155 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000156
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000157 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000158 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000159
160 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000161 // requires endianness information to do the right thing. For example,
162 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
163 // folds to (little endian):
164 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
165 // and to (big endian):
166 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000167
Chris Lattner9d051242009-10-25 06:08:26 +0000168 // First thing is first. We only want to think about integer here, so if
169 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000170 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000171 // Fold to an vector of integers with same size as our FP type.
172 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000173 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000174 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
175 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000176 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000177
Chandler Carruthef860a22013-01-02 09:10:48 +0000178 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000179 return ConstantExpr::getBitCast(C, DestTy);
180 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000181
Chris Lattner9d051242009-10-25 06:08:26 +0000182 // Okay, we know the destination is integer, if the input is FP, convert
183 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000184 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000185 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000186 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000187 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000188 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000189 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000190 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000191 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
192 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000193 return C;
194 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000195
Chris Lattner9d051242009-10-25 06:08:26 +0000196 // Now we know that the input and output vectors are both integer vectors
197 // of the same size, and that their #elements is not the same. Do the
198 // conversion here, which depends on whether the input or output has
199 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000200 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000201
Chris Lattner9d051242009-10-25 06:08:26 +0000202 SmallVector<Constant*, 32> Result;
203 if (NumDstElt < NumSrcElt) {
204 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
205 Constant *Zero = Constant::getNullValue(DstEltTy);
206 unsigned Ratio = NumSrcElt/NumDstElt;
207 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
208 unsigned SrcElt = 0;
209 for (unsigned i = 0; i != NumDstElt; ++i) {
210 // Build each element of the result.
211 Constant *Elt = Zero;
212 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
213 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000214 Constant *Src = C->getAggregateElement(SrcElt++);
215 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000216 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000217 else
218 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000219 if (!Src) // Reject constantexpr elements.
220 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000221
Chris Lattner9d051242009-10-25 06:08:26 +0000222 // Zero extend the element to the right size.
223 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000224
Chris Lattner9d051242009-10-25 06:08:26 +0000225 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000226 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000227 ConstantInt::get(Src->getType(), ShiftAmt));
228 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000229
Chris Lattner9d051242009-10-25 06:08:26 +0000230 // Mix it in.
231 Elt = ConstantExpr::getOr(Elt, Src);
232 }
233 Result.push_back(Elt);
234 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000235 return ConstantVector::get(Result);
236 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000237
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000238 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
239 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000240 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000241
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000242 // Loop over each source value, expanding into multiple results.
243 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagio7277afe2016-09-13 14:50:47 +0000244 auto *Element = C->getAggregateElement(i);
245
246 if (!Element) // Reject constantexpr elements.
247 return ConstantExpr::getBitCast(C, DestTy);
248
249 if (isa<UndefValue>(Element)) {
250 // Correctly Propagate undef values.
251 Result.append(Ratio, UndefValue::get(DstEltTy));
252 continue;
253 }
254
255 auto *Src = dyn_cast<ConstantInt>(Element);
256 if (!Src)
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000257 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000258
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000259 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
260 for (unsigned j = 0; j != Ratio; ++j) {
261 // Shift the piece of the value into the right place, depending on
262 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000264 ConstantInt::get(Src->getType(), ShiftAmt));
265 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000266
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000267 // Truncate the element to an integer with the same pointer size and
268 // convert the element back to a pointer using a inttoptr.
269 if (DstEltTy->isPointerTy()) {
270 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
271 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
272 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
273 continue;
274 }
275
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000276 // Truncate and remember this piece.
277 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000278 }
279 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000280
Chris Lattner69229312011-02-15 00:14:00 +0000281 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000282}
283
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000284} // end anonymous namespace
285
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000286/// If this constant is a constant offset from a global, return the global and
287/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000288bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
289 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000290 // Trivial case, constant is the global.
291 if ((GV = dyn_cast<GlobalValue>(C))) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000292 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000293 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000294 return true;
295 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000296
Chris Lattner44d68b92007-01-31 00:51:48 +0000297 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000298 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000299 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000300
Chris Lattner44d68b92007-01-31 00:51:48 +0000301 // Look through ptr->int and ptr->ptr casts.
302 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000303 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000305
306 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000307 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000308 if (!GEP)
309 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000310
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000311 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000312 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000313
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000314 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000316 return false;
317
318 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000320 return false;
321
322 Offset = TmpOffset;
323 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000324}
325
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000326Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
327 const DataLayout &DL) {
328 do {
329 Type *SrcTy = C->getType();
330
331 // If the type sizes are the same and a cast is legal, just directly
332 // cast the constant.
333 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
334 Instruction::CastOps Cast = Instruction::BitCast;
335 // If we are going from a pointer to int or vice versa, we spell the cast
336 // differently.
337 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
338 Cast = Instruction::IntToPtr;
339 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
340 Cast = Instruction::PtrToInt;
341
342 if (CastInst::castIsValid(Cast, C, DestTy))
343 return ConstantExpr::getCast(Cast, C, DestTy);
344 }
345
346 // If this isn't an aggregate type, there is nothing we can do to drill down
347 // and find a bitcastable constant.
348 if (!SrcTy->isAggregateType())
349 return nullptr;
350
351 // We're simulating a load through a pointer that was bitcast to point to
352 // a different type, so we can try to walk down through the initial
Nikita Popov79c994d2018-12-11 20:29:16 +0000353 // elements of an aggregate to see if some part of the aggregate is
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000354 // castable to implement the "load" semantic model.
Nikita Popov79c994d2018-12-11 20:29:16 +0000355 if (SrcTy->isStructTy()) {
356 // Struct types might have leading zero-length elements like [0 x i32],
357 // which are certainly not what we are looking for, so skip them.
358 unsigned Elem = 0;
359 Constant *ElemC;
360 do {
361 ElemC = C->getAggregateElement(Elem++);
362 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()) == 0);
363 C = ElemC;
364 } else {
365 C = C->getAggregateElement(0u);
366 }
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000367 } while (C);
368
369 return nullptr;
370}
371
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000372namespace {
373
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000374/// Recursive helper to read bits out of global. C is the constant being copied
375/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
376/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000377/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000378bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
379 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000381 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000382
Chris Lattner3db7bd22009-10-24 05:27:19 +0000383 // If this element is zero or undefined, we can just return since *CurPtr is
384 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000385 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
386 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000387
David Majnemer90a97042016-07-13 04:22:12 +0000388 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000389 if (CI->getBitWidth() > 64 ||
390 (CI->getBitWidth() & 7) != 0)
391 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000392
Chris Lattnered00b802009-10-23 06:23:49 +0000393 uint64_t Val = CI->getZExtValue();
394 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000395
Chris Lattnered00b802009-10-23 06:23:49 +0000396 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000397 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000398 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000399 n = IntBytes - n - 1;
400 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000401 ++ByteOffset;
402 }
403 return true;
404 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000405
David Majnemer90a97042016-07-13 04:22:12 +0000406 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000407 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
409 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000410 }
411 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000412 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
413 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000414 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000415 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
417 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000418 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000419 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000420 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000421
David Majnemer90a97042016-07-13 04:22:12 +0000422 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000424 unsigned Index = SL->getElementContainingOffset(ByteOffset);
425 uint64_t CurEltOffset = SL->getElementOffset(Index);
426 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000427
Eugene Zelenko1804a772016-08-25 00:45:04 +0000428 while (true) {
Chris Lattnered00b802009-10-23 06:23:49 +0000429 // If the element access is to the element itself and not to tail padding,
430 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000431 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000432
433 if (ByteOffset < EltSize &&
434 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000435 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000436 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000437
Chris Lattnered00b802009-10-23 06:23:49 +0000438 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000439
Chris Lattnered00b802009-10-23 06:23:49 +0000440 // Check to see if we read from the last struct element, if so we're done.
441 if (Index == CS->getType()->getNumElements())
442 return true;
443
444 // If we read all of the bytes we needed from this element we're done.
445 uint64_t NextEltOffset = SL->getElementOffset(Index);
446
Matt Arsenault8c789092013-08-12 23:15:58 +0000447 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000448 return true;
449
450 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000451 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
452 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000453 ByteOffset = 0;
454 CurEltOffset = NextEltOffset;
455 }
456 // not reached.
457 }
458
Chris Lattner67058832012-01-25 06:48:06 +0000459 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
460 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000461 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000462 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000463 uint64_t Index = ByteOffset / EltSize;
464 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000465 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000466 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000467 NumElts = AT->getNumElements();
468 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000469 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000470
Chris Lattner67058832012-01-25 06:48:06 +0000471 for (; Index != NumElts; ++Index) {
472 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000473 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000474 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000475
476 uint64_t BytesWritten = EltSize - Offset;
477 assert(BytesWritten <= EltSize && "Not indexing into this element?");
478 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000479 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000480
Chris Lattner67058832012-01-25 06:48:06 +0000481 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000482 BytesLeft -= BytesWritten;
483 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000484 }
485 return true;
486 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000487
David Majnemer90a97042016-07-13 04:22:12 +0000488 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000489 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000491 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000492 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000493 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000494 }
495
Chris Lattnered00b802009-10-23 06:23:49 +0000496 // Otherwise, unknown initializer type.
497 return false;
498}
499
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000500Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
501 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000502 auto *PTy = cast<PointerType>(C->getType());
503 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000504
Chris Lattnered00b802009-10-23 06:23:49 +0000505 // If this isn't an integer load we can't fold it directly.
506 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000507 unsigned AS = PTy->getAddressSpace();
508
Chris Lattnered00b802009-10-23 06:23:49 +0000509 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000510 // and then bitcast the result. This can be useful for union cases. Note
511 // that address spaces don't matter here since we're not going to result in
512 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000513 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000514 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000515 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000516 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000517 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000518 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000519 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000520 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000521 MapTy = PointerType::getIntNTy(C->getContext(),
Jay Foad45d19fb2019-06-19 10:28:48 +0000522 DL.getTypeSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000523 } else
Craig Topper9f008862014-04-15 04:59:12 +0000524 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000525
Eduard Burtescu14239212016-01-22 01:17:26 +0000526 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
Keno Fischercea88822019-09-26 02:07:51 +0000527 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) {
528 if (Res->isNullValue() && !LoadTy->isX86_MMXTy())
529 // Materializing a zero can be done trivially without a bitcast
530 return Constant::getNullValue(LoadTy);
531 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
532 Res = FoldBitCast(Res, CastTy, DL);
533 if (LoadTy->isPtrOrPtrVectorTy()) {
534 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
535 if (Res->isNullValue() && !LoadTy->isX86_MMXTy())
536 return Constant::getNullValue(LoadTy);
537 if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
538 // Be careful not to replace a load of an addrspace value with an inttoptr here
539 return nullptr;
540 Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy);
541 }
542 return Res;
543 }
Craig Topper9f008862014-04-15 04:59:12 +0000544 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000545 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000546
Chris Lattnered00b802009-10-23 06:23:49 +0000547 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000548 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000549 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000550
Chris Lattnered00b802009-10-23 06:23:49 +0000551 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000552 APInt OffsetAI;
553 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000554 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000555
David Majnemer90a97042016-07-13 04:22:12 +0000556 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000557 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000558 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000559 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000560
David Majnemerf89660a2016-07-13 23:33:07 +0000561 int64_t Offset = OffsetAI.getSExtValue();
562 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000563
Chris Lattnered00b802009-10-23 06:23:49 +0000564 // If we're not accessing anything in this constant, the result is undefined.
Alina Sbirlea7153f272019-07-31 18:22:22 +0000565 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
David Majnemerf89660a2016-07-13 23:33:07 +0000566 return UndefValue::get(IntType);
567
568 // If we're not accessing anything in this constant, the result is undefined.
569 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000570 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000571
Chris Lattner59f94c02009-10-23 06:50:36 +0000572 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000573 unsigned char *CurPtr = RawBytes;
574 unsigned BytesLeft = BytesLoaded;
575
576 // If we're loading off the beginning of the global, some bytes may be valid.
577 if (Offset < 0) {
578 CurPtr += -Offset;
579 BytesLeft += Offset;
580 Offset = 0;
581 }
582
583 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000584 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000585
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000586 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000588 ResultVal = RawBytes[BytesLoaded - 1];
589 for (unsigned i = 1; i != BytesLoaded; ++i) {
590 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000591 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000592 }
593 } else {
594 ResultVal = RawBytes[0];
595 for (unsigned i = 1; i != BytesLoaded; ++i) {
596 ResultVal <<= 8;
597 ResultVal |= RawBytes[i];
598 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000599 }
Chris Lattnered00b802009-10-23 06:23:49 +0000600
Chris Lattner59f94c02009-10-23 06:50:36 +0000601 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000602}
603
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000604Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
605 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000606 auto *SrcPtr = CE->getOperand(0);
607 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
608 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000609 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000610 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000611
Eduard Burtescu14239212016-01-22 01:17:26 +0000612 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000613 if (!C)
614 return nullptr;
615
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000616 return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000617}
618
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000619} // end anonymous namespace
620
Eduard Burtescu14239212016-01-22 01:17:26 +0000621Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000623 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000624 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000625 if (GV->isConstant() && GV->hasDefinitiveInitializer())
626 return GV->getInitializer();
627
David Majnemered9abe12015-07-22 22:29:30 +0000628 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000629 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000630 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000631
Chris Lattnercf7e8942009-10-22 06:44:07 +0000632 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000633 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000634 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000635 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000636
Chris Lattnercf7e8942009-10-22 06:44:07 +0000637 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000638 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000639 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000640 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000641 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
642 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000643 }
644 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000645 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000646
Chandler Carrutha0e56952014-05-15 09:56:28 +0000647 if (CE->getOpcode() == Instruction::BitCast)
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000648 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000649 return LoadedC;
650
Chris Lattnercf7e8942009-10-22 06:44:07 +0000651 // Instead of loading constant c string, use corresponding integer value
652 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000653 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000655 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000656 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000657 // Replace load with immediate integer if the result is an integer or fp
658 // value.
659 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000660 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000661 APInt StrVal(NumBits, 0);
662 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000664 for (unsigned char C : reverse(Str.bytes())) {
665 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000666 StrVal = (StrVal << 8) | SingleChar;
667 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000668 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000669 for (unsigned char C : Str.bytes()) {
670 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000671 StrVal = (StrVal << 8) | SingleChar;
672 }
673 // Append NULL at the end.
674 SingleChar = 0;
675 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000676 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000677
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000678 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
679 if (Ty->isFloatingPointTy())
680 Res = ConstantExpr::getBitCast(Res, Ty);
681 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000682 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000683 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000684
Chris Lattnercf7e8942009-10-22 06:44:07 +0000685 // If this load comes from anywhere in a constant global, and if the global
686 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000687 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000688 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000689 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000690 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000691 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000692 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000693 }
694 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000695
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000696 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000697 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000698}
699
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000700namespace {
701
702Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000703 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000704
David Majnemer90a97042016-07-13 04:22:12 +0000705 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000706 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000707
Craig Topper9f008862014-04-15 04:59:12 +0000708 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000709}
Chris Lattner44d68b92007-01-31 00:51:48 +0000710
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000711/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000712/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000713/// these together. If target data info is available, it is provided as DL,
714/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000715Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
716 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000717 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000718
Chris Lattner44d68b92007-01-31 00:51:48 +0000719 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
720 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
721 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000722
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 if (Opc == Instruction::And) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000724 KnownBits Known0 = computeKnownBits(Op0, DL);
725 KnownBits Known1 = computeKnownBits(Op1, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000726 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000727 // All the bits of Op0 that the 'and' could be masking are already zero.
728 return Op0;
729 }
Craig Topperb45eabc2017-04-26 16:39:58 +0000730 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000731 // All the bits of Op1 that the 'and' could be masking are already zero.
732 return Op1;
733 }
734
Craig Topper8189a872017-05-03 23:12:29 +0000735 Known0.Zero |= Known1.Zero;
736 Known0.One &= Known1.One;
737 if (Known0.isConstant())
738 return ConstantInt::get(Op0->getType(), Known0.getConstant());
Nick Lewycky06417742013-02-14 03:23:37 +0000739 }
740
Chris Lattner44d68b92007-01-31 00:51:48 +0000741 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
742 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000743 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000744 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000745 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000746
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000747 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
748 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
749 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000750
Chris Lattner44d68b92007-01-31 00:51:48 +0000751 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000752 // PtrToInt may change the bitwidth so we have convert to the right size
753 // first.
754 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
755 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000756 }
757 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000758
Craig Topper9f008862014-04-15 04:59:12 +0000759 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000760}
761
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000762/// If array indices are not pointer-sized integers, explicitly cast them so
763/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000764Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourned93620b2016-11-10 22:34:55 +0000765 Type *ResultTy, Optional<unsigned> InRangeIndex,
766 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000767 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischerdc091192016-12-08 17:22:35 +0000768 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000769
770 bool Any = false;
771 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000772 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000773 if ((i == 1 ||
Keno Fischerdc091192016-12-08 17:22:35 +0000774 !isa<StructType>(GetElementPtrInst::getIndexedType(
775 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kupersteindd92c782016-12-21 17:34:21 +0000776 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000777 Any = true;
Michael Kupersteindd92c782016-12-21 17:34:21 +0000778 Type *NewType = Ops[i]->getType()->isVectorTy()
779 ? IntPtrTy
780 : IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000781 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
782 true,
Michael Kupersteindd92c782016-12-21 17:34:21 +0000783 NewType,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000784 true),
Michael Kupersteindd92c782016-12-21 17:34:21 +0000785 Ops[i], NewType));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000786 } else
787 NewIdxs.push_back(Ops[i]);
788 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000789
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000790 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000791 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000792
Peter Collingbourned93620b2016-11-10 22:34:55 +0000793 Constant *C = ConstantExpr::getGetElementPtr(
794 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemerd536f232016-07-29 03:27:26 +0000795 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
796 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000797
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000798 return C;
799}
800
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000801/// Strip the pointer casts, but preserve the address space information.
Peter Collingbourne2452d702019-08-22 19:56:14 +0000802Constant *StripPtrCastKeepAS(Constant *Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000803 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000804 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Peter Collingbourne2452d702019-08-22 19:56:14 +0000805 Ptr = cast<Constant>(Ptr->stripPointerCasts());
David Majnemer90a97042016-07-13 04:22:12 +0000806 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000807
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000808 ElemTy = NewPtrTy->getPointerElementType();
809
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000810 // Preserve the address space number of the pointer.
811 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000812 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000813 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000814 }
815 return Ptr;
816}
817
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000818/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000819Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
820 ArrayRef<Constant *> Ops,
821 const DataLayout &DL,
822 const TargetLibraryInfo *TLI) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000823 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000824 bool InBounds = GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000825
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000826 Type *SrcElemTy = GEP->getSourceElementType();
827 Type *ResElemTy = GEP->getResultElementType();
828 Type *ResTy = GEP->getType();
829 if (!SrcElemTy->isSized())
830 return nullptr;
831
Peter Collingbourned93620b2016-11-10 22:34:55 +0000832 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
833 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000834 return C;
835
Chris Lattner44d68b92007-01-31 00:51:48 +0000836 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000837 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000838 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000839
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000840 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000841
842 // If this is a constant expr gep that is effectively computing an
843 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000844 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000845 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000846
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000847 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
848 // "inttoptr (sub (ptrtoint Ptr), V)"
849 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
850 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
851 assert((!CE || CE->getType() == IntPtrTy) &&
852 "CastGEPIndices didn't canonicalize index types!");
853 if (CE && CE->getOpcode() == Instruction::Sub &&
854 CE->getOperand(0)->isNullValue()) {
855 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
856 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
857 Res = ConstantExpr::getIntToPtr(Res, ResTy);
858 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
859 Res = FoldedRes;
860 return Res;
861 }
Chris Lattner5858e092011-01-06 06:19:46 +0000862 }
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000863 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000864 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000865
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000866 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000867 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000868 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000869 DL.getIndexedOffsetInType(
870 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000871 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000872 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000873
874 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000875 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000876 InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000877 InBounds &= GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000878
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000879 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000880
881 // Do not try the incorporate the sub-GEP if some index is not a number.
882 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000883 for (Value *NestedOp : NestedOps)
884 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000885 AllConstantInt = false;
886 break;
887 }
888 if (!AllConstantInt)
889 break;
890
Dan Gohman474e488c2010-03-10 19:31:51 +0000891 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000892 SrcElemTy = GEP->getSourceElementType();
893 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000894 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000895 }
896
Dan Gohman81ce8422009-08-19 18:18:36 +0000897 // If the base value for this address is a literal integer value, fold the
898 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000899 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000900 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000901 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000902 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000903 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000904 }
905 }
906
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000907 auto *PTy = cast<PointerType>(Ptr->getType());
908 if ((Ptr->isNullValue() || BasePtr != 0) &&
909 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000910 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000911 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000912 }
913
914 // Otherwise form a regular getelementptr. Recompute the indices so that
915 // we eliminate over-indexing of the notional static type array bounds.
916 // This makes it easy to determine if the getelementptr is "inbounds".
917 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000918 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000919 SmallVector<Constant *, 32> NewIdxs;
920
Dan Gohmanc59ba422009-08-19 22:46:59 +0000921 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000922 if (!Ty->isStructTy()) {
923 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000924 // The only pointer indexing we'll do is on the first index of the GEP.
925 if (!NewIdxs.empty())
926 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000927
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000928 Ty = SrcElemTy;
929
Chris Lattner77c36d62009-12-03 01:05:45 +0000930 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000931 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000932 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000933 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
934 Ty = ATy->getElementType();
935 } else {
936 // We've reached some non-indexable type.
937 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000938 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000939
Dan Gohman81ce8422009-08-19 18:18:36 +0000940 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000941 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000942 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000943 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000944 // index for this level and proceed to the next level to see if it can
945 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000946 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000947 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000948 // The element size is non-zero divide the offset by the element
949 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000950 bool Overflow;
951 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
952 if (Overflow)
953 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000954 Offset -= NewIdx * ElemSize;
955 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
956 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000957 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000958 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000959 // If we end up with an offset that isn't valid for this struct type, we
960 // can't re-form this GEP in a regular form, so bail out. The pointer
961 // operand likely went through casts that are necessary to make the GEP
962 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000964 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000965 break;
966
967 // Determine which field of the struct the offset points into. The
968 // getZExtValue is fine as we've already ensured that the offset is
969 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000970 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000971 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
972 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000973 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000974 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000975 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000976 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000977
978 // If we haven't used up the entire offset by descending the static
979 // type, then the offset is pointing into the middle of an indivisible
980 // member, so we can't simplify it.
981 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000982 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000983
Peter Collingbourned93620b2016-11-10 22:34:55 +0000984 // Preserve the inrange index from the innermost GEP if possible. We must
985 // have calculated the same indices up to and including the inrange index.
986 Optional<unsigned> InRangeIndex;
987 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
988 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
989 NewIdxs.size() > *LastIRIndex) {
990 InRangeIndex = LastIRIndex;
991 for (unsigned I = 0; I <= *LastIRIndex; ++I)
Peter Collingbournec7d28192018-09-11 01:53:36 +0000992 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
993 return nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +0000994 }
995
Dan Gohman21c62162009-09-11 00:04:14 +0000996 // Create a GEP.
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000997 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
998 InBounds, InRangeIndex);
Matt Arsenault8c789092013-08-12 23:15:58 +0000999 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +00001000 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +00001001
Dan Gohmanc59ba422009-08-19 22:46:59 +00001002 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00001003 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001004 if (Ty != ResElemTy)
1005 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +00001006
1007 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +00001008}
1009
Manuel Jacobe9024592016-01-21 06:33:22 +00001010/// Attempt to constant fold an instruction with the
1011/// specified opcode and operands. If successful, the constant result is
1012/// returned, if not, null is returned. Note that this function can fail when
1013/// attempting to fold instructions like loads and stores, which have no
1014/// constant expression form.
David Majnemera926b3e2016-07-29 03:27:33 +00001015Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001016 ArrayRef<Constant *> Ops,
1017 const DataLayout &DL,
1018 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001019 Type *DestTy = InstOrCE->getType();
1020
Cameron McInally1d0c8452019-05-05 16:07:09 +00001021 if (Instruction::isUnaryOp(Opcode))
1022 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1023
Manuel Jacobe9024592016-01-21 06:33:22 +00001024 if (Instruction::isBinaryOp(Opcode))
1025 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1026
1027 if (Instruction::isCast(Opcode))
1028 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1029
David Majnemer17bdf442016-07-13 03:42:38 +00001030 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001031 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1032 return C;
1033
Peter Collingbourned93620b2016-11-10 22:34:55 +00001034 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1035 Ops.slice(1), GEP->isInBounds(),
1036 GEP->getInRangeIndex());
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001037 }
1038
David Majnemer57b94c82016-07-29 03:27:31 +00001039 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1040 return CE->getWithOperands(Ops);
1041
Manuel Jacobe9024592016-01-21 06:33:22 +00001042 switch (Opcode) {
1043 default: return nullptr;
1044 case Instruction::ICmp:
1045 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1046 case Instruction::Call:
Andrew Kaylor647025f2017-06-09 23:18:11 +00001047 if (auto *F = dyn_cast<Function>(Ops.back())) {
Chandler Carruth751d95f2019-02-11 07:51:44 +00001048 const auto *Call = cast<CallBase>(InstOrCE);
1049 if (canConstantFoldCallTo(Call, F))
1050 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
Andrew Kaylor647025f2017-06-09 23:18:11 +00001051 }
Manuel Jacobe9024592016-01-21 06:33:22 +00001052 return nullptr;
1053 case Instruction::Select:
1054 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1055 case Instruction::ExtractElement:
1056 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chen Zheng627095e2019-07-11 02:18:22 +00001057 case Instruction::ExtractValue:
1058 return ConstantExpr::getExtractValue(
Simon Pilgrim514e6b62019-09-26 16:30:36 +00001059 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
Manuel Jacobe9024592016-01-21 06:33:22 +00001060 case Instruction::InsertElement:
1061 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1062 case Instruction::ShuffleVector:
1063 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +00001064 }
1065}
1066
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001067} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +00001068
1069//===----------------------------------------------------------------------===//
1070// Constant Folding public APIs
1071//===----------------------------------------------------------------------===//
1072
David Majnemerd536f232016-07-29 03:27:26 +00001073namespace {
1074
1075Constant *
1076ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1077 const TargetLibraryInfo *TLI,
1078 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1079 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1080 return nullptr;
1081
1082 SmallVector<Constant *, 8> Ops;
1083 for (const Use &NewU : C->operands()) {
1084 auto *NewC = cast<Constant>(&NewU);
1085 // Recursively fold the ConstantExpr's operands. If we have already folded
1086 // a ConstantExpr, we don't have to process it again.
1087 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1088 auto It = FoldedOps.find(NewC);
1089 if (It == FoldedOps.end()) {
1090 if (auto *FoldedC =
1091 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
David Majnemerd536f232016-07-29 03:27:26 +00001092 FoldedOps.insert({NewC, FoldedC});
David Greenda211702017-03-21 10:17:39 +00001093 NewC = FoldedC;
David Majnemerd536f232016-07-29 03:27:26 +00001094 } else {
1095 FoldedOps.insert({NewC, NewC});
1096 }
1097 } else {
1098 NewC = It->second;
1099 }
1100 }
1101 Ops.push_back(NewC);
1102 }
1103
1104 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1105 if (CE->isCompare())
1106 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1107 DL, TLI);
1108
David Majnemera926b3e2016-07-29 03:27:33 +00001109 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001110 }
1111
1112 assert(isa<ConstantVector>(C));
1113 return ConstantVector::get(Ops);
1114}
1115
1116} // end anonymous namespace
1117
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001118Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001119 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001120 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001121 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001122 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001123
David Majnemerd536f232016-07-29 03:27:26 +00001124 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001125 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001126 // If the incoming value is undef then skip it. Note that while we could
1127 // skip the value if it is equal to the phi node itself we choose not to
1128 // because that would break the rule that constant folding only applies if
1129 // all operands are constants.
1130 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001131 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001132 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001133 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001134 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001135 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001136 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001137 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1138 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001139 // If the incoming value is a different constant to
1140 // the one we saw previously, then give up.
1141 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001142 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001143 CommonValue = C;
1144 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001145
Duncan Sands1d27f0122010-11-14 12:53:18 +00001146 // If we reach here, all incoming values are the same constant or undef.
1147 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001148 }
1149
1150 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001151 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001152 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1153 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001154
David Majnemerd536f232016-07-29 03:27:26 +00001155 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001156 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001157 for (const Use &OpU : I->operands()) {
1158 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001159 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001160 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1161 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001162
1163 Ops.push_back(Op);
1164 }
1165
David Majnemer90a97042016-07-13 04:22:12 +00001166 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001167 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001168 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001169
David Majnemer90a97042016-07-13 04:22:12 +00001170 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001171 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001172
David Majnemer90a97042016-07-13 04:22:12 +00001173 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001174 return ConstantExpr::getInsertValue(
1175 cast<Constant>(IVI->getAggregateOperand()),
1176 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001177 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001178 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001179
David Majnemer90a97042016-07-13 04:22:12 +00001180 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001181 return ConstantExpr::getExtractValue(
1182 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001183 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001184 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001185
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001186 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001187}
1188
David Majnemerd536f232016-07-29 03:27:26 +00001189Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1190 const TargetLibraryInfo *TLI) {
1191 SmallDenseMap<Constant *, Constant *> FoldedOps;
1192 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001193}
1194
Manuel Jacobe9024592016-01-21 06:33:22 +00001195Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001196 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001197 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001198 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001199 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001200}
1201
Chris Lattnerd2265b42007-12-10 22:53:04 +00001202Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001203 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001204 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001205 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001206 // fold: icmp (inttoptr x), null -> icmp x, 0
Craig Topperb23e7c72017-06-02 16:17:32 +00001207 // fold: icmp null, (inttoptr x) -> icmp 0, x
Chris Lattnerd2265b42007-12-10 22:53:04 +00001208 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Craig Topperb23e7c72017-06-02 16:17:32 +00001209 // fold: icmp 0, (ptrtoint x) -> icmp null, x
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001210 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001211 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1212 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001213 // FIXME: The following comment is out of data and the DataLayout is here now.
1214 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001215 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001216 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001217 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001218 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001219 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001220 // Convert the integer value to the right size to ensure we get the
1221 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001222 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001223 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001224 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001225 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001226 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001227
Chris Lattnerd2265b42007-12-10 22:53:04 +00001228 // Only do this transformation if the int is intptrty in size, otherwise
1229 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001230 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001231 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001232 if (CE0->getType() == IntPtrTy) {
1233 Constant *C = CE0->getOperand(0);
1234 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001235 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001236 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001237 }
1238 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001239
David Majnemer90a97042016-07-13 04:22:12 +00001240 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001241 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001242 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001243 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001244
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001245 // Convert the integer value to the right size to ensure we get the
1246 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001247 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001248 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001249 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001250 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001251 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001252 }
1253
Chandler Carruth7ec50852012-11-01 08:07:29 +00001254 // Only do this transformation if the int is intptrty in size, otherwise
1255 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001256 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001257 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001258 if (CE0->getType() == IntPtrTy &&
1259 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001260 return ConstantFoldCompareInstOperands(
1261 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001262 }
1263 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001264 }
1265 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001266
Chris Lattner8fb74c62010-01-02 01:22:23 +00001267 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1268 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1269 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1270 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001271 Constant *LHS = ConstantFoldCompareInstOperands(
1272 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1273 Constant *RHS = ConstantFoldCompareInstOperands(
1274 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001275 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001276 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001277 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001278 }
Craig Topperb23e7c72017-06-02 16:17:32 +00001279 } else if (isa<ConstantExpr>(Ops1)) {
1280 // If RHS is a constant expression, but the left side isn't, swap the
1281 // operands and try again.
1282 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1283 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001284 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001285
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001286 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001287}
1288
Cameron McInally1d0c8452019-05-05 16:07:09 +00001289Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1290 const DataLayout &DL) {
1291 assert(Instruction::isUnaryOp(Opcode));
1292
1293 return ConstantExpr::get(Opcode, Op);
1294}
1295
Manuel Jacoba61ca372016-01-21 06:26:35 +00001296Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1297 Constant *RHS,
1298 const DataLayout &DL) {
1299 assert(Instruction::isBinaryOp(Opcode));
1300 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1301 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1302 return C;
1303
1304 return ConstantExpr::get(Opcode, LHS, RHS);
1305}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001306
Manuel Jacob925d0292016-01-21 06:31:08 +00001307Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1308 Type *DestTy, const DataLayout &DL) {
1309 assert(Instruction::isCast(Opcode));
1310 switch (Opcode) {
1311 default:
1312 llvm_unreachable("Missing case");
1313 case Instruction::PtrToInt:
1314 // If the input is a inttoptr, eliminate the pair. This requires knowing
1315 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001316 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001317 if (CE->getOpcode() == Instruction::IntToPtr) {
1318 Constant *Input = CE->getOperand(0);
1319 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1320 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1321 if (PtrWidth < InWidth) {
1322 Constant *Mask =
1323 ConstantInt::get(CE->getContext(),
1324 APInt::getLowBitsSet(InWidth, PtrWidth));
1325 Input = ConstantExpr::getAnd(Input, Mask);
1326 }
1327 // Do a zext or trunc to get to the dest size.
1328 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1329 }
1330 }
1331 return ConstantExpr::getCast(Opcode, C, DestTy);
1332 case Instruction::IntToPtr:
1333 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1334 // the int size is >= the ptr size and the address spaces are the same.
1335 // This requires knowing the width of a pointer, so it can't be done in
1336 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001337 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001338 if (CE->getOpcode() == Instruction::PtrToInt) {
1339 Constant *SrcPtr = CE->getOperand(0);
1340 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1341 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1342
1343 if (MidIntSize >= SrcPtrSize) {
1344 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1345 if (SrcAS == DestTy->getPointerAddressSpace())
1346 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1347 }
1348 }
1349 }
1350
1351 return ConstantExpr::getCast(Opcode, C, DestTy);
1352 case Instruction::Trunc:
1353 case Instruction::ZExt:
1354 case Instruction::SExt:
1355 case Instruction::FPTrunc:
1356 case Instruction::FPExt:
1357 case Instruction::UIToFP:
1358 case Instruction::SIToFP:
1359 case Instruction::FPToUI:
1360 case Instruction::FPToSI:
1361 case Instruction::AddrSpaceCast:
1362 return ConstantExpr::getCast(Opcode, C, DestTy);
1363 case Instruction::BitCast:
1364 return FoldBitCast(C, DestTy, DL);
1365 }
1366}
1367
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001368Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001369 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001370 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001371 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001372
1373 // Loop over all of the operands, tracking down which value we are
1374 // addressing.
1375 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1376 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001377 if (!C)
1378 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001379 }
1380 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001381}
1382
David Majnemer90a97042016-07-13 04:22:12 +00001383Constant *
1384llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1385 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001386 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001387 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001388 for (Constant *Index : Indices) {
1389 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001390 if (!C)
1391 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001392 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001393 return C;
1394}
1395
Chris Lattner2ae054a2007-01-30 23:45:45 +00001396//===----------------------------------------------------------------------===//
1397// Constant Folding for Calls
1398//
John Criswell970af112005-10-27 16:00:10 +00001399
Chandler Carruth751d95f2019-02-11 07:51:44 +00001400bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1401 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00001402 return false;
John Criswell970af112005-10-27 16:00:10 +00001403 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001404 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001405 case Intrinsic::minnum:
1406 case Intrinsic::maxnum:
Thomas Livelyfa54e562018-10-19 18:15:32 +00001407 case Intrinsic::minimum:
1408 case Intrinsic::maximum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001409 case Intrinsic::log:
1410 case Intrinsic::log2:
1411 case Intrinsic::log10:
1412 case Intrinsic::exp:
1413 case Intrinsic::exp2:
1414 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001415 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001416 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001417 case Intrinsic::sin:
1418 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001419 case Intrinsic::trunc:
1420 case Intrinsic::rint:
1421 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001422 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001423 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001424 case Intrinsic::bswap:
1425 case Intrinsic::ctpop:
1426 case Intrinsic::ctlz:
1427 case Intrinsic::cttz:
Sanjay Patel411b8602018-08-17 13:23:44 +00001428 case Intrinsic::fshl:
1429 case Intrinsic::fshr:
Matt Arsenault83778582014-03-05 00:02:00 +00001430 case Intrinsic::fma:
1431 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001432 case Intrinsic::copysign:
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001433 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001434 case Intrinsic::strip_invariant_group:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001435 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001436 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001437 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001438 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001439 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001440 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001441 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001442 case Intrinsic::umul_with_overflow:
Sanjay Patelefc3d1d2018-11-20 17:05:55 +00001443 case Intrinsic::sadd_sat:
1444 case Intrinsic::uadd_sat:
1445 case Intrinsic::ssub_sat:
1446 case Intrinsic::usub_sat:
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00001447 case Intrinsic::smul_fix:
1448 case Intrinsic::smul_fix_sat:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001449 case Intrinsic::convert_from_fp16:
1450 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001451 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001452 case Intrinsic::x86_sse_cvtss2si:
1453 case Intrinsic::x86_sse_cvtss2si64:
1454 case Intrinsic::x86_sse_cvttss2si:
1455 case Intrinsic::x86_sse_cvttss2si64:
1456 case Intrinsic::x86_sse2_cvtsd2si:
1457 case Intrinsic::x86_sse2_cvtsd2si64:
1458 case Intrinsic::x86_sse2_cvttsd2si:
1459 case Intrinsic::x86_sse2_cvttsd2si64:
Craig Topper484b3422018-08-12 22:09:54 +00001460 case Intrinsic::x86_avx512_vcvtss2si32:
1461 case Intrinsic::x86_avx512_vcvtss2si64:
1462 case Intrinsic::x86_avx512_cvttss2si:
1463 case Intrinsic::x86_avx512_cvttss2si64:
1464 case Intrinsic::x86_avx512_vcvtsd2si32:
1465 case Intrinsic::x86_avx512_vcvtsd2si64:
1466 case Intrinsic::x86_avx512_cvttsd2si:
1467 case Intrinsic::x86_avx512_cvttsd2si64:
1468 case Intrinsic::x86_avx512_vcvtss2usi32:
1469 case Intrinsic::x86_avx512_vcvtss2usi64:
1470 case Intrinsic::x86_avx512_cvttss2usi:
1471 case Intrinsic::x86_avx512_cvttss2usi64:
1472 case Intrinsic::x86_avx512_vcvtsd2usi32:
1473 case Intrinsic::x86_avx512_vcvtsd2usi64:
1474 case Intrinsic::x86_avx512_cvttsd2usi:
1475 case Intrinsic::x86_avx512_cvttsd2usi64:
James Y Knight72f76bf2018-11-07 15:24:12 +00001476 case Intrinsic::is_constant:
John Criswell970af112005-10-27 16:00:10 +00001477 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001478 default:
1479 return false;
Craig Topper492db482017-04-07 21:36:32 +00001480 case Intrinsic::not_intrinsic: break;
John Criswell970af112005-10-27 16:00:10 +00001481 }
1482
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001483 if (!F->hasName())
1484 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001485
Chris Lattner785f9982007-08-08 06:55:43 +00001486 // In these cases, the check of the length is required. We don't want to
1487 // return true for a name like "cos\0blah" which strcmp would return equal to
1488 // "cos", but has length 8.
Evandro Menezes6f136972019-09-06 16:49:49 +00001489 StringRef Name = F->getName();
Daniel Dunbarca414c72009-07-26 08:34:35 +00001490 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001491 default:
1492 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001493 case 'a':
Evandro Menezes6f136972019-09-06 16:49:49 +00001494 return Name == "acos" || Name == "acosf" ||
1495 Name == "asin" || Name == "asinf" ||
1496 Name == "atan" || Name == "atanf" ||
1497 Name == "atan2" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001498 case 'c':
Evandro Menezes6f136972019-09-06 16:49:49 +00001499 return Name == "ceil" || Name == "ceilf" ||
1500 Name == "cos" || Name == "cosf" ||
1501 Name == "cosh" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001502 case 'e':
Evandro Menezes6f136972019-09-06 16:49:49 +00001503 return Name == "exp" || Name == "expf" ||
1504 Name == "exp2" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001505 case 'f':
Evandro Menezes6f136972019-09-06 16:49:49 +00001506 return Name == "fabs" || Name == "fabsf" ||
1507 Name == "floor" || Name == "floorf" ||
1508 Name == "fmod" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001509 case 'l':
Evandro Menezes6f136972019-09-06 16:49:49 +00001510 return Name == "log" || Name == "logf" ||
Evandro Menezes22cb3d22019-09-30 20:53:23 +00001511 Name == "log2" || Name == "log2f" ||
Evandro Menezes6f136972019-09-06 16:49:49 +00001512 Name == "log10" || Name == "log10f";
Evandro Menezes08df6e62019-09-12 21:23:22 +00001513 case 'n':
1514 return Name == "nearbyint" || Name == "nearbyintf";
Chris Lattner785f9982007-08-08 06:55:43 +00001515 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001516 return Name == "pow" || Name == "powf";
Bryant Wongb5e03b62016-12-26 14:29:29 +00001517 case 'r':
Evandro Menezes08df6e62019-09-12 21:23:22 +00001518 return Name == "rint" || Name == "rintf" ||
1519 Name == "round" || Name == "roundf";
Chris Lattner785f9982007-08-08 06:55:43 +00001520 case 's':
Evandro Menezes6f136972019-09-06 16:49:49 +00001521 return Name == "sin" || Name == "sinf" ||
1522 Name == "sinh" || Name == "sinhf" ||
1523 Name == "sqrt" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001524 case 't':
Evandro Menezes6f136972019-09-06 16:49:49 +00001525 return Name == "tan" || Name == "tanf" ||
Evandro Menezes08df6e62019-09-12 21:23:22 +00001526 Name == "tanh" || Name == "tanhf" ||
1527 Name == "trunc" || Name == "truncf";
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001528 case '_':
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001529 // Check for various function names that get used for the math functions
1530 // when the header files are preprocessed with the macro
1531 // __FINITE_MATH_ONLY__ enabled.
1532 // The '12' here is the length of the shortest name that can match.
1533 // We need to check the size before looking at Name[1] and Name[2]
1534 // so we may as well check a limit that will eliminate mismatches.
1535 if (Name.size() < 12 || Name[1] != '_')
1536 return false;
1537 switch (Name[2]) {
1538 default:
1539 return false;
1540 case 'a':
1541 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1542 Name == "__asin_finite" || Name == "__asinf_finite" ||
1543 Name == "__atan2_finite" || Name == "__atan2f_finite";
1544 case 'c':
1545 return Name == "__cosh_finite" || Name == "__coshf_finite";
1546 case 'e':
1547 return Name == "__exp_finite" || Name == "__expf_finite" ||
1548 Name == "__exp2_finite" || Name == "__exp2f_finite";
1549 case 'l':
1550 return Name == "__log_finite" || Name == "__logf_finite" ||
1551 Name == "__log10_finite" || Name == "__log10f_finite";
1552 case 'p':
1553 return Name == "__pow_finite" || Name == "__powf_finite";
1554 case 's':
1555 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1556 }
John Criswell970af112005-10-27 16:00:10 +00001557 }
1558}
1559
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001560namespace {
1561
1562Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Bixia Zhengbdf02302019-03-22 16:37:37 +00001563 if (Ty->isHalfTy() || Ty->isFloatTy()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001564 APFloat APF(V);
1565 bool unused;
Bixia Zhengbdf02302019-03-22 16:37:37 +00001566 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001567 return ConstantFP::get(Ty->getContext(), APF);
1568 }
Chris Lattner351534f2009-10-05 05:06:24 +00001569 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001570 return ConstantFP::get(Ty->getContext(), APFloat(V));
Xin Tongc063c3f2017-10-01 00:09:53 +00001571 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001572}
1573
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001574/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001575inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001576#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001577 feclearexcept(FE_ALL_EXCEPT);
1578#endif
1579 errno = 0;
1580}
1581
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001582/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001583inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001584 int errno_val = errno;
1585 if (errno_val == ERANGE || errno_val == EDOM)
1586 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001587#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001588 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1589 return true;
1590#endif
1591 return false;
1592}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001593
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001594Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001595 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001596 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001597 if (llvm_fenv_testexcept()) {
1598 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001599 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001600 }
1601
1602 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001603}
1604
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001605Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1606 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001607 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001608 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001609 if (llvm_fenv_testexcept()) {
1610 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001611 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001612 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001613
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001614 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001615}
1616
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001617/// Attempt to fold an SSE floating point to integer conversion of a constant
1618/// floating point. If roundTowardZero is false, the default IEEE rounding is
1619/// used (toward nearest, ties to even). This matches the behavior of the
1620/// non-truncating SSE instructions in the default rounding mode. The desired
1621/// integer type Ty is used to select how many bits are available for the
1622/// result. Returns null if the conversion cannot be performed, otherwise
1623/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001624Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
Craig Topper484b3422018-08-12 22:09:54 +00001625 Type *Ty, bool IsSigned) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001626 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001627 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001628 assert(ResultWidth <= 64 &&
1629 "Can only constant fold conversions to 64 and 32 bit ints");
1630
1631 uint64_t UIntVal;
1632 bool isExact = false;
1633 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1634 : APFloat::rmNearestTiesToEven;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001635 APFloat::opStatus status =
1636 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
Craig Topper484b3422018-08-12 22:09:54 +00001637 IsSigned, mode, &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001638 if (status != APFloat::opOK &&
1639 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001640 return nullptr;
Craig Topper484b3422018-08-12 22:09:54 +00001641 return ConstantInt::get(Ty, UIntVal, IsSigned);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001642}
1643
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001644double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001645 Type *Ty = Op->getType();
1646
1647 if (Ty->isFloatTy())
1648 return Op->getValueAPF().convertToFloat();
1649
1650 if (Ty->isDoubleTy())
1651 return Op->getValueAPF().convertToDouble();
1652
1653 bool unused;
1654 APFloat APF = Op->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001655 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001656 return APF.convertToDouble();
1657}
1658
James Y Knight72f76bf2018-11-07 15:24:12 +00001659static bool isManifestConstant(const Constant *c) {
1660 if (isa<ConstantData>(c)) {
1661 return true;
1662 } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1663 for (const Value *subc : c->operand_values()) {
1664 if (!isManifestConstant(cast<Constant>(subc)))
1665 return false;
1666 }
1667 return true;
1668 }
1669 return false;
1670}
1671
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00001672static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1673 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1674 C = &CI->getValue();
1675 return true;
1676 }
1677 if (isa<UndefValue>(Op)) {
1678 C = nullptr;
1679 return true;
1680 }
1681 return false;
1682}
1683
Bjorn Pettersson485a4212019-06-24 12:07:17 +00001684static Constant *ConstantFoldScalarCall1(StringRef Name,
1685 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001686 Type *Ty,
1687 ArrayRef<Constant *> Operands,
1688 const TargetLibraryInfo *TLI,
1689 const CallBase *Call) {
1690 assert(Operands.size() == 1 && "Wrong number of operands.");
1691
1692 if (IntrinsicID == Intrinsic::is_constant) {
1693 // We know we have a "Constant" argument. But we want to only
1694 // return true for manifest constants, not those that depend on
1695 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1696 if (isManifestConstant(Operands[0]))
1697 return ConstantInt::getTrue(Ty->getContext());
1698 return nullptr;
1699 }
1700 if (isa<UndefValue>(Operands[0])) {
1701 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1702 // ctpop() is between 0 and bitwidth, pick 0 for undef.
1703 if (IntrinsicID == Intrinsic::cos ||
1704 IntrinsicID == Intrinsic::ctpop)
1705 return Constant::getNullValue(Ty);
1706 if (IntrinsicID == Intrinsic::bswap ||
1707 IntrinsicID == Intrinsic::bitreverse ||
1708 IntrinsicID == Intrinsic::launder_invariant_group ||
1709 IntrinsicID == Intrinsic::strip_invariant_group)
1710 return Operands[0];
1711 }
1712
1713 if (isa<ConstantPointerNull>(Operands[0])) {
1714 // launder(null) == null == strip(null) iff in addrspace 0
1715 if (IntrinsicID == Intrinsic::launder_invariant_group ||
1716 IntrinsicID == Intrinsic::strip_invariant_group) {
1717 // If instruction is not yet put in a basic block (e.g. when cloning
1718 // a function during inlining), Call's caller may not be available.
1719 // So check Call's BB first before querying Call->getCaller.
1720 const Function *Caller =
1721 Call->getParent() ? Call->getCaller() : nullptr;
1722 if (Caller &&
1723 !NullPointerIsDefined(
1724 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1725 return Operands[0];
1726 }
James Y Knight72f76bf2018-11-07 15:24:12 +00001727 return nullptr;
1728 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001729 }
1730
1731 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1732 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1733 APFloat Val(Op->getValueAPF());
1734
1735 bool lost = false;
1736 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1737
1738 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001739 }
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001740
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001741 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1742 return nullptr;
1743
Evandro Menezesed5f4522019-09-11 21:46:57 +00001744 // Use internal versions of these intrinsics.
1745 APFloat U = Op->getValueAPF();
1746
1747 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1748 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1749 return ConstantFP::get(Ty->getContext(), U);
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001750 }
1751
Evandro Menezesed5f4522019-09-11 21:46:57 +00001752 if (IntrinsicID == Intrinsic::round) {
1753 U.roundToIntegral(APFloat::rmNearestTiesToAway);
1754 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001755 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001756
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001757 if (IntrinsicID == Intrinsic::ceil) {
Evandro Menezesed5f4522019-09-11 21:46:57 +00001758 U.roundToIntegral(APFloat::rmTowardPositive);
1759 return ConstantFP::get(Ty->getContext(), U);
1760 }
1761
1762 if (IntrinsicID == Intrinsic::floor) {
1763 U.roundToIntegral(APFloat::rmTowardNegative);
1764 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001765 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001766
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001767 if (IntrinsicID == Intrinsic::trunc) {
Evandro Menezesed5f4522019-09-11 21:46:57 +00001768 U.roundToIntegral(APFloat::rmTowardZero);
1769 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001770 }
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001771
Evandro Menezesed5f4522019-09-11 21:46:57 +00001772 if (IntrinsicID == Intrinsic::fabs) {
1773 U.clearSign();
1774 return ConstantFP::get(Ty->getContext(), U);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001775 }
1776
1777 /// We only fold functions with finite arguments. Folding NaN and inf is
1778 /// likely to be aborted with an exception anyway, and some host libms
1779 /// have known errors raising exceptions.
1780 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1781 return nullptr;
1782
1783 /// Currently APFloat versions of these functions do not exist, so we use
1784 /// the host native double versions. Float versions are not called
1785 /// directly but for all these it is true (float)(f((double)arg)) ==
1786 /// f(arg). Long double not supported yet.
1787 double V = getValueAsDouble(Op);
1788
1789 switch (IntrinsicID) {
1790 default: break;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001791 case Intrinsic::log:
1792 return ConstantFoldFP(log, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001793 case Intrinsic::log2:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001794 // TODO: What about hosts that lack a C99 library?
Evandro Menezes6f136972019-09-06 16:49:49 +00001795 return ConstantFoldFP(Log2, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001796 case Intrinsic::log10:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001797 // TODO: What about hosts that lack a C99 library?
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001798 return ConstantFoldFP(log10, V, Ty);
1799 case Intrinsic::exp:
1800 return ConstantFoldFP(exp, V, Ty);
1801 case Intrinsic::exp2:
Evandro Menezes7feb8122019-09-06 18:24:21 +00001802 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
1803 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001804 case Intrinsic::sin:
1805 return ConstantFoldFP(sin, V, Ty);
1806 case Intrinsic::cos:
1807 return ConstantFoldFP(cos, V, Ty);
1808 case Intrinsic::sqrt:
1809 return ConstantFoldFP(sqrt, V, Ty);
1810 }
1811
1812 if (!TLI)
1813 return nullptr;
1814
Evandro Menezes6f136972019-09-06 16:49:49 +00001815 LibFunc Func = NotLibFunc;
1816 TLI->getLibFunc(Name, Func);
Evandro Menezes6f136972019-09-06 16:49:49 +00001817 switch (Func) {
1818 default:
1819 break;
1820 case LibFunc_acos:
1821 case LibFunc_acosf:
1822 case LibFunc_acos_finite:
1823 case LibFunc_acosf_finite:
1824 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001825 return ConstantFoldFP(acos, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001826 break;
1827 case LibFunc_asin:
1828 case LibFunc_asinf:
1829 case LibFunc_asin_finite:
1830 case LibFunc_asinf_finite:
1831 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001832 return ConstantFoldFP(asin, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001833 break;
1834 case LibFunc_atan:
1835 case LibFunc_atanf:
1836 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001837 return ConstantFoldFP(atan, V, Ty);
1838 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001839 case LibFunc_ceil:
1840 case LibFunc_ceilf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001841 if (TLI->has(Func)) {
1842 U.roundToIntegral(APFloat::rmTowardPositive);
1843 return ConstantFP::get(Ty->getContext(), U);
1844 }
Evandro Menezes6f136972019-09-06 16:49:49 +00001845 break;
1846 case LibFunc_cos:
1847 case LibFunc_cosf:
1848 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001849 return ConstantFoldFP(cos, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001850 break;
1851 case LibFunc_cosh:
1852 case LibFunc_coshf:
1853 case LibFunc_cosh_finite:
1854 case LibFunc_coshf_finite:
1855 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001856 return ConstantFoldFP(cosh, V, Ty);
1857 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001858 case LibFunc_exp:
1859 case LibFunc_expf:
1860 case LibFunc_exp_finite:
1861 case LibFunc_expf_finite:
1862 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001863 return ConstantFoldFP(exp, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001864 break;
1865 case LibFunc_exp2:
1866 case LibFunc_exp2f:
1867 case LibFunc_exp2_finite:
1868 case LibFunc_exp2f_finite:
1869 if (TLI->has(Func))
1870 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001871 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1872 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001873 case LibFunc_fabs:
1874 case LibFunc_fabsf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001875 if (TLI->has(Func)) {
1876 U.clearSign();
1877 return ConstantFP::get(Ty->getContext(), U);
1878 }
Evandro Menezes6f136972019-09-06 16:49:49 +00001879 break;
1880 case LibFunc_floor:
1881 case LibFunc_floorf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001882 if (TLI->has(Func)) {
1883 U.roundToIntegral(APFloat::rmTowardNegative);
1884 return ConstantFP::get(Ty->getContext(), U);
1885 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001886 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001887 case LibFunc_log:
1888 case LibFunc_logf:
1889 case LibFunc_log_finite:
1890 case LibFunc_logf_finite:
1891 if (V > 0.0 && TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001892 return ConstantFoldFP(log, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001893 break;
Evandro Menezes22cb3d22019-09-30 20:53:23 +00001894 case LibFunc_log2:
1895 case LibFunc_log2f:
1896 case LibFunc_log2_finite:
1897 case LibFunc_log2f_finite:
1898 if (V > 0.0 && TLI->has(Func))
1899 // TODO: What about hosts that lack a C99 library?
1900 return ConstantFoldFP(Log2, V, Ty);
1901 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001902 case LibFunc_log10:
1903 case LibFunc_log10f:
1904 case LibFunc_log10_finite:
1905 case LibFunc_log10f_finite:
1906 if (V > 0.0 && TLI->has(Func))
Evandro Menezes7feb8122019-09-06 18:24:21 +00001907 // TODO: What about hosts that lack a C99 library?
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001908 return ConstantFoldFP(log10, V, Ty);
1909 break;
Evandro Menezes08df6e62019-09-12 21:23:22 +00001910 case LibFunc_nearbyint:
1911 case LibFunc_nearbyintf:
1912 case LibFunc_rint:
1913 case LibFunc_rintf:
1914 if (TLI->has(Func)) {
1915 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1916 return ConstantFP::get(Ty->getContext(), U);
1917 }
1918 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001919 case LibFunc_round:
1920 case LibFunc_roundf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00001921 if (TLI->has(Func)) {
1922 U.roundToIntegral(APFloat::rmNearestTiesToAway);
1923 return ConstantFP::get(Ty->getContext(), U);
1924 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001925 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001926 case LibFunc_sin:
1927 case LibFunc_sinf:
1928 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001929 return ConstantFoldFP(sin, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001930 break;
1931 case LibFunc_sinh:
1932 case LibFunc_sinhf:
1933 case LibFunc_sinh_finite:
1934 case LibFunc_sinhf_finite:
1935 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001936 return ConstantFoldFP(sinh, V, Ty);
Evandro Menezes6f136972019-09-06 16:49:49 +00001937 break;
1938 case LibFunc_sqrt:
1939 case LibFunc_sqrtf:
1940 if (V >= 0.0 && TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001941 return ConstantFoldFP(sqrt, V, Ty);
1942 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001943 case LibFunc_tan:
1944 case LibFunc_tanf:
1945 if (TLI->has(Func))
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001946 return ConstantFoldFP(tan, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001947 break;
Evandro Menezes6f136972019-09-06 16:49:49 +00001948 case LibFunc_tanh:
1949 case LibFunc_tanhf:
1950 if (TLI->has(Func))
1951 return ConstantFoldFP(tanh, V, Ty);
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001952 break;
Evandro Menezes08df6e62019-09-12 21:23:22 +00001953 case LibFunc_trunc:
1954 case LibFunc_truncf:
1955 if (TLI->has(Func)) {
1956 U.roundToIntegral(APFloat::rmTowardZero);
1957 return ConstantFP::get(Ty->getContext(), U);
1958 }
1959 break;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00001960 }
1961 return nullptr;
1962 }
1963
1964 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
1965 switch (IntrinsicID) {
1966 case Intrinsic::bswap:
1967 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1968 case Intrinsic::ctpop:
1969 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1970 case Intrinsic::bitreverse:
1971 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1972 case Intrinsic::convert_from_fp16: {
1973 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
1974
1975 bool lost = false;
1976 APFloat::opStatus status = Val.convert(
1977 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1978
1979 // Conversion is always precise.
1980 (void)status;
1981 assert(status == APFloat::opOK && !lost &&
1982 "Precision lost during fp16 constfolding");
1983
1984 return ConstantFP::get(Ty->getContext(), Val);
1985 }
1986 default:
1987 return nullptr;
1988 }
1989 }
1990
1991 // Support ConstantVector in case we have an Undef in the top.
1992 if (isa<ConstantVector>(Operands[0]) ||
1993 isa<ConstantDataVector>(Operands[0])) {
1994 auto *Op = cast<Constant>(Operands[0]);
1995 switch (IntrinsicID) {
1996 default: break;
1997 case Intrinsic::x86_sse_cvtss2si:
1998 case Intrinsic::x86_sse_cvtss2si64:
1999 case Intrinsic::x86_sse2_cvtsd2si:
2000 case Intrinsic::x86_sse2_cvtsd2si64:
2001 if (ConstantFP *FPOp =
2002 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2003 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2004 /*roundTowardZero=*/false, Ty,
2005 /*IsSigned*/true);
2006 break;
2007 case Intrinsic::x86_sse_cvttss2si:
2008 case Intrinsic::x86_sse_cvttss2si64:
2009 case Intrinsic::x86_sse2_cvttsd2si:
2010 case Intrinsic::x86_sse2_cvttsd2si64:
2011 if (ConstantFP *FPOp =
2012 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2013 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2014 /*roundTowardZero=*/true, Ty,
2015 /*IsSigned*/true);
2016 break;
2017 }
2018 }
2019
2020 return nullptr;
2021}
2022
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002023static Constant *ConstantFoldScalarCall2(StringRef Name,
2024 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002025 Type *Ty,
2026 ArrayRef<Constant *> Operands,
2027 const TargetLibraryInfo *TLI,
2028 const CallBase *Call) {
2029 assert(Operands.size() == 2 && "Wrong number of operands.");
2030
2031 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2032 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2033 return nullptr;
2034 double Op1V = getValueAsDouble(Op1);
2035
2036 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2037 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00002038 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00002039
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002040 double Op2V = getValueAsDouble(Op2);
2041 if (IntrinsicID == Intrinsic::pow) {
2042 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2043 }
2044 if (IntrinsicID == Intrinsic::copysign) {
2045 APFloat V1 = Op1->getValueAPF();
2046 const APFloat &V2 = Op2->getValueAPF();
2047 V1.copySign(V2);
2048 return ConstantFP::get(Ty->getContext(), V1);
Karthik Bhatb67688a2014-03-07 04:36:21 +00002049 }
2050
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002051 if (IntrinsicID == Intrinsic::minnum) {
2052 const APFloat &C1 = Op1->getValueAPF();
2053 const APFloat &C2 = Op2->getValueAPF();
2054 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002055 }
2056
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002057 if (IntrinsicID == Intrinsic::maxnum) {
2058 const APFloat &C1 = Op1->getValueAPF();
2059 const APFloat &C2 = Op2->getValueAPF();
2060 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002061 }
2062
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002063 if (IntrinsicID == Intrinsic::minimum) {
2064 const APFloat &C1 = Op1->getValueAPF();
2065 const APFloat &C2 = Op2->getValueAPF();
2066 return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
Karthik Bhatd818e382015-07-21 08:52:23 +00002067 }
2068
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002069 if (IntrinsicID == Intrinsic::maximum) {
2070 const APFloat &C1 = Op1->getValueAPF();
2071 const APFloat &C2 = Op2->getValueAPF();
2072 return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
Owen Andersond4ebfd82013-02-06 22:43:31 +00002073 }
2074
Benjamin Kramer061d1472014-03-05 19:41:48 +00002075 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00002076 return nullptr;
Evandro Menezes6f136972019-09-06 16:49:49 +00002077
2078 LibFunc Func = NotLibFunc;
2079 TLI->getLibFunc(Name, Func);
2080 switch (Func) {
2081 default:
2082 break;
2083 case LibFunc_pow:
2084 case LibFunc_powf:
2085 case LibFunc_pow_finite:
2086 case LibFunc_powf_finite:
2087 if (TLI->has(Func))
2088 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2089 break;
2090 case LibFunc_fmod:
2091 case LibFunc_fmodf:
Evandro Menezesed5f4522019-09-11 21:46:57 +00002092 if (TLI->has(Func)) {
2093 APFloat V = Op1->getValueAPF();
2094 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2095 return ConstantFP::get(Ty->getContext(), V);
2096 }
Evandro Menezes6f136972019-09-06 16:49:49 +00002097 break;
2098 case LibFunc_atan2:
2099 case LibFunc_atan2f:
2100 case LibFunc_atan2_finite:
2101 case LibFunc_atan2f_finite:
2102 if (TLI->has(Func))
2103 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2104 break;
2105 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002106 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2107 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2108 return ConstantFP::get(Ty->getContext(),
2109 APFloat((float)std::pow((float)Op1V,
2110 (int)Op2C->getZExtValue())));
2111 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2112 return ConstantFP::get(Ty->getContext(),
2113 APFloat((float)std::pow((float)Op1V,
2114 (int)Op2C->getZExtValue())));
2115 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2116 return ConstantFP::get(Ty->getContext(),
2117 APFloat((double)std::pow((double)Op1V,
2118 (int)Op2C->getZExtValue())));
Chris Lattner9ca7c092009-10-05 05:00:35 +00002119 }
Craig Topper9f008862014-04-15 04:59:12 +00002120 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00002121 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00002122
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002123 if (Operands[0]->getType()->isIntegerTy() &&
2124 Operands[1]->getType()->isIntegerTy()) {
2125 const APInt *C0, *C1;
2126 if (!getConstIntOrUndef(Operands[0], C0) ||
2127 !getConstIntOrUndef(Operands[1], C1))
Craig Topper9f008862014-04-15 04:59:12 +00002128 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00002129
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002130 switch (IntrinsicID) {
2131 default: break;
Roman Lebedevff21e3f2019-09-01 11:56:52 +00002132 case Intrinsic::usub_with_overflow:
2133 case Intrinsic::ssub_with_overflow:
2134 case Intrinsic::uadd_with_overflow:
2135 case Intrinsic::sadd_with_overflow:
2136 // X - undef -> { undef, false }
2137 // undef - X -> { undef, false }
2138 // X + undef -> { undef, false }
2139 // undef + x -> { undef, false }
2140 if (!C0 || !C1) {
2141 return ConstantStruct::get(
2142 cast<StructType>(Ty),
2143 {UndefValue::get(Ty->getStructElementType(0)),
2144 Constant::getNullValue(Ty->getStructElementType(1))});
2145 }
2146 LLVM_FALLTHROUGH;
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002147 case Intrinsic::smul_with_overflow:
Roman Lebedevff21e3f2019-09-01 11:56:52 +00002148 case Intrinsic::umul_with_overflow: {
2149 // undef * X -> { 0, false }
2150 // X * undef -> { 0, false }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002151 if (!C0 || !C1)
2152 return Constant::getNullValue(Ty);
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002153
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002154 APInt Res;
2155 bool Overflow;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002156 switch (IntrinsicID) {
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002157 default: llvm_unreachable("Invalid case");
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002158 case Intrinsic::sadd_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002159 Res = C0->sadd_ov(*C1, Overflow);
2160 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002161 case Intrinsic::uadd_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002162 Res = C0->uadd_ov(*C1, Overflow);
2163 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002164 case Intrinsic::ssub_with_overflow:
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002165 Res = C0->ssub_ov(*C1, Overflow);
2166 break;
2167 case Intrinsic::usub_with_overflow:
2168 Res = C0->usub_ov(*C1, Overflow);
2169 break;
2170 case Intrinsic::smul_with_overflow:
2171 Res = C0->smul_ov(*C1, Overflow);
2172 break;
2173 case Intrinsic::umul_with_overflow:
2174 Res = C0->umul_ov(*C1, Overflow);
2175 break;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002176 }
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002177 Constant *Ops[] = {
2178 ConstantInt::get(Ty->getContext(), Res),
2179 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2180 };
2181 return ConstantStruct::get(cast<StructType>(Ty), Ops);
2182 }
2183 case Intrinsic::uadd_sat:
2184 case Intrinsic::sadd_sat:
2185 if (!C0 && !C1)
2186 return UndefValue::get(Ty);
2187 if (!C0 || !C1)
2188 return Constant::getAllOnesValue(Ty);
2189 if (IntrinsicID == Intrinsic::uadd_sat)
2190 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2191 else
2192 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2193 case Intrinsic::usub_sat:
2194 case Intrinsic::ssub_sat:
2195 if (!C0 && !C1)
2196 return UndefValue::get(Ty);
2197 if (!C0 || !C1)
2198 return Constant::getNullValue(Ty);
2199 if (IntrinsicID == Intrinsic::usub_sat)
2200 return ConstantInt::get(Ty, C0->usub_sat(*C1));
2201 else
2202 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2203 case Intrinsic::cttz:
2204 case Intrinsic::ctlz:
2205 assert(C1 && "Must be constant int");
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002206
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002207 // cttz(0, 1) and ctlz(0, 1) are undef.
2208 if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2209 return UndefValue::get(Ty);
2210 if (!C0)
2211 return Constant::getNullValue(Ty);
2212 if (IntrinsicID == Intrinsic::cttz)
2213 return ConstantInt::get(Ty, C0->countTrailingZeros());
2214 else
2215 return ConstantInt::get(Ty, C0->countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00002216 }
Craig Topper484b3422018-08-12 22:09:54 +00002217
Craig Topper9f008862014-04-15 04:59:12 +00002218 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002219 }
Matt Arsenault83778582014-03-05 00:02:00 +00002220
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002221 // Support ConstantVector in case we have an Undef in the top.
2222 if ((isa<ConstantVector>(Operands[0]) ||
2223 isa<ConstantDataVector>(Operands[0])) &&
2224 // Check for default rounding mode.
2225 // FIXME: Support other rounding modes?
2226 isa<ConstantInt>(Operands[1]) &&
2227 cast<ConstantInt>(Operands[1])->getValue() == 4) {
2228 auto *Op = cast<Constant>(Operands[0]);
2229 switch (IntrinsicID) {
2230 default: break;
2231 case Intrinsic::x86_avx512_vcvtss2si32:
2232 case Intrinsic::x86_avx512_vcvtss2si64:
2233 case Intrinsic::x86_avx512_vcvtsd2si32:
2234 case Intrinsic::x86_avx512_vcvtsd2si64:
2235 if (ConstantFP *FPOp =
2236 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2237 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2238 /*roundTowardZero=*/false, Ty,
2239 /*IsSigned*/true);
2240 break;
2241 case Intrinsic::x86_avx512_vcvtss2usi32:
2242 case Intrinsic::x86_avx512_vcvtss2usi64:
2243 case Intrinsic::x86_avx512_vcvtsd2usi32:
2244 case Intrinsic::x86_avx512_vcvtsd2usi64:
2245 if (ConstantFP *FPOp =
2246 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2247 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2248 /*roundTowardZero=*/false, Ty,
2249 /*IsSigned*/false);
2250 break;
2251 case Intrinsic::x86_avx512_cvttss2si:
2252 case Intrinsic::x86_avx512_cvttss2si64:
2253 case Intrinsic::x86_avx512_cvttsd2si:
2254 case Intrinsic::x86_avx512_cvttsd2si64:
2255 if (ConstantFP *FPOp =
2256 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2257 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2258 /*roundTowardZero=*/true, Ty,
2259 /*IsSigned*/true);
2260 break;
2261 case Intrinsic::x86_avx512_cvttss2usi:
2262 case Intrinsic::x86_avx512_cvttss2usi64:
2263 case Intrinsic::x86_avx512_cvttsd2usi:
2264 case Intrinsic::x86_avx512_cvttsd2usi64:
2265 if (ConstantFP *FPOp =
2266 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2267 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2268 /*roundTowardZero=*/true, Ty,
2269 /*IsSigned*/false);
2270 break;
2271 }
2272 }
2273 return nullptr;
2274}
2275
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002276static Constant *ConstantFoldScalarCall3(StringRef Name,
2277 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002278 Type *Ty,
2279 ArrayRef<Constant *> Operands,
2280 const TargetLibraryInfo *TLI,
2281 const CallBase *Call) {
2282 assert(Operands.size() == 3 && "Wrong number of operands.");
Matt Arsenault83778582014-03-05 00:02:00 +00002283
David Majnemer90a97042016-07-13 04:22:12 +00002284 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2285 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2286 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002287 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00002288 default: break;
2289 case Intrinsic::fma:
2290 case Intrinsic::fmuladd: {
2291 APFloat V = Op1->getValueAPF();
Sanjay Patel3f5a8082019-09-12 14:10:50 +00002292 V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(),
2293 APFloat::rmNearestTiesToEven);
2294 return ConstantFP::get(Ty->getContext(), V);
Matt Arsenault83778582014-03-05 00:02:00 +00002295 }
2296 }
2297 }
2298 }
2299 }
2300
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00002301 if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
2302 if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
2303 if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) {
2304 switch (IntrinsicID) {
2305 default: break;
2306 case Intrinsic::smul_fix:
2307 case Intrinsic::smul_fix_sat: {
2308 // This code performs rounding towards negative infinity in case the
2309 // result cannot be represented exactly for the given scale. Targets
2310 // that do care about rounding should use a target hook for specifying
2311 // how rounding should be done, and provide their own folding to be
2312 // consistent with rounding. This is the same approach as used by
2313 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2314 APInt Lhs = Op1->getValue();
2315 APInt Rhs = Op2->getValue();
2316 unsigned Scale = Op3->getValue().getZExtValue();
2317 unsigned Width = Lhs.getBitWidth();
2318 assert(Scale < Width && "Illegal scale.");
2319 unsigned ExtendedWidth = Width * 2;
2320 APInt Product = (Lhs.sextOrSelf(ExtendedWidth) *
2321 Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale);
2322 if (IntrinsicID == Intrinsic::smul_fix_sat) {
2323 APInt MaxValue =
2324 APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2325 APInt MinValue =
2326 APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2327 Product = APIntOps::smin(Product, MaxValue);
2328 Product = APIntOps::smax(Product, MinValue);
2329 }
2330 return ConstantInt::get(Ty->getContext(),
2331 Product.sextOrTrunc(Width));
2332 }
2333 }
2334 }
2335 }
2336 }
2337
Sanjay Patel411b8602018-08-17 13:23:44 +00002338 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002339 const APInt *C0, *C1, *C2;
2340 if (!getConstIntOrUndef(Operands[0], C0) ||
2341 !getConstIntOrUndef(Operands[1], C1) ||
2342 !getConstIntOrUndef(Operands[2], C2))
Sanjay Patel411b8602018-08-17 13:23:44 +00002343 return nullptr;
2344
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002345 bool IsRight = IntrinsicID == Intrinsic::fshr;
2346 if (!C2)
2347 return Operands[IsRight ? 1 : 0];
2348 if (!C0 && !C1)
2349 return UndefValue::get(Ty);
2350
Sanjay Patel411b8602018-08-17 13:23:44 +00002351 // The shift amount is interpreted as modulo the bitwidth. If the shift
2352 // amount is effectively 0, avoid UB due to oversized inverse shift below.
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002353 unsigned BitWidth = C2->getBitWidth();
2354 unsigned ShAmt = C2->urem(BitWidth);
Sanjay Patel411b8602018-08-17 13:23:44 +00002355 if (!ShAmt)
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002356 return Operands[IsRight ? 1 : 0];
Sanjay Patel411b8602018-08-17 13:23:44 +00002357
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002358 // (C0 << ShlAmt) | (C1 >> LshrAmt)
Sanjay Patel411b8602018-08-17 13:23:44 +00002359 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2360 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002361 if (!C0)
2362 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2363 if (!C1)
2364 return ConstantInt::get(Ty, C0->shl(ShlAmt));
2365 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
Sanjay Patel411b8602018-08-17 13:23:44 +00002366 }
2367
Craig Topper9f008862014-04-15 04:59:12 +00002368 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002369}
Benjamin Kramer061d1472014-03-05 19:41:48 +00002370
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002371static Constant *ConstantFoldScalarCall(StringRef Name,
2372 Intrinsic::ID IntrinsicID,
Bjorn Petterssonb81b9a42019-06-19 14:27:51 +00002373 Type *Ty,
2374 ArrayRef<Constant *> Operands,
2375 const TargetLibraryInfo *TLI,
2376 const CallBase *Call) {
2377 if (Operands.size() == 1)
2378 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2379
2380 if (Operands.size() == 2)
2381 return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2382
2383 if (Operands.size() == 3)
2384 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2385
2386 return nullptr;
2387}
2388
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002389static Constant *ConstantFoldVectorCall(StringRef Name,
2390 Intrinsic::ID IntrinsicID,
Joerg Sonnenbergerb2e96162019-06-07 13:28:52 +00002391 VectorType *VTy,
2392 ArrayRef<Constant *> Operands,
2393 const DataLayout &DL,
2394 const TargetLibraryInfo *TLI,
2395 const CallBase *Call) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002396 SmallVector<Constant *, 4> Result(VTy->getNumElements());
2397 SmallVector<Constant *, 4> Lane(Operands.size());
2398 Type *Ty = VTy->getElementType();
2399
David Majnemer7f781ab2016-07-14 00:29:50 +00002400 if (IntrinsicID == Intrinsic::masked_load) {
2401 auto *SrcPtr = Operands[0];
2402 auto *Mask = Operands[2];
2403 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00002404
David Majnemer7f781ab2016-07-14 00:29:50 +00002405 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00002406
2407 SmallVector<Constant *, 32> NewElements;
2408 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00002409 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00002410 if (!MaskElt)
2411 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00002412 auto *PassthruElt = Passthru->getAggregateElement(I);
2413 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2414 if (isa<UndefValue>(MaskElt)) {
2415 if (PassthruElt)
2416 NewElements.push_back(PassthruElt);
2417 else if (VecElt)
2418 NewElements.push_back(VecElt);
2419 else
2420 return nullptr;
2421 }
2422 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002423 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002424 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002425 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002426 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002427 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002428 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002429 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002430 } else {
2431 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002432 }
2433 }
David Majnemer17a95aa2016-07-14 06:58:37 +00002434 if (NewElements.size() != VTy->getNumElements())
2435 return nullptr;
2436 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00002437 }
2438
Benjamin Kramer061d1472014-03-05 19:41:48 +00002439 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2440 // Gather a column of constants.
2441 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
Bjorn Pettersson485a4212019-06-24 12:07:17 +00002442 // Some intrinsics use a scalar type for certain arguments.
2443 if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
Bjorn Pettersson16ff5fe2019-06-19 14:28:03 +00002444 Lane[J] = Operands[J];
2445 continue;
2446 }
Craig Topper7c553ed2017-06-03 18:50:29 +00002447
Benjamin Kramer061d1472014-03-05 19:41:48 +00002448 Constant *Agg = Operands[J]->getAggregateElement(I);
2449 if (!Agg)
2450 return nullptr;
2451
2452 Lane[J] = Agg;
2453 }
2454
2455 // Use the regular scalar folding to simplify this column.
Chandler Carruth751d95f2019-02-11 07:51:44 +00002456 Constant *Folded =
2457 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002458 if (!Folded)
2459 return nullptr;
2460 Result[I] = Folded;
2461 }
2462
2463 return ConstantVector::get(Result);
2464}
2465
Eugene Zelenko35623fb2016-03-28 17:40:08 +00002466} // end anonymous namespace
2467
Chandler Carruth751d95f2019-02-11 07:51:44 +00002468Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
2469 ArrayRef<Constant *> Operands,
2470 const TargetLibraryInfo *TLI) {
2471 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002472 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002473 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00002474 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002475 StringRef Name = F->getName();
2476
2477 Type *Ty = F->getReturnType();
2478
David Majnemer90a97042016-07-13 04:22:12 +00002479 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00002480 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
Chandler Carruth751d95f2019-02-11 07:51:44 +00002481 F->getParent()->getDataLayout(), TLI, Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002482
Chandler Carruth751d95f2019-02-11 07:51:44 +00002483 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
2484 Call);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002485}
Eli Friedmanb6befc32016-11-02 20:48:11 +00002486
Chandler Carruth751d95f2019-02-11 07:51:44 +00002487bool llvm::isMathLibCallNoop(const CallBase *Call,
2488 const TargetLibraryInfo *TLI) {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002489 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2490 // (and to some extent ConstantFoldScalarCall).
Chandler Carruth751d95f2019-02-11 07:51:44 +00002491 if (Call->isNoBuiltin() || Call->isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002492 return false;
Chandler Carruth751d95f2019-02-11 07:51:44 +00002493 Function *F = Call->getCalledFunction();
Eli Friedmanb6befc32016-11-02 20:48:11 +00002494 if (!F)
2495 return false;
2496
David L. Jonesd21529f2017-01-23 23:16:46 +00002497 LibFunc Func;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002498 if (!TLI || !TLI->getLibFunc(*F, Func))
2499 return false;
2500
Chandler Carruth751d95f2019-02-11 07:51:44 +00002501 if (Call->getNumArgOperands() == 1) {
2502 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002503 const APFloat &Op = OpC->getValueAPF();
2504 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002505 case LibFunc_logl:
2506 case LibFunc_log:
2507 case LibFunc_logf:
2508 case LibFunc_log2l:
2509 case LibFunc_log2:
2510 case LibFunc_log2f:
2511 case LibFunc_log10l:
2512 case LibFunc_log10:
2513 case LibFunc_log10f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002514 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2515
David L. Jonesd21529f2017-01-23 23:16:46 +00002516 case LibFunc_expl:
2517 case LibFunc_exp:
2518 case LibFunc_expf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002519 // FIXME: These boundaries are slightly conservative.
2520 if (OpC->getType()->isDoubleTy())
2521 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2522 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2523 if (OpC->getType()->isFloatTy())
2524 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2525 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2526 break;
2527
David L. Jonesd21529f2017-01-23 23:16:46 +00002528 case LibFunc_exp2l:
2529 case LibFunc_exp2:
2530 case LibFunc_exp2f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002531 // FIXME: These boundaries are slightly conservative.
2532 if (OpC->getType()->isDoubleTy())
2533 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2534 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2535 if (OpC->getType()->isFloatTy())
2536 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2537 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2538 break;
2539
David L. Jonesd21529f2017-01-23 23:16:46 +00002540 case LibFunc_sinl:
2541 case LibFunc_sin:
2542 case LibFunc_sinf:
2543 case LibFunc_cosl:
2544 case LibFunc_cos:
2545 case LibFunc_cosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002546 return !Op.isInfinity();
2547
David L. Jonesd21529f2017-01-23 23:16:46 +00002548 case LibFunc_tanl:
2549 case LibFunc_tan:
2550 case LibFunc_tanf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002551 // FIXME: Stop using the host math library.
2552 // FIXME: The computation isn't done in the right precision.
2553 Type *Ty = OpC->getType();
2554 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2555 double OpV = getValueAsDouble(OpC);
2556 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2557 }
2558 break;
2559 }
2560
David L. Jonesd21529f2017-01-23 23:16:46 +00002561 case LibFunc_asinl:
2562 case LibFunc_asin:
2563 case LibFunc_asinf:
2564 case LibFunc_acosl:
2565 case LibFunc_acos:
2566 case LibFunc_acosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002567 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2568 APFloat::cmpLessThan &&
2569 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2570 APFloat::cmpGreaterThan;
2571
David L. Jonesd21529f2017-01-23 23:16:46 +00002572 case LibFunc_sinh:
2573 case LibFunc_cosh:
2574 case LibFunc_sinhf:
2575 case LibFunc_coshf:
2576 case LibFunc_sinhl:
2577 case LibFunc_coshl:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002578 // FIXME: These boundaries are slightly conservative.
2579 if (OpC->getType()->isDoubleTy())
2580 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2581 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2582 if (OpC->getType()->isFloatTy())
2583 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2584 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2585 break;
2586
David L. Jonesd21529f2017-01-23 23:16:46 +00002587 case LibFunc_sqrtl:
2588 case LibFunc_sqrt:
2589 case LibFunc_sqrtf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002590 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2591
2592 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2593 // maybe others?
2594 default:
2595 break;
2596 }
2597 }
2598 }
2599
Chandler Carruth751d95f2019-02-11 07:51:44 +00002600 if (Call->getNumArgOperands() == 2) {
2601 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
2602 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
Eli Friedmanb6befc32016-11-02 20:48:11 +00002603 if (Op0C && Op1C) {
2604 const APFloat &Op0 = Op0C->getValueAPF();
2605 const APFloat &Op1 = Op1C->getValueAPF();
2606
2607 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002608 case LibFunc_powl:
2609 case LibFunc_pow:
2610 case LibFunc_powf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002611 // FIXME: Stop using the host math library.
2612 // FIXME: The computation isn't done in the right precision.
2613 Type *Ty = Op0C->getType();
2614 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2615 if (Ty == Op1C->getType()) {
2616 double Op0V = getValueAsDouble(Op0C);
2617 double Op1V = getValueAsDouble(Op1C);
2618 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2619 }
2620 }
2621 break;
2622 }
2623
David L. Jonesd21529f2017-01-23 23:16:46 +00002624 case LibFunc_fmodl:
2625 case LibFunc_fmod:
2626 case LibFunc_fmodf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002627 return Op0.isNaN() || Op1.isNaN() ||
2628 (!Op0.isInfinity() && !Op1.isZero());
2629
2630 default:
2631 break;
2632 }
2633 }
2634 }
2635
2636 return false;
2637}