blob: 69e1dda9e75098faa53714e0ddc4120df104d39b [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"
Alp Tokerc817d6a2014-06-09 18:28:53 +000028#include "llvm/Config/config.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000036#include "llvm/IR/InstrTypes.h"
37#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000043#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000044#include "llvm/Support/KnownBits.h"
John Criswell970af112005-10-27 16:00:10 +000045#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000046#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000047#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000048#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000049#include <cmath>
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include <cstddef>
51#include <cstdint>
Alp Tokerc817d6a2014-06-09 18:28:53 +000052
John Criswell970af112005-10-27 16:00:10 +000053using namespace llvm;
54
Eugene Zelenko35623fb2016-03-28 17:40:08 +000055namespace {
56
Chris Lattner44d68b92007-01-31 00:51:48 +000057//===----------------------------------------------------------------------===//
58// Constant Folding internal helper functions
59//===----------------------------------------------------------------------===//
60
Matt Arsenault47a4b392016-12-02 02:26:02 +000061static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
62 Constant *C, Type *SrcEltTy,
63 unsigned NumSrcElts,
64 const DataLayout &DL) {
65 // Now that we know that the input value is a vector of integers, just shift
66 // and insert them into our result.
67 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
68 for (unsigned i = 0; i != NumSrcElts; ++i) {
69 Constant *Element;
70 if (DL.isLittleEndian())
71 Element = C->getAggregateElement(NumSrcElts - i - 1);
72 else
73 Element = C->getAggregateElement(i);
74
75 if (Element && isa<UndefValue>(Element)) {
76 Result <<= BitShift;
77 continue;
78 }
79
80 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
81 if (!ElementCI)
82 return ConstantExpr::getBitCast(C, DestTy);
83
84 Result <<= BitShift;
85 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
86 }
87
88 return nullptr;
89}
90
Matt Arsenault624e1b32016-12-07 20:56:11 +000091/// Constant fold bitcast, symbolically evaluating it with DataLayout.
Sanjay Patel0d7dee62014-10-02 15:13:22 +000092/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000093/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000094Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000095 // Catch the obvious splat cases.
96 if (C->isNullValue() && !DestTy->isX86_MMXTy())
97 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000098 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
99 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +0000100 return Constant::getAllOnesValue(DestTy);
101
Matt Arsenault624e1b32016-12-07 20:56:11 +0000102 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
103 // Handle a vector->scalar integer/fp cast.
104 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
105 unsigned NumSrcElts = VTy->getNumElements();
106 Type *SrcEltTy = VTy->getElementType();
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000107
Matt Arsenault624e1b32016-12-07 20:56:11 +0000108 // If the vector is a vector of floating point, convert it to vector of int
109 // to simplify things.
110 if (SrcEltTy->isFloatingPointTy()) {
111 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
112 Type *SrcIVTy =
113 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
114 // Ask IR to do the conversion now that #elts line up.
115 C = ConstantExpr::getBitCast(C, SrcIVTy);
116 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000117
Matt Arsenault624e1b32016-12-07 20:56:11 +0000118 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
119 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
120 SrcEltTy, NumSrcElts, DL))
121 return CE;
122
123 if (isa<IntegerType>(DestTy))
124 return ConstantInt::get(DestTy, Result);
125
126 APFloat FP(DestTy->getFltSemantics(), Result);
127 return ConstantFP::get(DestTy->getContext(), FP);
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000128 }
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000129 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000130
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000131 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000132 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000133 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000134 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000135
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000136 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
137 // vector so the code below can handle it uniformly.
138 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
139 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000141 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000142
Chris Lattner9d051242009-10-25 06:08:26 +0000143 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000144 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000145 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000146
Chandler Carruthef860a22013-01-02 09:10:48 +0000147 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000148 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000149 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000150 if (NumDstElt == NumSrcElt)
151 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000152
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000153 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000154 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000155
156 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000157 // requires endianness information to do the right thing. For example,
158 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
159 // folds to (little endian):
160 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
161 // and to (big endian):
162 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000163
Chris Lattner9d051242009-10-25 06:08:26 +0000164 // First thing is first. We only want to think about integer here, so if
165 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000166 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000167 // Fold to an vector of integers with same size as our FP type.
168 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000169 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000170 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
171 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000172 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000173
Chandler Carruthef860a22013-01-02 09:10:48 +0000174 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000175 return ConstantExpr::getBitCast(C, DestTy);
176 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000177
Chris Lattner9d051242009-10-25 06:08:26 +0000178 // Okay, we know the destination is integer, if the input is FP, convert
179 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000180 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000181 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000182 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000183 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000184 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000185 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000186 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000187 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
188 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000189 return C;
190 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000191
Chris Lattner9d051242009-10-25 06:08:26 +0000192 // Now we know that the input and output vectors are both integer vectors
193 // of the same size, and that their #elements is not the same. Do the
194 // conversion here, which depends on whether the input or output has
195 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000196 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000197
Chris Lattner9d051242009-10-25 06:08:26 +0000198 SmallVector<Constant*, 32> Result;
199 if (NumDstElt < NumSrcElt) {
200 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
201 Constant *Zero = Constant::getNullValue(DstEltTy);
202 unsigned Ratio = NumSrcElt/NumDstElt;
203 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
204 unsigned SrcElt = 0;
205 for (unsigned i = 0; i != NumDstElt; ++i) {
206 // Build each element of the result.
207 Constant *Elt = Zero;
208 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
209 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000210 Constant *Src = C->getAggregateElement(SrcElt++);
211 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000212 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000213 else
214 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000215 if (!Src) // Reject constantexpr elements.
216 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000217
Chris Lattner9d051242009-10-25 06:08:26 +0000218 // Zero extend the element to the right size.
219 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000220
Chris Lattner9d051242009-10-25 06:08:26 +0000221 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000222 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000223 ConstantInt::get(Src->getType(), ShiftAmt));
224 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000225
Chris Lattner9d051242009-10-25 06:08:26 +0000226 // Mix it in.
227 Elt = ConstantExpr::getOr(Elt, Src);
228 }
229 Result.push_back(Elt);
230 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000231 return ConstantVector::get(Result);
232 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000233
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000234 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
235 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000237
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000238 // Loop over each source value, expanding into multiple results.
239 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagio7277afe2016-09-13 14:50:47 +0000240 auto *Element = C->getAggregateElement(i);
241
242 if (!Element) // Reject constantexpr elements.
243 return ConstantExpr::getBitCast(C, DestTy);
244
245 if (isa<UndefValue>(Element)) {
246 // Correctly Propagate undef values.
247 Result.append(Ratio, UndefValue::get(DstEltTy));
248 continue;
249 }
250
251 auto *Src = dyn_cast<ConstantInt>(Element);
252 if (!Src)
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000253 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000254
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000255 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
256 for (unsigned j = 0; j != Ratio; ++j) {
257 // Shift the piece of the value into the right place, depending on
258 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000259 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000260 ConstantInt::get(Src->getType(), ShiftAmt));
261 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000262
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000263 // Truncate the element to an integer with the same pointer size and
264 // convert the element back to a pointer using a inttoptr.
265 if (DstEltTy->isPointerTy()) {
266 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
267 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
268 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
269 continue;
270 }
271
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000272 // Truncate and remember this piece.
273 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000274 }
275 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000276
Chris Lattner69229312011-02-15 00:14:00 +0000277 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000278}
279
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000280} // end anonymous namespace
281
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000282/// If this constant is a constant offset from a global, return the global and
283/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000284bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
285 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000286 // Trivial case, constant is the global.
287 if ((GV = dyn_cast<GlobalValue>(C))) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000288 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000289 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000290 return true;
291 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000292
Chris Lattner44d68b92007-01-31 00:51:48 +0000293 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000294 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000295 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000296
Chris Lattner44d68b92007-01-31 00:51:48 +0000297 // Look through ptr->int and ptr->ptr casts.
298 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000299 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000301
302 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000303 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000304 if (!GEP)
305 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000306
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000307 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000308 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000309
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000310 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000312 return false;
313
314 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000316 return false;
317
318 Offset = TmpOffset;
319 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000320}
321
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000322Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
323 const DataLayout &DL) {
324 do {
325 Type *SrcTy = C->getType();
326
327 // If the type sizes are the same and a cast is legal, just directly
328 // cast the constant.
329 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
330 Instruction::CastOps Cast = Instruction::BitCast;
331 // If we are going from a pointer to int or vice versa, we spell the cast
332 // differently.
333 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
334 Cast = Instruction::IntToPtr;
335 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
336 Cast = Instruction::PtrToInt;
337
338 if (CastInst::castIsValid(Cast, C, DestTy))
339 return ConstantExpr::getCast(Cast, C, DestTy);
340 }
341
342 // If this isn't an aggregate type, there is nothing we can do to drill down
343 // and find a bitcastable constant.
344 if (!SrcTy->isAggregateType())
345 return nullptr;
346
347 // We're simulating a load through a pointer that was bitcast to point to
348 // a different type, so we can try to walk down through the initial
Nikita Popov79c994d2018-12-11 20:29:16 +0000349 // elements of an aggregate to see if some part of the aggregate is
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000350 // castable to implement the "load" semantic model.
Nikita Popov79c994d2018-12-11 20:29:16 +0000351 if (SrcTy->isStructTy()) {
352 // Struct types might have leading zero-length elements like [0 x i32],
353 // which are certainly not what we are looking for, so skip them.
354 unsigned Elem = 0;
355 Constant *ElemC;
356 do {
357 ElemC = C->getAggregateElement(Elem++);
358 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()) == 0);
359 C = ElemC;
360 } else {
361 C = C->getAggregateElement(0u);
362 }
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000363 } while (C);
364
365 return nullptr;
366}
367
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000368namespace {
369
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000370/// Recursive helper to read bits out of global. C is the constant being copied
371/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
372/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000373/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000374bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
375 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000376 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000377 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000378
Chris Lattner3db7bd22009-10-24 05:27:19 +0000379 // If this element is zero or undefined, we can just return since *CurPtr is
380 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000381 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
382 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000383
David Majnemer90a97042016-07-13 04:22:12 +0000384 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000385 if (CI->getBitWidth() > 64 ||
386 (CI->getBitWidth() & 7) != 0)
387 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000388
Chris Lattnered00b802009-10-23 06:23:49 +0000389 uint64_t Val = CI->getZExtValue();
390 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000391
Chris Lattnered00b802009-10-23 06:23:49 +0000392 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000393 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000394 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000395 n = IntBytes - n - 1;
396 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000397 ++ByteOffset;
398 }
399 return true;
400 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000401
David Majnemer90a97042016-07-13 04:22:12 +0000402 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000403 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000404 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
405 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000406 }
407 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
409 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000410 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000411 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000412 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
413 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000414 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000415 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000416 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000417
David Majnemer90a97042016-07-13 04:22:12 +0000418 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000419 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000420 unsigned Index = SL->getElementContainingOffset(ByteOffset);
421 uint64_t CurEltOffset = SL->getElementOffset(Index);
422 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000423
Eugene Zelenko1804a772016-08-25 00:45:04 +0000424 while (true) {
Chris Lattnered00b802009-10-23 06:23:49 +0000425 // If the element access is to the element itself and not to tail padding,
426 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000428
429 if (ByteOffset < EltSize &&
430 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000431 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000432 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000433
Chris Lattnered00b802009-10-23 06:23:49 +0000434 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000435
Chris Lattnered00b802009-10-23 06:23:49 +0000436 // Check to see if we read from the last struct element, if so we're done.
437 if (Index == CS->getType()->getNumElements())
438 return true;
439
440 // If we read all of the bytes we needed from this element we're done.
441 uint64_t NextEltOffset = SL->getElementOffset(Index);
442
Matt Arsenault8c789092013-08-12 23:15:58 +0000443 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000444 return true;
445
446 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000447 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
448 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000449 ByteOffset = 0;
450 CurEltOffset = NextEltOffset;
451 }
452 // not reached.
453 }
454
Chris Lattner67058832012-01-25 06:48:06 +0000455 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
456 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000457 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000458 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000459 uint64_t Index = ByteOffset / EltSize;
460 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000461 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000462 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000463 NumElts = AT->getNumElements();
464 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000465 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000466
Chris Lattner67058832012-01-25 06:48:06 +0000467 for (; Index != NumElts; ++Index) {
468 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000469 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000470 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000471
472 uint64_t BytesWritten = EltSize - Offset;
473 assert(BytesWritten <= EltSize && "Not indexing into this element?");
474 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000475 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000476
Chris Lattner67058832012-01-25 06:48:06 +0000477 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000478 BytesLeft -= BytesWritten;
479 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000480 }
481 return true;
482 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000483
David Majnemer90a97042016-07-13 04:22:12 +0000484 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000485 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000487 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000489 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000490 }
491
Chris Lattnered00b802009-10-23 06:23:49 +0000492 // Otherwise, unknown initializer type.
493 return false;
494}
495
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000496Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
497 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000498 auto *PTy = cast<PointerType>(C->getType());
499 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000500
Chris Lattnered00b802009-10-23 06:23:49 +0000501 // If this isn't an integer load we can't fold it directly.
502 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000503 unsigned AS = PTy->getAddressSpace();
504
Chris Lattnered00b802009-10-23 06:23:49 +0000505 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000506 // and then bitcast the result. This can be useful for union cases. Note
507 // that address spaces don't matter here since we're not going to result in
508 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000509 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000510 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000511 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000512 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000513 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000514 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000515 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000516 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000517 MapTy = PointerType::getIntNTy(C->getContext(),
518 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000519 } else
Craig Topper9f008862014-04-15 04:59:12 +0000520 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000521
Eduard Burtescu14239212016-01-22 01:17:26 +0000522 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
523 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000524 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000525 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000526 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000527
Chris Lattnered00b802009-10-23 06:23:49 +0000528 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000529 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000530 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000531
Chris Lattnered00b802009-10-23 06:23:49 +0000532 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000533 APInt OffsetAI;
534 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000535 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000536
David Majnemer90a97042016-07-13 04:22:12 +0000537 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000538 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000539 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000540 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000541
David Majnemerf89660a2016-07-13 23:33:07 +0000542 int64_t Offset = OffsetAI.getSExtValue();
543 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000544
Chris Lattnered00b802009-10-23 06:23:49 +0000545 // If we're not accessing anything in this constant, the result is undefined.
David Majnemerf89660a2016-07-13 23:33:07 +0000546 if (Offset + BytesLoaded <= 0)
547 return UndefValue::get(IntType);
548
549 // If we're not accessing anything in this constant, the result is undefined.
550 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000551 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000552
Chris Lattner59f94c02009-10-23 06:50:36 +0000553 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000554 unsigned char *CurPtr = RawBytes;
555 unsigned BytesLeft = BytesLoaded;
556
557 // If we're loading off the beginning of the global, some bytes may be valid.
558 if (Offset < 0) {
559 CurPtr += -Offset;
560 BytesLeft += Offset;
561 Offset = 0;
562 }
563
564 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000565 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000566
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000567 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000568 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000569 ResultVal = RawBytes[BytesLoaded - 1];
570 for (unsigned i = 1; i != BytesLoaded; ++i) {
571 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000572 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000573 }
574 } else {
575 ResultVal = RawBytes[0];
576 for (unsigned i = 1; i != BytesLoaded; ++i) {
577 ResultVal <<= 8;
578 ResultVal |= RawBytes[i];
579 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000580 }
Chris Lattnered00b802009-10-23 06:23:49 +0000581
Chris Lattner59f94c02009-10-23 06:50:36 +0000582 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000583}
584
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000585Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
586 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000587 auto *SrcPtr = CE->getOperand(0);
588 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
589 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000590 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000591 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000592
Eduard Burtescu14239212016-01-22 01:17:26 +0000593 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000594 if (!C)
595 return nullptr;
596
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000597 return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000598}
599
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000600} // end anonymous namespace
601
Eduard Burtescu14239212016-01-22 01:17:26 +0000602Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000603 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000604 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000605 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000606 if (GV->isConstant() && GV->hasDefinitiveInitializer())
607 return GV->getInitializer();
608
David Majnemered9abe12015-07-22 22:29:30 +0000609 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000610 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000611 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000612
Chris Lattnercf7e8942009-10-22 06:44:07 +0000613 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000614 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000615 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000616 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000617
Chris Lattnercf7e8942009-10-22 06:44:07 +0000618 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000619 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000620 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000621 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000622 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
623 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000624 }
625 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000626 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000627
Chandler Carrutha0e56952014-05-15 09:56:28 +0000628 if (CE->getOpcode() == Instruction::BitCast)
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000629 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000630 return LoadedC;
631
Chris Lattnercf7e8942009-10-22 06:44:07 +0000632 // Instead of loading constant c string, use corresponding integer value
633 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000634 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000635 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000636 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000637 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000638 // Replace load with immediate integer if the result is an integer or fp
639 // value.
640 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000641 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000642 APInt StrVal(NumBits, 0);
643 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000645 for (unsigned char C : reverse(Str.bytes())) {
646 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000647 StrVal = (StrVal << 8) | SingleChar;
648 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000649 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000650 for (unsigned char C : Str.bytes()) {
651 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000652 StrVal = (StrVal << 8) | SingleChar;
653 }
654 // Append NULL at the end.
655 SingleChar = 0;
656 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000657 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000658
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000659 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
660 if (Ty->isFloatingPointTy())
661 Res = ConstantExpr::getBitCast(Res, Ty);
662 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000663 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000664 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000665
Chris Lattnercf7e8942009-10-22 06:44:07 +0000666 // If this load comes from anywhere in a constant global, and if the global
667 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000668 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000669 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000670 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000671 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000672 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000673 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000674 }
675 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000676
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000677 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000678 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000679}
680
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000681namespace {
682
683Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000684 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000685
David Majnemer90a97042016-07-13 04:22:12 +0000686 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000687 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000688
Craig Topper9f008862014-04-15 04:59:12 +0000689 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000690}
Chris Lattner44d68b92007-01-31 00:51:48 +0000691
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000692/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000693/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000694/// these together. If target data info is available, it is provided as DL,
695/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000696Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
697 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000698 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000699
Chris Lattner44d68b92007-01-31 00:51:48 +0000700 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
701 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
702 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000703
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 if (Opc == Instruction::And) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000705 KnownBits Known0 = computeKnownBits(Op0, DL);
706 KnownBits Known1 = computeKnownBits(Op1, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000707 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000708 // All the bits of Op0 that the 'and' could be masking are already zero.
709 return Op0;
710 }
Craig Topperb45eabc2017-04-26 16:39:58 +0000711 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000712 // All the bits of Op1 that the 'and' could be masking are already zero.
713 return Op1;
714 }
715
Craig Topper8189a872017-05-03 23:12:29 +0000716 Known0.Zero |= Known1.Zero;
717 Known0.One &= Known1.One;
718 if (Known0.isConstant())
719 return ConstantInt::get(Op0->getType(), Known0.getConstant());
Nick Lewycky06417742013-02-14 03:23:37 +0000720 }
721
Chris Lattner44d68b92007-01-31 00:51:48 +0000722 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
723 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000724 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000725 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000726 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000727
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000728 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
729 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
730 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000731
Chris Lattner44d68b92007-01-31 00:51:48 +0000732 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000733 // PtrToInt may change the bitwidth so we have convert to the right size
734 // first.
735 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
736 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000737 }
738 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000739
Craig Topper9f008862014-04-15 04:59:12 +0000740 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000741}
742
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000743/// If array indices are not pointer-sized integers, explicitly cast them so
744/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000745Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourned93620b2016-11-10 22:34:55 +0000746 Type *ResultTy, Optional<unsigned> InRangeIndex,
747 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000748 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischerdc091192016-12-08 17:22:35 +0000749 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000750
751 bool Any = false;
752 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000753 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000754 if ((i == 1 ||
Keno Fischerdc091192016-12-08 17:22:35 +0000755 !isa<StructType>(GetElementPtrInst::getIndexedType(
756 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kupersteindd92c782016-12-21 17:34:21 +0000757 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000758 Any = true;
Michael Kupersteindd92c782016-12-21 17:34:21 +0000759 Type *NewType = Ops[i]->getType()->isVectorTy()
760 ? IntPtrTy
761 : IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000762 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
763 true,
Michael Kupersteindd92c782016-12-21 17:34:21 +0000764 NewType,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000765 true),
Michael Kupersteindd92c782016-12-21 17:34:21 +0000766 Ops[i], NewType));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000767 } else
768 NewIdxs.push_back(Ops[i]);
769 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000770
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000771 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000772 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000773
Peter Collingbourned93620b2016-11-10 22:34:55 +0000774 Constant *C = ConstantExpr::getGetElementPtr(
775 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemerd536f232016-07-29 03:27:26 +0000776 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
777 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000778
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000779 return C;
780}
781
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000782/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000783Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000784 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000785 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000786 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000787 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000788
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000789 ElemTy = NewPtrTy->getPointerElementType();
790
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000791 // Preserve the address space number of the pointer.
792 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000793 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000794 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000795 }
796 return Ptr;
797}
798
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000799/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000800Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
801 ArrayRef<Constant *> Ops,
802 const DataLayout &DL,
803 const TargetLibraryInfo *TLI) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000804 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000805 bool InBounds = GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000806
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000807 Type *SrcElemTy = GEP->getSourceElementType();
808 Type *ResElemTy = GEP->getResultElementType();
809 Type *ResTy = GEP->getType();
810 if (!SrcElemTy->isSized())
811 return nullptr;
812
Peter Collingbourned93620b2016-11-10 22:34:55 +0000813 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
814 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000815 return C;
816
Chris Lattner44d68b92007-01-31 00:51:48 +0000817 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000818 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000819 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000820
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000821 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000822
823 // If this is a constant expr gep that is effectively computing an
824 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000825 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000826 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000827
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000828 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
829 // "inttoptr (sub (ptrtoint Ptr), V)"
830 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
831 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
832 assert((!CE || CE->getType() == IntPtrTy) &&
833 "CastGEPIndices didn't canonicalize index types!");
834 if (CE && CE->getOpcode() == Instruction::Sub &&
835 CE->getOperand(0)->isNullValue()) {
836 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
837 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
838 Res = ConstantExpr::getIntToPtr(Res, ResTy);
839 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
840 Res = FoldedRes;
841 return Res;
842 }
Chris Lattner5858e092011-01-06 06:19:46 +0000843 }
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000844 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000845 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000846
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000847 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000848 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000849 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000850 DL.getIndexedOffsetInType(
851 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000852 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000853 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000854
855 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000856 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000857 InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000858 InBounds &= GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000859
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000860 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000861
862 // Do not try the incorporate the sub-GEP if some index is not a number.
863 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000864 for (Value *NestedOp : NestedOps)
865 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000866 AllConstantInt = false;
867 break;
868 }
869 if (!AllConstantInt)
870 break;
871
Dan Gohman474e488c2010-03-10 19:31:51 +0000872 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000873 SrcElemTy = GEP->getSourceElementType();
874 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000875 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000876 }
877
Dan Gohman81ce8422009-08-19 18:18:36 +0000878 // If the base value for this address is a literal integer value, fold the
879 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000880 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000881 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000882 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000883 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000884 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000885 }
886 }
887
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000888 auto *PTy = cast<PointerType>(Ptr->getType());
889 if ((Ptr->isNullValue() || BasePtr != 0) &&
890 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000891 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000892 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000893 }
894
895 // Otherwise form a regular getelementptr. Recompute the indices so that
896 // we eliminate over-indexing of the notional static type array bounds.
897 // This makes it easy to determine if the getelementptr is "inbounds".
898 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000899 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000900 SmallVector<Constant *, 32> NewIdxs;
901
Dan Gohmanc59ba422009-08-19 22:46:59 +0000902 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000903 if (!Ty->isStructTy()) {
904 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000905 // The only pointer indexing we'll do is on the first index of the GEP.
906 if (!NewIdxs.empty())
907 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000908
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000909 Ty = SrcElemTy;
910
Chris Lattner77c36d62009-12-03 01:05:45 +0000911 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000912 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000913 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000914 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
915 Ty = ATy->getElementType();
916 } else {
917 // We've reached some non-indexable type.
918 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000919 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000920
Dan Gohman81ce8422009-08-19 18:18:36 +0000921 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000922 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000923 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000924 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000925 // index for this level and proceed to the next level to see if it can
926 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000927 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000928 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000929 // The element size is non-zero divide the offset by the element
930 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000931 bool Overflow;
932 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
933 if (Overflow)
934 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000935 Offset -= NewIdx * ElemSize;
936 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
937 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000938 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000939 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000940 // If we end up with an offset that isn't valid for this struct type, we
941 // can't re-form this GEP in a regular form, so bail out. The pointer
942 // operand likely went through casts that are necessary to make the GEP
943 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000944 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000945 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000946 break;
947
948 // Determine which field of the struct the offset points into. The
949 // getZExtValue is fine as we've already ensured that the offset is
950 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000951 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000952 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
953 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000954 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000955 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000956 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000957 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000958
959 // If we haven't used up the entire offset by descending the static
960 // type, then the offset is pointing into the middle of an indivisible
961 // member, so we can't simplify it.
962 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000963 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000964
Peter Collingbourned93620b2016-11-10 22:34:55 +0000965 // Preserve the inrange index from the innermost GEP if possible. We must
966 // have calculated the same indices up to and including the inrange index.
967 Optional<unsigned> InRangeIndex;
968 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
969 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
970 NewIdxs.size() > *LastIRIndex) {
971 InRangeIndex = LastIRIndex;
972 for (unsigned I = 0; I <= *LastIRIndex; ++I)
Peter Collingbournec7d28192018-09-11 01:53:36 +0000973 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
974 return nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +0000975 }
976
Dan Gohman21c62162009-09-11 00:04:14 +0000977 // Create a GEP.
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000978 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
979 InBounds, InRangeIndex);
Matt Arsenault8c789092013-08-12 23:15:58 +0000980 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000981 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000982
Dan Gohmanc59ba422009-08-19 22:46:59 +0000983 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000984 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000985 if (Ty != ResElemTy)
986 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000987
988 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000989}
990
Manuel Jacobe9024592016-01-21 06:33:22 +0000991/// Attempt to constant fold an instruction with the
992/// specified opcode and operands. If successful, the constant result is
993/// returned, if not, null is returned. Note that this function can fail when
994/// attempting to fold instructions like loads and stores, which have no
995/// constant expression form.
David Majnemera926b3e2016-07-29 03:27:33 +0000996Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000997 ArrayRef<Constant *> Ops,
998 const DataLayout &DL,
999 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001000 Type *DestTy = InstOrCE->getType();
1001
Manuel Jacobe9024592016-01-21 06:33:22 +00001002 // Handle easy binops first.
1003 if (Instruction::isBinaryOp(Opcode))
1004 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1005
1006 if (Instruction::isCast(Opcode))
1007 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1008
David Majnemer17bdf442016-07-13 03:42:38 +00001009 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001010 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1011 return C;
1012
Peter Collingbourned93620b2016-11-10 22:34:55 +00001013 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1014 Ops.slice(1), GEP->isInBounds(),
1015 GEP->getInRangeIndex());
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001016 }
1017
David Majnemer57b94c82016-07-29 03:27:31 +00001018 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1019 return CE->getWithOperands(Ops);
1020
Manuel Jacobe9024592016-01-21 06:33:22 +00001021 switch (Opcode) {
1022 default: return nullptr;
1023 case Instruction::ICmp:
1024 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1025 case Instruction::Call:
Andrew Kaylor647025f2017-06-09 23:18:11 +00001026 if (auto *F = dyn_cast<Function>(Ops.back())) {
1027 ImmutableCallSite CS(cast<CallInst>(InstOrCE));
1028 if (canConstantFoldCallTo(CS, F))
1029 return ConstantFoldCall(CS, F, Ops.slice(0, Ops.size() - 1), TLI);
1030 }
Manuel Jacobe9024592016-01-21 06:33:22 +00001031 return nullptr;
1032 case Instruction::Select:
1033 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1034 case Instruction::ExtractElement:
1035 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1036 case Instruction::InsertElement:
1037 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1038 case Instruction::ShuffleVector:
1039 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +00001040 }
1041}
1042
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001043} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +00001044
1045//===----------------------------------------------------------------------===//
1046// Constant Folding public APIs
1047//===----------------------------------------------------------------------===//
1048
David Majnemerd536f232016-07-29 03:27:26 +00001049namespace {
1050
1051Constant *
1052ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1053 const TargetLibraryInfo *TLI,
1054 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1055 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1056 return nullptr;
1057
1058 SmallVector<Constant *, 8> Ops;
1059 for (const Use &NewU : C->operands()) {
1060 auto *NewC = cast<Constant>(&NewU);
1061 // Recursively fold the ConstantExpr's operands. If we have already folded
1062 // a ConstantExpr, we don't have to process it again.
1063 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1064 auto It = FoldedOps.find(NewC);
1065 if (It == FoldedOps.end()) {
1066 if (auto *FoldedC =
1067 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
David Majnemerd536f232016-07-29 03:27:26 +00001068 FoldedOps.insert({NewC, FoldedC});
David Greenda211702017-03-21 10:17:39 +00001069 NewC = FoldedC;
David Majnemerd536f232016-07-29 03:27:26 +00001070 } else {
1071 FoldedOps.insert({NewC, NewC});
1072 }
1073 } else {
1074 NewC = It->second;
1075 }
1076 }
1077 Ops.push_back(NewC);
1078 }
1079
1080 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1081 if (CE->isCompare())
1082 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1083 DL, TLI);
1084
David Majnemera926b3e2016-07-29 03:27:33 +00001085 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001086 }
1087
1088 assert(isa<ConstantVector>(C));
1089 return ConstantVector::get(Ops);
1090}
1091
1092} // end anonymous namespace
1093
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001094Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001095 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001096 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001097 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001098 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001099
David Majnemerd536f232016-07-29 03:27:26 +00001100 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001101 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001102 // If the incoming value is undef then skip it. Note that while we could
1103 // skip the value if it is equal to the phi node itself we choose not to
1104 // because that would break the rule that constant folding only applies if
1105 // all operands are constants.
1106 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001107 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001108 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001109 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001110 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001111 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001112 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001113 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1114 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001115 // If the incoming value is a different constant to
1116 // the one we saw previously, then give up.
1117 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001118 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001119 CommonValue = C;
1120 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001121
Duncan Sands1d27f0122010-11-14 12:53:18 +00001122 // If we reach here, all incoming values are the same constant or undef.
1123 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001124 }
1125
1126 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001127 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001128 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1129 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001130
David Majnemerd536f232016-07-29 03:27:26 +00001131 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001132 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001133 for (const Use &OpU : I->operands()) {
1134 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001135 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001136 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1137 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001138
1139 Ops.push_back(Op);
1140 }
1141
David Majnemer90a97042016-07-13 04:22:12 +00001142 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001143 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001145
David Majnemer90a97042016-07-13 04:22:12 +00001146 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001147 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001148
David Majnemer90a97042016-07-13 04:22:12 +00001149 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001150 return ConstantExpr::getInsertValue(
1151 cast<Constant>(IVI->getAggregateOperand()),
1152 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001153 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001154 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001155
David Majnemer90a97042016-07-13 04:22:12 +00001156 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001157 return ConstantExpr::getExtractValue(
1158 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001159 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001160 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001161
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001162 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001163}
1164
David Majnemerd536f232016-07-29 03:27:26 +00001165Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1166 const TargetLibraryInfo *TLI) {
1167 SmallDenseMap<Constant *, Constant *> FoldedOps;
1168 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001169}
1170
Manuel Jacobe9024592016-01-21 06:33:22 +00001171Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001172 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001173 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001174 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001175 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001176}
1177
Chris Lattnerd2265b42007-12-10 22:53:04 +00001178Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001179 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001181 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001182 // fold: icmp (inttoptr x), null -> icmp x, 0
Craig Topperb23e7c72017-06-02 16:17:32 +00001183 // fold: icmp null, (inttoptr x) -> icmp 0, x
Chris Lattnerd2265b42007-12-10 22:53:04 +00001184 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Craig Topperb23e7c72017-06-02 16:17:32 +00001185 // fold: icmp 0, (ptrtoint x) -> icmp null, x
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001186 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001187 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1188 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001189 // FIXME: The following comment is out of data and the DataLayout is here now.
1190 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001191 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001192 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001193 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001194 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001195 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001196 // Convert the integer value to the right size to ensure we get the
1197 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001198 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001199 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001200 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001201 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001202 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001203
Chris Lattnerd2265b42007-12-10 22:53:04 +00001204 // Only do this transformation if the int is intptrty in size, otherwise
1205 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001206 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001207 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001208 if (CE0->getType() == IntPtrTy) {
1209 Constant *C = CE0->getOperand(0);
1210 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001211 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001212 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001213 }
1214 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001215
David Majnemer90a97042016-07-13 04:22:12 +00001216 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001217 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001218 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001219 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001220
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001221 // Convert the integer value to the right size to ensure we get the
1222 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001223 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001224 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001225 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001226 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001227 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001228 }
1229
Chandler Carruth7ec50852012-11-01 08:07:29 +00001230 // Only do this transformation if the int is intptrty in size, otherwise
1231 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001232 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001233 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001234 if (CE0->getType() == IntPtrTy &&
1235 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001236 return ConstantFoldCompareInstOperands(
1237 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001238 }
1239 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001240 }
1241 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001242
Chris Lattner8fb74c62010-01-02 01:22:23 +00001243 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1244 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1245 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1246 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247 Constant *LHS = ConstantFoldCompareInstOperands(
1248 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1249 Constant *RHS = ConstantFoldCompareInstOperands(
1250 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001251 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001252 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001253 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001254 }
Craig Topperb23e7c72017-06-02 16:17:32 +00001255 } else if (isa<ConstantExpr>(Ops1)) {
1256 // If RHS is a constant expression, but the left side isn't, swap the
1257 // operands and try again.
1258 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1259 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001260 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001261
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001262 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001263}
1264
Manuel Jacoba61ca372016-01-21 06:26:35 +00001265Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1266 Constant *RHS,
1267 const DataLayout &DL) {
1268 assert(Instruction::isBinaryOp(Opcode));
1269 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1270 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1271 return C;
1272
1273 return ConstantExpr::get(Opcode, LHS, RHS);
1274}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001275
Manuel Jacob925d0292016-01-21 06:31:08 +00001276Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1277 Type *DestTy, const DataLayout &DL) {
1278 assert(Instruction::isCast(Opcode));
1279 switch (Opcode) {
1280 default:
1281 llvm_unreachable("Missing case");
1282 case Instruction::PtrToInt:
1283 // If the input is a inttoptr, eliminate the pair. This requires knowing
1284 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001285 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001286 if (CE->getOpcode() == Instruction::IntToPtr) {
1287 Constant *Input = CE->getOperand(0);
1288 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1289 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1290 if (PtrWidth < InWidth) {
1291 Constant *Mask =
1292 ConstantInt::get(CE->getContext(),
1293 APInt::getLowBitsSet(InWidth, PtrWidth));
1294 Input = ConstantExpr::getAnd(Input, Mask);
1295 }
1296 // Do a zext or trunc to get to the dest size.
1297 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1298 }
1299 }
1300 return ConstantExpr::getCast(Opcode, C, DestTy);
1301 case Instruction::IntToPtr:
1302 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1303 // the int size is >= the ptr size and the address spaces are the same.
1304 // This requires knowing the width of a pointer, so it can't be done in
1305 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001306 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001307 if (CE->getOpcode() == Instruction::PtrToInt) {
1308 Constant *SrcPtr = CE->getOperand(0);
1309 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1310 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1311
1312 if (MidIntSize >= SrcPtrSize) {
1313 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1314 if (SrcAS == DestTy->getPointerAddressSpace())
1315 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1316 }
1317 }
1318 }
1319
1320 return ConstantExpr::getCast(Opcode, C, DestTy);
1321 case Instruction::Trunc:
1322 case Instruction::ZExt:
1323 case Instruction::SExt:
1324 case Instruction::FPTrunc:
1325 case Instruction::FPExt:
1326 case Instruction::UIToFP:
1327 case Instruction::SIToFP:
1328 case Instruction::FPToUI:
1329 case Instruction::FPToSI:
1330 case Instruction::AddrSpaceCast:
1331 return ConstantExpr::getCast(Opcode, C, DestTy);
1332 case Instruction::BitCast:
1333 return FoldBitCast(C, DestTy, DL);
1334 }
1335}
1336
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001337Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001338 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001339 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001340 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001341
1342 // Loop over all of the operands, tracking down which value we are
1343 // addressing.
1344 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1345 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001346 if (!C)
1347 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001348 }
1349 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001350}
1351
David Majnemer90a97042016-07-13 04:22:12 +00001352Constant *
1353llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1354 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001355 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001356 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001357 for (Constant *Index : Indices) {
1358 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001359 if (!C)
1360 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001361 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001362 return C;
1363}
1364
Chris Lattner2ae054a2007-01-30 23:45:45 +00001365//===----------------------------------------------------------------------===//
1366// Constant Folding for Calls
1367//
John Criswell970af112005-10-27 16:00:10 +00001368
Andrew Kaylor647025f2017-06-09 23:18:11 +00001369bool llvm::canConstantFoldCallTo(ImmutableCallSite CS, const Function *F) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001370 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00001371 return false;
John Criswell970af112005-10-27 16:00:10 +00001372 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001373 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001374 case Intrinsic::minnum:
1375 case Intrinsic::maxnum:
Thomas Livelyfa54e562018-10-19 18:15:32 +00001376 case Intrinsic::minimum:
1377 case Intrinsic::maximum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001378 case Intrinsic::log:
1379 case Intrinsic::log2:
1380 case Intrinsic::log10:
1381 case Intrinsic::exp:
1382 case Intrinsic::exp2:
1383 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001384 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001385 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001386 case Intrinsic::sin:
1387 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001388 case Intrinsic::trunc:
1389 case Intrinsic::rint:
1390 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001391 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001392 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001393 case Intrinsic::bswap:
1394 case Intrinsic::ctpop:
1395 case Intrinsic::ctlz:
1396 case Intrinsic::cttz:
Sanjay Patel411b8602018-08-17 13:23:44 +00001397 case Intrinsic::fshl:
1398 case Intrinsic::fshr:
Matt Arsenault83778582014-03-05 00:02:00 +00001399 case Intrinsic::fma:
1400 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001401 case Intrinsic::copysign:
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001402 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001403 case Intrinsic::strip_invariant_group:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001404 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001405 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001406 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001407 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001408 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001409 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001410 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001411 case Intrinsic::umul_with_overflow:
Sanjay Patelefc3d1d2018-11-20 17:05:55 +00001412 case Intrinsic::sadd_sat:
1413 case Intrinsic::uadd_sat:
1414 case Intrinsic::ssub_sat:
1415 case Intrinsic::usub_sat:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001416 case Intrinsic::convert_from_fp16:
1417 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001418 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001419 case Intrinsic::x86_sse_cvtss2si:
1420 case Intrinsic::x86_sse_cvtss2si64:
1421 case Intrinsic::x86_sse_cvttss2si:
1422 case Intrinsic::x86_sse_cvttss2si64:
1423 case Intrinsic::x86_sse2_cvtsd2si:
1424 case Intrinsic::x86_sse2_cvtsd2si64:
1425 case Intrinsic::x86_sse2_cvttsd2si:
1426 case Intrinsic::x86_sse2_cvttsd2si64:
Craig Topper484b3422018-08-12 22:09:54 +00001427 case Intrinsic::x86_avx512_vcvtss2si32:
1428 case Intrinsic::x86_avx512_vcvtss2si64:
1429 case Intrinsic::x86_avx512_cvttss2si:
1430 case Intrinsic::x86_avx512_cvttss2si64:
1431 case Intrinsic::x86_avx512_vcvtsd2si32:
1432 case Intrinsic::x86_avx512_vcvtsd2si64:
1433 case Intrinsic::x86_avx512_cvttsd2si:
1434 case Intrinsic::x86_avx512_cvttsd2si64:
1435 case Intrinsic::x86_avx512_vcvtss2usi32:
1436 case Intrinsic::x86_avx512_vcvtss2usi64:
1437 case Intrinsic::x86_avx512_cvttss2usi:
1438 case Intrinsic::x86_avx512_cvttss2usi64:
1439 case Intrinsic::x86_avx512_vcvtsd2usi32:
1440 case Intrinsic::x86_avx512_vcvtsd2usi64:
1441 case Intrinsic::x86_avx512_cvttsd2usi:
1442 case Intrinsic::x86_avx512_cvttsd2usi64:
James Y Knight72f76bf2018-11-07 15:24:12 +00001443 case Intrinsic::is_constant:
John Criswell970af112005-10-27 16:00:10 +00001444 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001445 default:
1446 return false;
Craig Topper492db482017-04-07 21:36:32 +00001447 case Intrinsic::not_intrinsic: break;
John Criswell970af112005-10-27 16:00:10 +00001448 }
1449
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001450 if (!F->hasName())
1451 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001452 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001453
Chris Lattner785f9982007-08-08 06:55:43 +00001454 // In these cases, the check of the length is required. We don't want to
1455 // return true for a name like "cos\0blah" which strcmp would return equal to
1456 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001457 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001458 default:
1459 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001460 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001461 return Name == "acos" || Name == "asin" || Name == "atan" ||
1462 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1463 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001464 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001465 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1466 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001467 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001468 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001469 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001470 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1471 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001472 case 'l':
Xin Tongc063c3f2017-10-01 00:09:53 +00001473 return Name == "log" || Name == "log10" || Name == "logf" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001474 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001475 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001476 return Name == "pow" || Name == "powf";
Bryant Wongb5e03b62016-12-26 14:29:29 +00001477 case 'r':
1478 return Name == "round" || Name == "roundf";
Chris Lattner785f9982007-08-08 06:55:43 +00001479 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001480 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001481 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001482 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001483 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001484 case '_':
1485
1486 // Check for various function names that get used for the math functions
1487 // when the header files are preprocessed with the macro
1488 // __FINITE_MATH_ONLY__ enabled.
1489 // The '12' here is the length of the shortest name that can match.
1490 // We need to check the size before looking at Name[1] and Name[2]
1491 // so we may as well check a limit that will eliminate mismatches.
1492 if (Name.size() < 12 || Name[1] != '_')
1493 return false;
1494 switch (Name[2]) {
1495 default:
1496 return false;
1497 case 'a':
1498 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1499 Name == "__asin_finite" || Name == "__asinf_finite" ||
1500 Name == "__atan2_finite" || Name == "__atan2f_finite";
1501 case 'c':
1502 return Name == "__cosh_finite" || Name == "__coshf_finite";
1503 case 'e':
1504 return Name == "__exp_finite" || Name == "__expf_finite" ||
1505 Name == "__exp2_finite" || Name == "__exp2f_finite";
1506 case 'l':
1507 return Name == "__log_finite" || Name == "__logf_finite" ||
1508 Name == "__log10_finite" || Name == "__log10f_finite";
1509 case 'p':
1510 return Name == "__pow_finite" || Name == "__powf_finite";
1511 case 's':
1512 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1513 }
John Criswell970af112005-10-27 16:00:10 +00001514 }
1515}
1516
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001517namespace {
1518
1519Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001520 if (Ty->isHalfTy()) {
1521 APFloat APF(V);
1522 bool unused;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001523 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001524 return ConstantFP::get(Ty->getContext(), APF);
1525 }
Chris Lattner351534f2009-10-05 05:06:24 +00001526 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001527 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001528 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001529 return ConstantFP::get(Ty->getContext(), APFloat(V));
Xin Tongc063c3f2017-10-01 00:09:53 +00001530 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001531}
1532
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001533/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001534inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001535#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001536 feclearexcept(FE_ALL_EXCEPT);
1537#endif
1538 errno = 0;
1539}
1540
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001541/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001542inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001543 int errno_val = errno;
1544 if (errno_val == ERANGE || errno_val == EDOM)
1545 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001546#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001547 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1548 return true;
1549#endif
1550 return false;
1551}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001552
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001553Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001554 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001555 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001556 if (llvm_fenv_testexcept()) {
1557 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001558 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001559 }
1560
1561 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001562}
1563
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001564Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1565 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001566 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001567 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001568 if (llvm_fenv_testexcept()) {
1569 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001570 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001571 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001572
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001573 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001574}
1575
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001576/// Attempt to fold an SSE floating point to integer conversion of a constant
1577/// floating point. If roundTowardZero is false, the default IEEE rounding is
1578/// used (toward nearest, ties to even). This matches the behavior of the
1579/// non-truncating SSE instructions in the default rounding mode. The desired
1580/// integer type Ty is used to select how many bits are available for the
1581/// result. Returns null if the conversion cannot be performed, otherwise
1582/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001583Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
Craig Topper484b3422018-08-12 22:09:54 +00001584 Type *Ty, bool IsSigned) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001585 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001586 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001587 assert(ResultWidth <= 64 &&
1588 "Can only constant fold conversions to 64 and 32 bit ints");
1589
1590 uint64_t UIntVal;
1591 bool isExact = false;
1592 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1593 : APFloat::rmNearestTiesToEven;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001594 APFloat::opStatus status =
1595 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
Craig Topper484b3422018-08-12 22:09:54 +00001596 IsSigned, mode, &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001597 if (status != APFloat::opOK &&
1598 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001599 return nullptr;
Craig Topper484b3422018-08-12 22:09:54 +00001600 return ConstantInt::get(Ty, UIntVal, IsSigned);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001601}
1602
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001603double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001604 Type *Ty = Op->getType();
1605
1606 if (Ty->isFloatTy())
1607 return Op->getValueAPF().convertToFloat();
1608
1609 if (Ty->isDoubleTy())
1610 return Op->getValueAPF().convertToDouble();
1611
1612 bool unused;
1613 APFloat APF = Op->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001614 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001615 return APF.convertToDouble();
1616}
1617
James Y Knight72f76bf2018-11-07 15:24:12 +00001618static bool isManifestConstant(const Constant *c) {
1619 if (isa<ConstantData>(c)) {
1620 return true;
1621 } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1622 for (const Value *subc : c->operand_values()) {
1623 if (!isManifestConstant(cast<Constant>(subc)))
1624 return false;
1625 }
1626 return true;
1627 }
1628 return false;
1629}
1630
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00001631static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1632 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1633 C = &CI->getValue();
1634 return true;
1635 }
1636 if (isa<UndefValue>(Op)) {
1637 C = nullptr;
1638 return true;
1639 }
1640 return false;
1641}
1642
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001643Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1644 ArrayRef<Constant *> Operands,
Manoj Gupta77eeac32018-07-09 22:27:23 +00001645 const TargetLibraryInfo *TLI,
1646 ImmutableCallSite CS) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001647 if (Operands.size() == 1) {
James Y Knight72f76bf2018-11-07 15:24:12 +00001648 if (IntrinsicID == Intrinsic::is_constant) {
1649 // We know we have a "Constant" argument. But we want to only
1650 // return true for manifest constants, not those that depend on
1651 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1652 if (isManifestConstant(Operands[0]))
1653 return ConstantInt::getTrue(Ty->getContext());
1654 return nullptr;
1655 }
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001656 if (isa<UndefValue>(Operands[0])) {
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00001657 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1658 // ctpop() is between 0 and bitwidth, pick 0 for undef.
1659 if (IntrinsicID == Intrinsic::cos ||
1660 IntrinsicID == Intrinsic::ctpop)
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001661 return Constant::getNullValue(Ty);
Craig Topperd470d732017-06-04 08:21:53 +00001662 if (IntrinsicID == Intrinsic::bswap ||
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001663 IntrinsicID == Intrinsic::bitreverse ||
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001664 IntrinsicID == Intrinsic::launder_invariant_group ||
1665 IntrinsicID == Intrinsic::strip_invariant_group)
Craig Topperd470d732017-06-04 08:21:53 +00001666 return Operands[0];
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001667 }
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001668
Manoj Guptaf9f50f62018-07-23 21:20:00 +00001669 if (isa<ConstantPointerNull>(Operands[0])) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001670 // launder(null) == null == strip(null) iff in addrspace 0
1671 if (IntrinsicID == Intrinsic::launder_invariant_group ||
Manoj Guptaf9f50f62018-07-23 21:20:00 +00001672 IntrinsicID == Intrinsic::strip_invariant_group) {
1673 // If instruction is not yet put in a basic block (e.g. when cloning
1674 // a function during inlining), CS caller may not be available.
1675 // So check CS's BB first before querying CS.getCaller.
1676 const Function *Caller = CS.getParent() ? CS.getCaller() : nullptr;
1677 if (Caller &&
1678 !NullPointerIsDefined(
1679 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1680 return Operands[0];
1681 }
1682 return nullptr;
1683 }
Piotr Padlewskia26a08c2018-05-18 23:52:57 +00001684 }
1685
David Majnemer90a97042016-07-13 04:22:12 +00001686 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001687 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001688 APFloat Val(Op->getValueAPF());
1689
1690 bool lost = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001691 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001692
Benjamin Kramer061d1472014-03-05 19:41:48 +00001693 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001694 }
1695
Xin Tongc063c3f2017-10-01 00:09:53 +00001696 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001697 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001698
Karthik Bhatb67688a2014-03-07 04:36:21 +00001699 if (IntrinsicID == Intrinsic::round) {
1700 APFloat V = Op->getValueAPF();
1701 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1702 return ConstantFP::get(Ty->getContext(), V);
1703 }
1704
Karthik Bhatd818e382015-07-21 08:52:23 +00001705 if (IntrinsicID == Intrinsic::floor) {
1706 APFloat V = Op->getValueAPF();
1707 V.roundToIntegral(APFloat::rmTowardNegative);
1708 return ConstantFP::get(Ty->getContext(), V);
1709 }
1710
1711 if (IntrinsicID == Intrinsic::ceil) {
1712 APFloat V = Op->getValueAPF();
1713 V.roundToIntegral(APFloat::rmTowardPositive);
1714 return ConstantFP::get(Ty->getContext(), V);
1715 }
1716
1717 if (IntrinsicID == Intrinsic::trunc) {
1718 APFloat V = Op->getValueAPF();
1719 V.roundToIntegral(APFloat::rmTowardZero);
1720 return ConstantFP::get(Ty->getContext(), V);
1721 }
1722
1723 if (IntrinsicID == Intrinsic::rint) {
1724 APFloat V = Op->getValueAPF();
1725 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1726 return ConstantFP::get(Ty->getContext(), V);
1727 }
1728
1729 if (IntrinsicID == Intrinsic::nearbyint) {
1730 APFloat V = Op->getValueAPF();
1731 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1732 return ConstantFP::get(Ty->getContext(), V);
1733 }
1734
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001735 /// We only fold functions with finite arguments. Folding NaN and inf is
1736 /// likely to be aborted with an exception anyway, and some host libms
1737 /// have known errors raising exceptions.
1738 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001739 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001740
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001741 /// Currently APFloat versions of these functions do not exist, so we use
1742 /// the host native double versions. Float versions are not called
1743 /// directly but for all these it is true (float)(f((double)arg)) ==
1744 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001745 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001746
Benjamin Kramer061d1472014-03-05 19:41:48 +00001747 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001748 default: break;
1749 case Intrinsic::fabs:
1750 return ConstantFoldFP(fabs, V, Ty);
1751 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001752 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001753 case Intrinsic::log:
1754 return ConstantFoldFP(log, V, Ty);
1755 case Intrinsic::log10:
1756 return ConstantFoldFP(log10, V, Ty);
1757 case Intrinsic::exp:
1758 return ConstantFoldFP(exp, V, Ty);
1759 case Intrinsic::exp2:
1760 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001761 case Intrinsic::sin:
1762 return ConstantFoldFP(sin, V, Ty);
1763 case Intrinsic::cos:
1764 return ConstantFoldFP(cos, V, Ty);
Justin Lebar8b18a342017-01-21 00:59:57 +00001765 case Intrinsic::sqrt:
1766 return ConstantFoldFP(sqrt, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001767 }
1768
Benjamin Kramer061d1472014-03-05 19:41:48 +00001769 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001770 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001771
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001772 char NameKeyChar = Name[0];
1773 if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_')
1774 NameKeyChar = Name[2];
1775
1776 switch (NameKeyChar) {
Chris Lattner785f9982007-08-08 06:55:43 +00001777 case 'a':
David L. Jonesd21529f2017-01-23 23:16:46 +00001778 if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001779 (Name == "acosf" && TLI->has(LibFunc_acosf)) ||
1780 (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) ||
1781 (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001782 return ConstantFoldFP(acos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001783 else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001784 (Name == "asinf" && TLI->has(LibFunc_asinf)) ||
1785 (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) ||
1786 (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001787 return ConstantFoldFP(asin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001788 else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1789 (Name == "atanf" && TLI->has(LibFunc_atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001790 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001791 break;
1792 case 'c':
David L. Jonesd21529f2017-01-23 23:16:46 +00001793 if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1794 (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001795 return ConstantFoldFP(ceil, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001796 else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1797 (Name == "cosf" && TLI->has(LibFunc_cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001798 return ConstantFoldFP(cos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001799 else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001800 (Name == "coshf" && TLI->has(LibFunc_coshf)) ||
1801 (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) ||
1802 (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001803 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001804 break;
1805 case 'e':
David L. Jonesd21529f2017-01-23 23:16:46 +00001806 if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001807 (Name == "expf" && TLI->has(LibFunc_expf)) ||
1808 (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) ||
1809 (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001810 return ConstantFoldFP(exp, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001811 if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001812 (Name == "exp2f" && TLI->has(LibFunc_exp2f)) ||
1813 (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) ||
1814 (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite)))
Chris Lattner713d5232011-05-22 22:22:35 +00001815 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1816 // C99 library.
1817 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001818 break;
1819 case 'f':
David L. Jonesd21529f2017-01-23 23:16:46 +00001820 if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1821 (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001822 return ConstantFoldFP(fabs, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001823 else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1824 (Name == "floorf" && TLI->has(LibFunc_floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001825 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001826 break;
1827 case 'l':
David L. Jonesd21529f2017-01-23 23:16:46 +00001828 if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001829 (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) ||
1830 (Name == "__log_finite" && V > 0 &&
1831 TLI->has(LibFunc_log_finite)) ||
1832 (Name == "__logf_finite" && V > 0 &&
1833 TLI->has(LibFunc_logf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001834 return ConstantFoldFP(log, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001835 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001836 (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) ||
1837 (Name == "__log10_finite" && V > 0 &&
1838 TLI->has(LibFunc_log10_finite)) ||
1839 (Name == "__log10f_finite" && V > 0 &&
1840 TLI->has(LibFunc_log10f_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001841 return ConstantFoldFP(log10, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001842 break;
Bryant Wongb5e03b62016-12-26 14:29:29 +00001843 case 'r':
David L. Jonesd21529f2017-01-23 23:16:46 +00001844 if ((Name == "round" && TLI->has(LibFunc_round)) ||
1845 (Name == "roundf" && TLI->has(LibFunc_roundf)))
Bryant Wongb5e03b62016-12-26 14:29:29 +00001846 return ConstantFoldFP(round, V, Ty);
Galina Kistanovac2b642d2017-05-31 20:25:13 +00001847 break;
Chris Lattner785f9982007-08-08 06:55:43 +00001848 case 's':
David L. Jonesd21529f2017-01-23 23:16:46 +00001849 if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1850 (Name == "sinf" && TLI->has(LibFunc_sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001851 return ConstantFoldFP(sin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001852 else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001853 (Name == "sinhf" && TLI->has(LibFunc_sinhf)) ||
1854 (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) ||
1855 (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001856 return ConstantFoldFP(sinh, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001857 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1858 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001859 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001860 break;
1861 case 't':
David L. Jonesd21529f2017-01-23 23:16:46 +00001862 if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1863 (Name == "tanf" && TLI->has(LibFunc_tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001864 return ConstantFoldFP(tan, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001865 else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1866 (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001867 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001868 break;
1869 default:
1870 break;
John Criswell970af112005-10-27 16:00:10 +00001871 }
Craig Topper9f008862014-04-15 04:59:12 +00001872 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001873 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001874
David Majnemer90a97042016-07-13 04:22:12 +00001875 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001876 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001877 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001878 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001879 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001880 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001881 case Intrinsic::bitreverse:
1882 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001883 case Intrinsic::convert_from_fp16: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001884 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001885
1886 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001887 APFloat::opStatus status = Val.convert(
1888 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001889
1890 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001891 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001892 assert(status == APFloat::opOK && !lost &&
1893 "Precision lost during fp16 constfolding");
1894
Benjamin Kramer061d1472014-03-05 19:41:48 +00001895 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001896 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001897 default:
Craig Topper9f008862014-04-15 04:59:12 +00001898 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001899 }
John Criswell970af112005-10-27 16:00:10 +00001900 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001901
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001902 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001903 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001904 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001905 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001906 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001907 default: break;
1908 case Intrinsic::x86_sse_cvtss2si:
1909 case Intrinsic::x86_sse_cvtss2si64:
1910 case Intrinsic::x86_sse2_cvtsd2si:
1911 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001912 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001913 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1914 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
Craig Topper484b3422018-08-12 22:09:54 +00001915 /*roundTowardZero=*/false, Ty,
1916 /*IsSigned*/true);
Craig Topper0dd29e22017-06-04 08:21:51 +00001917 break;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001918 case Intrinsic::x86_sse_cvttss2si:
1919 case Intrinsic::x86_sse_cvttss2si64:
1920 case Intrinsic::x86_sse2_cvttsd2si:
1921 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001922 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001923 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1924 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
Craig Topper484b3422018-08-12 22:09:54 +00001925 /*roundTowardZero=*/true, Ty,
1926 /*IsSigned*/true);
Craig Topper0dd29e22017-06-04 08:21:51 +00001927 break;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001928 }
1929 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001930
Craig Topper9f008862014-04-15 04:59:12 +00001931 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001932 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001933
Jay Foadf4b14a22011-07-19 13:32:40 +00001934 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001935 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001936 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001937 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001938 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001939
David Majnemer90a97042016-07-13 04:22:12 +00001940 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001941 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001942 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001943
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001944 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001945 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001946 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1947 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001948 if (IntrinsicID == Intrinsic::copysign) {
1949 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001950 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001951 V1.copySign(V2);
1952 return ConstantFP::get(Ty->getContext(), V1);
1953 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001954
1955 if (IntrinsicID == Intrinsic::minnum) {
1956 const APFloat &C1 = Op1->getValueAPF();
1957 const APFloat &C2 = Op2->getValueAPF();
1958 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1959 }
1960
1961 if (IntrinsicID == Intrinsic::maxnum) {
1962 const APFloat &C1 = Op1->getValueAPF();
1963 const APFloat &C2 = Op2->getValueAPF();
1964 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1965 }
1966
Thomas Livelyfa54e562018-10-19 18:15:32 +00001967 if (IntrinsicID == Intrinsic::minimum) {
1968 const APFloat &C1 = Op1->getValueAPF();
1969 const APFloat &C2 = Op2->getValueAPF();
1970 return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
1971 }
1972
1973 if (IntrinsicID == Intrinsic::maximum) {
1974 const APFloat &C1 = Op1->getValueAPF();
1975 const APFloat &C2 = Op2->getValueAPF();
1976 return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
1977 }
1978
Chad Rosier0155a632011-12-03 00:00:03 +00001979 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001980 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00001981 if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001982 (Name == "powf" && TLI->has(LibFunc_powf)) ||
1983 (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) ||
1984 (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001985 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001986 if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1987 (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001988 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001990 (Name == "atan2f" && TLI->has(LibFunc_atan2f)) ||
1991 (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) ||
1992 (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001993 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001994 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001995 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1996 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001997 APFloat((float)std::pow((float)Op1V,
1998 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001999 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2000 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00002001 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00002002 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00002003 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2004 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00002005 APFloat((double)std::pow((double)Op1V,
2006 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00002007 }
Craig Topper9f008862014-04-15 04:59:12 +00002008 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002009 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00002010
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002011 if (Operands[0]->getType()->isIntegerTy() &&
2012 Operands[1]->getType()->isIntegerTy()) {
2013 const APInt *C0, *C1;
2014 if (!getConstIntOrUndef(Operands[0], C0) ||
2015 !getConstIntOrUndef(Operands[1], C1))
2016 return nullptr;
2017
2018 switch (IntrinsicID) {
2019 default: break;
2020 case Intrinsic::smul_with_overflow:
2021 case Intrinsic::umul_with_overflow:
2022 // Even if both operands are undef, we cannot fold muls to undef
2023 // in the general case. For example, on i2 there are no inputs
2024 // that would produce { i2 -1, i1 true } as the result.
2025 if (!C0 || !C1)
2026 return Constant::getNullValue(Ty);
2027 LLVM_FALLTHROUGH;
2028 case Intrinsic::sadd_with_overflow:
2029 case Intrinsic::uadd_with_overflow:
2030 case Intrinsic::ssub_with_overflow:
2031 case Intrinsic::usub_with_overflow: {
2032 if (!C0 || !C1)
2033 return UndefValue::get(Ty);
2034
2035 APInt Res;
2036 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002037 switch (IntrinsicID) {
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002038 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00002039 case Intrinsic::sadd_with_overflow:
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002040 Res = C0->sadd_ov(*C1, Overflow);
2041 break;
Chris Lattner698661c2010-10-14 00:05:07 +00002042 case Intrinsic::uadd_with_overflow:
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002043 Res = C0->uadd_ov(*C1, Overflow);
2044 break;
Chris Lattner698661c2010-10-14 00:05:07 +00002045 case Intrinsic::ssub_with_overflow:
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002046 Res = C0->ssub_ov(*C1, Overflow);
2047 break;
Chris Lattner698661c2010-10-14 00:05:07 +00002048 case Intrinsic::usub_with_overflow:
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002049 Res = C0->usub_ov(*C1, Overflow);
2050 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002051 case Intrinsic::smul_with_overflow:
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002052 Res = C0->smul_ov(*C1, Overflow);
2053 break;
2054 case Intrinsic::umul_with_overflow:
2055 Res = C0->umul_ov(*C1, Overflow);
2056 break;
Chris Lattner59d93982009-10-05 05:26:04 +00002057 }
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002058 Constant *Ops[] = {
2059 ConstantInt::get(Ty->getContext(), Res),
2060 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2061 };
2062 return ConstantStruct::get(cast<StructType>(Ty), Ops);
2063 }
2064 case Intrinsic::uadd_sat:
2065 case Intrinsic::sadd_sat:
2066 if (!C0 && !C1)
2067 return UndefValue::get(Ty);
2068 if (!C0 || !C1)
2069 return Constant::getAllOnesValue(Ty);
2070 if (IntrinsicID == Intrinsic::uadd_sat)
2071 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2072 else
2073 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2074 case Intrinsic::usub_sat:
2075 case Intrinsic::ssub_sat:
2076 if (!C0 && !C1)
2077 return UndefValue::get(Ty);
2078 if (!C0 || !C1)
2079 return Constant::getNullValue(Ty);
2080 if (IntrinsicID == Intrinsic::usub_sat)
2081 return ConstantInt::get(Ty, C0->usub_sat(*C1));
2082 else
2083 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2084 case Intrinsic::cttz:
2085 case Intrinsic::ctlz:
2086 assert(C1 && "Must be constant int");
2087
2088 // cttz(0, 1) and ctlz(0, 1) are undef.
2089 if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2090 return UndefValue::get(Ty);
2091 if (!C0)
2092 return Constant::getNullValue(Ty);
2093 if (IntrinsicID == Intrinsic::cttz)
2094 return ConstantInt::get(Ty, C0->countTrailingZeros());
2095 else
2096 return ConstantInt::get(Ty, C0->countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00002097 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00002098
Craig Topper9f008862014-04-15 04:59:12 +00002099 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00002100 }
Craig Topper484b3422018-08-12 22:09:54 +00002101
2102 // Support ConstantVector in case we have an Undef in the top.
2103 if ((isa<ConstantVector>(Operands[0]) ||
2104 isa<ConstantDataVector>(Operands[0])) &&
2105 // Check for default rounding mode.
2106 // FIXME: Support other rounding modes?
2107 isa<ConstantInt>(Operands[1]) &&
2108 cast<ConstantInt>(Operands[1])->getValue() == 4) {
2109 auto *Op = cast<Constant>(Operands[0]);
2110 switch (IntrinsicID) {
2111 default: break;
2112 case Intrinsic::x86_avx512_vcvtss2si32:
2113 case Intrinsic::x86_avx512_vcvtss2si64:
2114 case Intrinsic::x86_avx512_vcvtsd2si32:
2115 case Intrinsic::x86_avx512_vcvtsd2si64:
2116 if (ConstantFP *FPOp =
2117 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2118 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2119 /*roundTowardZero=*/false, Ty,
2120 /*IsSigned*/true);
2121 break;
2122 case Intrinsic::x86_avx512_vcvtss2usi32:
2123 case Intrinsic::x86_avx512_vcvtss2usi64:
2124 case Intrinsic::x86_avx512_vcvtsd2usi32:
2125 case Intrinsic::x86_avx512_vcvtsd2usi64:
2126 if (ConstantFP *FPOp =
2127 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2128 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2129 /*roundTowardZero=*/false, Ty,
2130 /*IsSigned*/false);
2131 break;
2132 case Intrinsic::x86_avx512_cvttss2si:
2133 case Intrinsic::x86_avx512_cvttss2si64:
2134 case Intrinsic::x86_avx512_cvttsd2si:
2135 case Intrinsic::x86_avx512_cvttsd2si64:
2136 if (ConstantFP *FPOp =
2137 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2138 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2139 /*roundTowardZero=*/true, Ty,
2140 /*IsSigned*/true);
2141 break;
2142 case Intrinsic::x86_avx512_cvttss2usi:
2143 case Intrinsic::x86_avx512_cvttss2usi64:
2144 case Intrinsic::x86_avx512_cvttsd2usi:
2145 case Intrinsic::x86_avx512_cvttsd2usi64:
2146 if (ConstantFP *FPOp =
2147 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2148 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2149 /*roundTowardZero=*/true, Ty,
2150 /*IsSigned*/false);
2151 break;
2152 }
2153 }
Craig Topper9f008862014-04-15 04:59:12 +00002154 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002155 }
Matt Arsenault83778582014-03-05 00:02:00 +00002156
2157 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00002158 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00002159
David Majnemer90a97042016-07-13 04:22:12 +00002160 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2161 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2162 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002163 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00002164 default: break;
2165 case Intrinsic::fma:
2166 case Intrinsic::fmuladd: {
2167 APFloat V = Op1->getValueAPF();
2168 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
2169 Op3->getValueAPF(),
2170 APFloat::rmNearestTiesToEven);
2171 if (s != APFloat::opInvalidOp)
2172 return ConstantFP::get(Ty->getContext(), V);
2173
Craig Topper9f008862014-04-15 04:59:12 +00002174 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00002175 }
2176 }
2177 }
2178 }
2179 }
2180
Sanjay Patel411b8602018-08-17 13:23:44 +00002181 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002182 const APInt *C0, *C1, *C2;
2183 if (!getConstIntOrUndef(Operands[0], C0) ||
2184 !getConstIntOrUndef(Operands[1], C1) ||
2185 !getConstIntOrUndef(Operands[2], C2))
Sanjay Patel411b8602018-08-17 13:23:44 +00002186 return nullptr;
2187
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002188 bool IsRight = IntrinsicID == Intrinsic::fshr;
2189 if (!C2)
2190 return Operands[IsRight ? 1 : 0];
2191 if (!C0 && !C1)
2192 return UndefValue::get(Ty);
2193
Sanjay Patel411b8602018-08-17 13:23:44 +00002194 // The shift amount is interpreted as modulo the bitwidth. If the shift
2195 // amount is effectively 0, avoid UB due to oversized inverse shift below.
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002196 unsigned BitWidth = C2->getBitWidth();
2197 unsigned ShAmt = C2->urem(BitWidth);
Sanjay Patel411b8602018-08-17 13:23:44 +00002198 if (!ShAmt)
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002199 return Operands[IsRight ? 1 : 0];
Sanjay Patel411b8602018-08-17 13:23:44 +00002200
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002201 // (C0 << ShlAmt) | (C1 >> LshrAmt)
Sanjay Patel411b8602018-08-17 13:23:44 +00002202 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2203 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
Nikita Popov9f6e9cf2019-01-11 21:18:00 +00002204 if (!C0)
2205 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2206 if (!C1)
2207 return ConstantInt::get(Ty, C0->shl(ShlAmt));
2208 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
Sanjay Patel411b8602018-08-17 13:23:44 +00002209 }
2210
Craig Topper9f008862014-04-15 04:59:12 +00002211 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00002212}
Benjamin Kramer061d1472014-03-05 19:41:48 +00002213
Eugene Zelenko35623fb2016-03-28 17:40:08 +00002214Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
2215 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer7f781ab2016-07-14 00:29:50 +00002216 const DataLayout &DL,
Manoj Gupta77eeac32018-07-09 22:27:23 +00002217 const TargetLibraryInfo *TLI,
2218 ImmutableCallSite CS) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00002219 SmallVector<Constant *, 4> Result(VTy->getNumElements());
2220 SmallVector<Constant *, 4> Lane(Operands.size());
2221 Type *Ty = VTy->getElementType();
2222
David Majnemer7f781ab2016-07-14 00:29:50 +00002223 if (IntrinsicID == Intrinsic::masked_load) {
2224 auto *SrcPtr = Operands[0];
2225 auto *Mask = Operands[2];
2226 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00002227
David Majnemer7f781ab2016-07-14 00:29:50 +00002228 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00002229
2230 SmallVector<Constant *, 32> NewElements;
2231 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00002232 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00002233 if (!MaskElt)
2234 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00002235 auto *PassthruElt = Passthru->getAggregateElement(I);
2236 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2237 if (isa<UndefValue>(MaskElt)) {
2238 if (PassthruElt)
2239 NewElements.push_back(PassthruElt);
2240 else if (VecElt)
2241 NewElements.push_back(VecElt);
2242 else
2243 return nullptr;
2244 }
2245 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002246 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002247 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002248 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002249 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002250 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002251 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002252 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002253 } else {
2254 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002255 }
2256 }
David Majnemer17a95aa2016-07-14 06:58:37 +00002257 if (NewElements.size() != VTy->getNumElements())
2258 return nullptr;
2259 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00002260 }
2261
Benjamin Kramer061d1472014-03-05 19:41:48 +00002262 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2263 // Gather a column of constants.
2264 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
Craig Topper7c553ed2017-06-03 18:50:29 +00002265 // These intrinsics use a scalar type for their second argument.
2266 if (J == 1 &&
Craig Topperfe9ad822017-06-04 07:30:28 +00002267 (IntrinsicID == Intrinsic::cttz || IntrinsicID == Intrinsic::ctlz ||
2268 IntrinsicID == Intrinsic::powi)) {
Craig Topper7c553ed2017-06-03 18:50:29 +00002269 Lane[J] = Operands[J];
2270 continue;
2271 }
2272
Benjamin Kramer061d1472014-03-05 19:41:48 +00002273 Constant *Agg = Operands[J]->getAggregateElement(I);
2274 if (!Agg)
2275 return nullptr;
2276
2277 Lane[J] = Agg;
2278 }
2279
2280 // Use the regular scalar folding to simplify this column.
Manoj Gupta77eeac32018-07-09 22:27:23 +00002281 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, CS);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002282 if (!Folded)
2283 return nullptr;
2284 Result[I] = Folded;
2285 }
2286
2287 return ConstantVector::get(Result);
2288}
2289
Eugene Zelenko35623fb2016-03-28 17:40:08 +00002290} // end anonymous namespace
2291
Benjamin Kramer061d1472014-03-05 19:41:48 +00002292Constant *
Andrew Kaylor647025f2017-06-09 23:18:11 +00002293llvm::ConstantFoldCall(ImmutableCallSite CS, Function *F,
2294 ArrayRef<Constant *> Operands,
Benjamin Kramer061d1472014-03-05 19:41:48 +00002295 const TargetLibraryInfo *TLI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002296 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002297 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002298 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00002299 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002300 StringRef Name = F->getName();
2301
2302 Type *Ty = F->getReturnType();
2303
David Majnemer90a97042016-07-13 04:22:12 +00002304 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00002305 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
Manoj Gupta77eeac32018-07-09 22:27:23 +00002306 F->getParent()->getDataLayout(), TLI, CS);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002307
Manoj Gupta77eeac32018-07-09 22:27:23 +00002308 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI, CS);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002309}
Eli Friedmanb6befc32016-11-02 20:48:11 +00002310
2311bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2312 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2313 // (and to some extent ConstantFoldScalarCall).
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002314 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002315 return false;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002316 Function *F = CS.getCalledFunction();
2317 if (!F)
2318 return false;
2319
David L. Jonesd21529f2017-01-23 23:16:46 +00002320 LibFunc Func;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002321 if (!TLI || !TLI->getLibFunc(*F, Func))
2322 return false;
2323
2324 if (CS.getNumArgOperands() == 1) {
2325 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2326 const APFloat &Op = OpC->getValueAPF();
2327 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002328 case LibFunc_logl:
2329 case LibFunc_log:
2330 case LibFunc_logf:
2331 case LibFunc_log2l:
2332 case LibFunc_log2:
2333 case LibFunc_log2f:
2334 case LibFunc_log10l:
2335 case LibFunc_log10:
2336 case LibFunc_log10f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002337 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2338
David L. Jonesd21529f2017-01-23 23:16:46 +00002339 case LibFunc_expl:
2340 case LibFunc_exp:
2341 case LibFunc_expf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002342 // FIXME: These boundaries are slightly conservative.
2343 if (OpC->getType()->isDoubleTy())
2344 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2345 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2346 if (OpC->getType()->isFloatTy())
2347 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2348 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2349 break;
2350
David L. Jonesd21529f2017-01-23 23:16:46 +00002351 case LibFunc_exp2l:
2352 case LibFunc_exp2:
2353 case LibFunc_exp2f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002354 // FIXME: These boundaries are slightly conservative.
2355 if (OpC->getType()->isDoubleTy())
2356 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2357 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2358 if (OpC->getType()->isFloatTy())
2359 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2360 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2361 break;
2362
David L. Jonesd21529f2017-01-23 23:16:46 +00002363 case LibFunc_sinl:
2364 case LibFunc_sin:
2365 case LibFunc_sinf:
2366 case LibFunc_cosl:
2367 case LibFunc_cos:
2368 case LibFunc_cosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002369 return !Op.isInfinity();
2370
David L. Jonesd21529f2017-01-23 23:16:46 +00002371 case LibFunc_tanl:
2372 case LibFunc_tan:
2373 case LibFunc_tanf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002374 // FIXME: Stop using the host math library.
2375 // FIXME: The computation isn't done in the right precision.
2376 Type *Ty = OpC->getType();
2377 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2378 double OpV = getValueAsDouble(OpC);
2379 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2380 }
2381 break;
2382 }
2383
David L. Jonesd21529f2017-01-23 23:16:46 +00002384 case LibFunc_asinl:
2385 case LibFunc_asin:
2386 case LibFunc_asinf:
2387 case LibFunc_acosl:
2388 case LibFunc_acos:
2389 case LibFunc_acosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002390 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2391 APFloat::cmpLessThan &&
2392 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2393 APFloat::cmpGreaterThan;
2394
David L. Jonesd21529f2017-01-23 23:16:46 +00002395 case LibFunc_sinh:
2396 case LibFunc_cosh:
2397 case LibFunc_sinhf:
2398 case LibFunc_coshf:
2399 case LibFunc_sinhl:
2400 case LibFunc_coshl:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002401 // FIXME: These boundaries are slightly conservative.
2402 if (OpC->getType()->isDoubleTy())
2403 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2404 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2405 if (OpC->getType()->isFloatTy())
2406 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2407 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2408 break;
2409
David L. Jonesd21529f2017-01-23 23:16:46 +00002410 case LibFunc_sqrtl:
2411 case LibFunc_sqrt:
2412 case LibFunc_sqrtf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002413 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2414
2415 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2416 // maybe others?
2417 default:
2418 break;
2419 }
2420 }
2421 }
2422
2423 if (CS.getNumArgOperands() == 2) {
2424 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2425 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2426 if (Op0C && Op1C) {
2427 const APFloat &Op0 = Op0C->getValueAPF();
2428 const APFloat &Op1 = Op1C->getValueAPF();
2429
2430 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002431 case LibFunc_powl:
2432 case LibFunc_pow:
2433 case LibFunc_powf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002434 // FIXME: Stop using the host math library.
2435 // FIXME: The computation isn't done in the right precision.
2436 Type *Ty = Op0C->getType();
2437 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2438 if (Ty == Op1C->getType()) {
2439 double Op0V = getValueAsDouble(Op0C);
2440 double Op1V = getValueAsDouble(Op1C);
2441 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2442 }
2443 }
2444 break;
2445 }
2446
David L. Jonesd21529f2017-01-23 23:16:46 +00002447 case LibFunc_fmodl:
2448 case LibFunc_fmod:
2449 case LibFunc_fmodf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002450 return Op0.isNaN() || Op1.isNaN() ||
2451 (!Op0.isInfinity() && !Op1.isZero());
2452
2453 default:
2454 break;
2455 }
2456 }
2457 }
2458
2459 return false;
2460}