blob: 8dc94219027ffd965d664ef7d8546b76803defd0 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswell970af112005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman91d598d2009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
Chandler Carruthef860a22013-01-02 09:10:48 +000012// Also, to supplement the basic IR ConstantExpr simplifications,
Dan Gohman91d598d2009-09-10 23:07:18 +000013// this file defines some additional folding routines that can make use of
Chandler Carruthef860a22013-01-02 09:10:48 +000014// DataLayout information. These functions cannot go in IR due to library
Dan Gohman91d598d2009-09-10 23:07:18 +000015// dependency issues.
John Criswell970af112005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000024#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000034#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000035#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLibraryInfo.h"
John Criswell970af112005-10-27 16:00:10 +000037#include <cerrno>
Jeff Cohencc08c832006-12-02 02:22:01 +000038#include <cmath>
Alp Tokerc817d6a2014-06-09 18:28:53 +000039
40#ifdef HAVE_FENV_H
41#include <fenv.h>
Alp Tokerc817d6a2014-06-09 18:28:53 +000042#endif
43
John Criswell970af112005-10-27 16:00:10 +000044using namespace llvm;
45
Chris Lattner44d68b92007-01-31 00:51:48 +000046//===----------------------------------------------------------------------===//
47// Constant Folding internal helper functions
48//===----------------------------------------------------------------------===//
49
NAKAMURA Takumidce89992012-11-05 00:11:11 +000050/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
Micah Villmowcdfe20b2012-10-08 16:38:25 +000051/// DataLayout. This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000052/// ConstantExpr if unfoldable.
Chris Lattner229907c2011-07-18 04:54:35 +000053static Constant *FoldBitCast(Constant *C, Type *DestTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000054 const DataLayout &TD) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000055 // Catch the obvious splat cases.
56 if (C->isNullValue() && !DestTy->isX86_MMXTy())
57 return Constant::getNullValue(DestTy);
58 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
59 return Constant::getAllOnesValue(DestTy);
60
Rafael Espindolabb893fe2012-01-27 23:33:07 +000061 // Handle a vector->integer cast.
62 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
Michael Ilsemana7b93c12013-02-26 22:51:07 +000063 VectorType *VTy = dyn_cast<VectorType>(C->getType());
Craig Topper9f008862014-04-15 04:59:12 +000064 if (!VTy)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000065 return ConstantExpr::getBitCast(C, DestTy);
66
Michael Ilsemana7b93c12013-02-26 22:51:07 +000067 unsigned NumSrcElts = VTy->getNumElements();
68 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000069
Rafael Espindolabb893fe2012-01-27 23:33:07 +000070 // If the vector is a vector of floating point, convert it to vector of int
71 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000072 if (SrcEltTy->isFloatingPointTy()) {
73 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000074 Type *SrcIVTy =
75 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000076 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000077 C = ConstantExpr::getBitCast(C, SrcIVTy);
78 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000079
Michael Ilsemana7b93c12013-02-26 22:51:07 +000080 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
Craig Topper9f008862014-04-15 04:59:12 +000081 if (!CDV)
Michael Ilsemana7b93c12013-02-26 22:51:07 +000082 return ConstantExpr::getBitCast(C, DestTy);
83
Rafael Espindolabb893fe2012-01-27 23:33:07 +000084 // Now that we know that the input value is a vector of integers, just shift
85 // and insert them into our result.
Chris Lattner8213c8a2012-02-06 21:56:39 +000086 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000087 APInt Result(IT->getBitWidth(), 0);
88 for (unsigned i = 0; i != NumSrcElts; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +000089 Result <<= BitShift;
90 if (TD.isLittleEndian())
91 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
92 else
93 Result |= CDV->getElementAsInteger(i);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000094 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000095
Rafael Espindolabb893fe2012-01-27 23:33:07 +000096 return ConstantInt::get(IT, Result);
97 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000098
Nadav Rotemad4a70a2011-08-20 14:02:29 +000099 // The code below only handles casts to vectors currently.
Chris Lattner229907c2011-07-18 04:54:35 +0000100 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000101 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000102 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000103
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000104 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
105 // vector so the code below can handle it uniformly.
106 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
107 Constant *Ops = C; // don't take the address of C!
Chris Lattner69229312011-02-15 00:14:00 +0000108 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000109 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000110
Chris Lattner9d051242009-10-25 06:08:26 +0000111 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000112 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000113 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000114
Chandler Carruthef860a22013-01-02 09:10:48 +0000115 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000116 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000117 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000118 if (NumDstElt == NumSrcElt)
119 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000120
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000121 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000122 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000123
124 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000125 // requires endianness information to do the right thing. For example,
126 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
127 // folds to (little endian):
128 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
129 // and to (big endian):
130 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000131
Chris Lattner9d051242009-10-25 06:08:26 +0000132 // First thing is first. We only want to think about integer here, so if
133 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000134 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000135 // Fold to an vector of integers with same size as our FP type.
136 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000137 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000138 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
139 // Recursively handle this integer conversion, if possible.
140 C = FoldBitCast(C, DestIVTy, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000141
Chandler Carruthef860a22013-01-02 09:10:48 +0000142 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000143 return ConstantExpr::getBitCast(C, DestTy);
144 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000145
Chris Lattner9d051242009-10-25 06:08:26 +0000146 // Okay, we know the destination is integer, if the input is FP, convert
147 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000148 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000149 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000150 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000151 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000152 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000153 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000154 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000155 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
156 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000157 return C;
158 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000159
Chris Lattner9d051242009-10-25 06:08:26 +0000160 // Now we know that the input and output vectors are both integer vectors
161 // of the same size, and that their #elements is not the same. Do the
162 // conversion here, which depends on whether the input or output has
163 // more elements.
164 bool isLittleEndian = TD.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000165
Chris Lattner9d051242009-10-25 06:08:26 +0000166 SmallVector<Constant*, 32> Result;
167 if (NumDstElt < NumSrcElt) {
168 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
169 Constant *Zero = Constant::getNullValue(DstEltTy);
170 unsigned Ratio = NumSrcElt/NumDstElt;
171 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
172 unsigned SrcElt = 0;
173 for (unsigned i = 0; i != NumDstElt; ++i) {
174 // Build each element of the result.
175 Constant *Elt = Zero;
176 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
177 for (unsigned j = 0; j != Ratio; ++j) {
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000178 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
Chris Lattner9d051242009-10-25 06:08:26 +0000179 if (!Src) // Reject constantexpr elements.
180 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000181
Chris Lattner9d051242009-10-25 06:08:26 +0000182 // Zero extend the element to the right size.
183 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000184
Chris Lattner9d051242009-10-25 06:08:26 +0000185 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000186 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000187 ConstantInt::get(Src->getType(), ShiftAmt));
188 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000189
Chris Lattner9d051242009-10-25 06:08:26 +0000190 // Mix it in.
191 Elt = ConstantExpr::getOr(Elt, Src);
192 }
193 Result.push_back(Elt);
194 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000195 return ConstantVector::get(Result);
196 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000197
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000198 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
199 unsigned Ratio = NumDstElt/NumSrcElt;
200 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000201
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000202 // Loop over each source value, expanding into multiple results.
203 for (unsigned i = 0; i != NumSrcElt; ++i) {
204 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
205 if (!Src) // Reject constantexpr elements.
206 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000207
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000208 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
209 for (unsigned j = 0; j != Ratio; ++j) {
210 // Shift the piece of the value into the right place, depending on
211 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000212 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000213 ConstantInt::get(Src->getType(), ShiftAmt));
214 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000215
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000216 // Truncate and remember this piece.
217 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000218 }
219 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000220
Chris Lattner69229312011-02-15 00:14:00 +0000221 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000222}
223
224
Chris Lattner44d68b92007-01-31 00:51:48 +0000225/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
226/// from a global, return the global and the constant. Because of
227/// constantexprs, this function is recursive.
228static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
Benjamin Kramer546bb562013-01-23 21:21:24 +0000229 APInt &Offset, const DataLayout &TD) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000230 // Trivial case, constant is the global.
231 if ((GV = dyn_cast<GlobalValue>(C))) {
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000232 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
233 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000234 return true;
235 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000236
Chris Lattner44d68b92007-01-31 00:51:48 +0000237 // Otherwise, if this isn't a constant expr, bail out.
238 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
239 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000240
Chris Lattner44d68b92007-01-31 00:51:48 +0000241 // Look through ptr->int and ptr->ptr casts.
242 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenaultcaa9c712014-07-14 22:39:26 +0000243 CE->getOpcode() == Instruction::BitCast ||
244 CE->getOpcode() == Instruction::AddrSpaceCast)
Chris Lattner44d68b92007-01-31 00:51:48 +0000245 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000246
247 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000248 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
249 if (!GEP)
250 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000251
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000252 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
253 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000254
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000255 // If the base isn't a global+constant, we aren't either.
256 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
257 return false;
258
259 // Otherwise, add any offset that our operands provide.
260 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
261 return false;
262
263 Offset = TmpOffset;
264 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000265}
266
Chris Lattnered00b802009-10-23 06:23:49 +0000267/// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
268/// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
269/// pointer to copy results into and BytesLeft is the number of bytes left in
270/// the CurPtr buffer. TD is the target data.
271static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
272 unsigned char *CurPtr, unsigned BytesLeft,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000273 const DataLayout &TD) {
Chris Lattnered00b802009-10-23 06:23:49 +0000274 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
275 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000276
Chris Lattner3db7bd22009-10-24 05:27:19 +0000277 // If this element is zero or undefined, we can just return since *CurPtr is
278 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000279 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
280 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000281
Chris Lattnered00b802009-10-23 06:23:49 +0000282 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
283 if (CI->getBitWidth() > 64 ||
284 (CI->getBitWidth() & 7) != 0)
285 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000286
Chris Lattnered00b802009-10-23 06:23:49 +0000287 uint64_t Val = CI->getZExtValue();
288 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000289
Chris Lattnered00b802009-10-23 06:23:49 +0000290 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000291 int n = ByteOffset;
292 if (!TD.isLittleEndian())
293 n = IntBytes - n - 1;
294 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000295 ++ByteOffset;
296 }
297 return true;
298 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000299
Chris Lattnered00b802009-10-23 06:23:49 +0000300 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
301 if (CFP->getType()->isDoubleTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000302 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000303 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
304 }
305 if (CFP->getType()->isFloatTy()){
Chris Lattner9d051242009-10-25 06:08:26 +0000306 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000307 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
308 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000309 if (CFP->getType()->isHalfTy()){
310 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
311 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
312 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000313 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000314 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000315
Chris Lattnered00b802009-10-23 06:23:49 +0000316 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
317 const StructLayout *SL = TD.getStructLayout(CS->getType());
318 unsigned Index = SL->getElementContainingOffset(ByteOffset);
319 uint64_t CurEltOffset = SL->getElementOffset(Index);
320 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000321
Chris Lattnered00b802009-10-23 06:23:49 +0000322 while (1) {
323 // If the element access is to the element itself and not to tail padding,
324 // read the bytes from the element.
325 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
326
327 if (ByteOffset < EltSize &&
328 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
329 BytesLeft, TD))
330 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000331
Chris Lattnered00b802009-10-23 06:23:49 +0000332 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000333
Chris Lattnered00b802009-10-23 06:23:49 +0000334 // Check to see if we read from the last struct element, if so we're done.
335 if (Index == CS->getType()->getNumElements())
336 return true;
337
338 // If we read all of the bytes we needed from this element we're done.
339 uint64_t NextEltOffset = SL->getElementOffset(Index);
340
Matt Arsenault8c789092013-08-12 23:15:58 +0000341 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000342 return true;
343
344 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000345 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
346 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000347 ByteOffset = 0;
348 CurEltOffset = NextEltOffset;
349 }
350 // not reached.
351 }
352
Chris Lattner67058832012-01-25 06:48:06 +0000353 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
354 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000355 Type *EltTy = C->getType()->getSequentialElementType();
Chris Lattner67058832012-01-25 06:48:06 +0000356 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000357 uint64_t Index = ByteOffset / EltSize;
358 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000359 uint64_t NumElts;
360 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
361 NumElts = AT->getNumElements();
362 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000363 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000364
Chris Lattner67058832012-01-25 06:48:06 +0000365 for (; Index != NumElts; ++Index) {
366 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
367 BytesLeft, TD))
368 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000369
370 uint64_t BytesWritten = EltSize - Offset;
371 assert(BytesWritten <= EltSize && "Not indexing into this element?");
372 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000373 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000374
Chris Lattner67058832012-01-25 06:48:06 +0000375 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000376 BytesLeft -= BytesWritten;
377 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000378 }
379 return true;
380 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000381
Anders Carlssond21b06a2011-02-06 20:11:56 +0000382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000383 if (CE->getOpcode() == Instruction::IntToPtr &&
Matt Arsenault7a960a82013-08-20 21:20:04 +0000384 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000385 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Chris Lattner67058832012-01-25 06:48:06 +0000386 BytesLeft, TD);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000387 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000388 }
389
Chris Lattnered00b802009-10-23 06:23:49 +0000390 // Otherwise, unknown initializer type.
391 return false;
392}
393
394static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000395 const DataLayout &TD) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000396 PointerType *PTy = cast<PointerType>(C->getType());
397 Type *LoadTy = PTy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000398 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000399
Chris Lattnered00b802009-10-23 06:23:49 +0000400 // If this isn't an integer load we can't fold it directly.
401 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000402 unsigned AS = PTy->getAddressSpace();
403
Chris Lattnered00b802009-10-23 06:23:49 +0000404 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000405 // and then bitcast the result. This can be useful for union cases. Note
406 // that address spaces don't matter here since we're not going to result in
407 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000408 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000409 if (LoadTy->isHalfTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000410 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000411 else if (LoadTy->isFloatTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000412 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000413 else if (LoadTy->isDoubleTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000414 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
Duncan Sands19d0b472010-02-16 11:11:14 +0000415 else if (LoadTy->isVectorTy()) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000416 MapTy = PointerType::getIntNPtrTy(C->getContext(),
417 TD.getTypeAllocSizeInBits(LoadTy),
418 AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000419 } else
Craig Topper9f008862014-04-15 04:59:12 +0000420 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000421
Chris Lattner9d051242009-10-25 06:08:26 +0000422 C = FoldBitCast(C, MapTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000423 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner9d051242009-10-25 06:08:26 +0000424 return FoldBitCast(Res, LoadTy, TD);
Craig Topper9f008862014-04-15 04:59:12 +0000425 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000426 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000427
Chris Lattnered00b802009-10-23 06:23:49 +0000428 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000429 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000430 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000431
Chris Lattnered00b802009-10-23 06:23:49 +0000432 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000433 APInt Offset;
Chris Lattnered00b802009-10-23 06:23:49 +0000434 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
Craig Topper9f008862014-04-15 04:59:12 +0000435 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000436
Chris Lattnered00b802009-10-23 06:23:49 +0000437 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000438 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000439 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000440 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000441
442 // If we're loading off the beginning of the global, some bytes may be valid,
443 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000444 if (Offset.isNegative())
Craig Topper9f008862014-04-15 04:59:12 +0000445 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000446
Chris Lattnered00b802009-10-23 06:23:49 +0000447 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000448 if (Offset.getZExtValue() >=
449 TD.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000450 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000451
Chris Lattner59f94c02009-10-23 06:50:36 +0000452 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000453 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Chris Lattnered00b802009-10-23 06:23:49 +0000454 BytesLoaded, TD))
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000456
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000457 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
458 if (TD.isLittleEndian()) {
459 ResultVal = RawBytes[BytesLoaded - 1];
460 for (unsigned i = 1; i != BytesLoaded; ++i) {
461 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000462 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000463 }
464 } else {
465 ResultVal = RawBytes[0];
466 for (unsigned i = 1; i != BytesLoaded; ++i) {
467 ResultVal <<= 8;
468 ResultVal |= RawBytes[i];
469 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000470 }
Chris Lattnered00b802009-10-23 06:23:49 +0000471
Chris Lattner59f94c02009-10-23 06:50:36 +0000472 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000473}
474
Chandler Carrutha0e56952014-05-15 09:56:28 +0000475static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
476 const DataLayout *DL) {
477 if (!DL)
478 return nullptr;
479 auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
480 if (!DestPtrTy)
481 return nullptr;
482 Type *DestTy = DestPtrTy->getElementType();
483
484 Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
485 if (!C)
486 return nullptr;
487
488 do {
489 Type *SrcTy = C->getType();
490
491 // If the type sizes are the same and a cast is legal, just directly
492 // cast the constant.
493 if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
494 Instruction::CastOps Cast = Instruction::BitCast;
495 // If we are going from a pointer to int or vice versa, we spell the cast
496 // differently.
497 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
498 Cast = Instruction::IntToPtr;
499 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
500 Cast = Instruction::PtrToInt;
501
502 if (CastInst::castIsValid(Cast, C, DestTy))
503 return ConstantExpr::getCast(Cast, C, DestTy);
504 }
505
506 // If this isn't an aggregate type, there is nothing we can do to drill down
507 // and find a bitcastable constant.
508 if (!SrcTy->isAggregateType())
509 return nullptr;
510
511 // We're simulating a load through a pointer that was bitcast to point to
512 // a different type, so we can try to walk down through the initial
513 // elements of an aggregate to see if some part of th e aggregate is
514 // castable to implement the "load" semantic model.
515 C = C->getAggregateElement(0u);
516 } while (C);
517
518 return nullptr;
519}
520
Chris Lattner1664a4f2009-10-22 06:25:11 +0000521/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
522/// produce if it is constant and determinable. If this is not determinable,
523/// return null.
524Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000525 const DataLayout *TD) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000526 // First, try the easy cases:
527 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
528 if (GV->isConstant() && GV->hasDefinitiveInitializer())
529 return GV->getInitializer();
530
Chris Lattnercf7e8942009-10-22 06:44:07 +0000531 // If the loaded value isn't a constant expr, we can't handle it.
532 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000533 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000534 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000535
Chris Lattnercf7e8942009-10-22 06:44:07 +0000536 if (CE->getOpcode() == Instruction::GetElementPtr) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000537 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
538 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000539 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000540 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
541 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000542 }
543 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000544 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000545
Chandler Carrutha0e56952014-05-15 09:56:28 +0000546 if (CE->getOpcode() == Instruction::BitCast)
547 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
548 return LoadedC;
549
Chris Lattnercf7e8942009-10-22 06:44:07 +0000550 // Instead of loading constant c string, use corresponding integer value
551 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000552 StringRef Str;
553 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
554 unsigned StrLen = Str.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000555 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnered00b802009-10-23 06:23:49 +0000556 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000557 // Replace load with immediate integer if the result is an integer or fp
558 // value.
559 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000560 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000561 APInt StrVal(NumBits, 0);
562 APInt SingleChar(NumBits, 0);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000563 if (TD->isLittleEndian()) {
Chris Lattnered00b802009-10-23 06:23:49 +0000564 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000565 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner51d2f702009-10-22 06:38:35 +0000566 StrVal = (StrVal << 8) | SingleChar;
567 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000568 } else {
Chris Lattnered00b802009-10-23 06:23:49 +0000569 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000570 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
571 StrVal = (StrVal << 8) | SingleChar;
572 }
573 // Append NULL at the end.
574 SingleChar = 0;
575 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000576 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000577
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000578 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
579 if (Ty->isFloatingPointTy())
580 Res = ConstantExpr::getBitCast(Res, Ty);
581 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000582 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000583 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000584
Chris Lattnercf7e8942009-10-22 06:44:07 +0000585 // If this load comes from anywhere in a constant global, and if the global
586 // is all undef or zero, we know what it loads.
Dan Gohman0f124e12011-01-24 18:53:32 +0000587 if (GlobalVariable *GV =
588 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000589 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000590 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
Chris Lattnercf7e8942009-10-22 06:44:07 +0000591 if (GV->getInitializer()->isNullValue())
592 return Constant::getNullValue(ResTy);
593 if (isa<UndefValue>(GV->getInitializer()))
594 return UndefValue::get(ResTy);
595 }
596 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000597
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000598 // Try hard to fold loads from bitcasted strange and non-type-safe things.
599 if (TD)
Chris Lattnered00b802009-10-23 06:23:49 +0000600 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Craig Topper9f008862014-04-15 04:59:12 +0000601 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000602}
603
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000604static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
Craig Topper9f008862014-04-15 04:59:12 +0000605 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000606
Chris Lattner1664a4f2009-10-22 06:25:11 +0000607 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
608 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000609
Craig Topper9f008862014-04-15 04:59:12 +0000610 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000611}
Chris Lattner44d68b92007-01-31 00:51:48 +0000612
613/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000614/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000615/// these together. If target data info is available, it is provided as DL,
616/// otherwise DL is null.
Chris Lattner44d68b92007-01-31 00:51:48 +0000617static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Nick Lewycky06417742013-02-14 03:23:37 +0000618 Constant *Op1, const DataLayout *DL){
Chris Lattner44d68b92007-01-31 00:51:48 +0000619 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000620
Chris Lattner44d68b92007-01-31 00:51:48 +0000621 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
622 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
623 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000624
625
Nick Lewycky06417742013-02-14 03:23:37 +0000626 if (Opc == Instruction::And && DL) {
Benjamin Kramerec1bb4f2013-04-19 16:56:24 +0000627 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000628 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
629 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000630 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
631 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000632 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
633 // All the bits of Op0 that the 'and' could be masking are already zero.
634 return Op0;
635 }
636 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
637 // All the bits of Op1 that the 'and' could be masking are already zero.
638 return Op1;
639 }
640
641 APInt KnownZero = KnownZero0 | KnownZero1;
642 APInt KnownOne = KnownOne0 & KnownOne1;
643 if ((KnownZero | KnownOne).isAllOnesValue()) {
644 return ConstantInt::get(Op0->getType(), KnownOne);
645 }
646 }
647
Chris Lattner44d68b92007-01-31 00:51:48 +0000648 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
649 // constant. This happens frequently when iterating over a global array.
Nick Lewycky06417742013-02-14 03:23:37 +0000650 if (Opc == Instruction::Sub && DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000651 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000652 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000653
Nick Lewycky06417742013-02-14 03:23:37 +0000654 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
655 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
Chris Lattner44d68b92007-01-31 00:51:48 +0000656 GV1 == GV2) {
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000657 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
658
Chris Lattner44d68b92007-01-31 00:51:48 +0000659 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000660 // PtrToInt may change the bitwidth so we have convert to the right size
661 // first.
662 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
663 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000664 }
665 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000666
Craig Topper9f008862014-04-15 04:59:12 +0000667 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000668}
669
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000670/// CastGEPIndices - If array indices are not pointer-sized integers,
671/// explicitly cast them so that they aren't implicitly casted by the
672/// getelementptr.
Jay Foadf4b14a22011-07-19 13:32:40 +0000673static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000674 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000675 const TargetLibraryInfo *TLI) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000676 if (!TD)
Craig Topper9f008862014-04-15 04:59:12 +0000677 return nullptr;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000678
679 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000680
681 bool Any = false;
682 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000683 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000684 if ((i == 1 ||
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000685 !isa<StructType>(GetElementPtrInst::getIndexedType(
686 Ops[0]->getType(),
687 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000688 Ops[i]->getType() != IntPtrTy) {
689 Any = true;
690 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
691 true,
692 IntPtrTy,
693 true),
694 Ops[i], IntPtrTy));
695 } else
696 NewIdxs.push_back(Ops[i]);
697 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000698
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000699 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000700 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000701
702 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
703 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chad Rosierc24b86f2011-12-01 03:08:23 +0000704 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000705 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000706 }
707
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000708 return C;
709}
710
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000711/// Strip the pointer casts, but preserve the address space information.
712static Constant* StripPtrCastKeepAS(Constant* Ptr) {
713 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
714 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000715 Ptr = Ptr->stripPointerCasts();
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000716 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
717
718 // Preserve the address space number of the pointer.
719 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
720 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
721 OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000722 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000723 }
724 return Ptr;
725}
726
Chris Lattner44d68b92007-01-31 00:51:48 +0000727/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
728/// constant expression, do so.
Jay Foadf4b14a22011-07-19 13:32:40 +0000729static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000730 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000731 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000732 Constant *Ptr = Ops[0];
Matt Arsenault8c789092013-08-12 23:15:58 +0000733 if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
Nadav Rotem3924cb02011-12-05 06:29:09 +0000734 !Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000735 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000736
Matt Arsenault7a960a82013-08-20 21:20:04 +0000737 Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Matt Arsenault8c789092013-08-12 23:15:58 +0000738 Type *ResultElementTy = ResultTy->getPointerElementType();
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000739
740 // If this is a constant expr gep that is effectively computing an
741 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000742 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000743 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000744
Chris Lattner5858e092011-01-06 06:19:46 +0000745 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
746 // "inttoptr (sub (ptrtoint Ptr), V)"
Matt Arsenault8c789092013-08-12 23:15:58 +0000747 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
Chris Lattner5858e092011-01-06 06:19:46 +0000748 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000749 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000750 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000751 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000752 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000753 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
754 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
755 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
756 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000757 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000758 return Res;
759 }
760 }
Craig Topper9f008862014-04-15 04:59:12 +0000761 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000762 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000763
Chris Lattner171608e2011-01-06 22:24:29 +0000764 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000765 APInt Offset =
766 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
Roman Divacky4717a8d2012-09-06 15:42:13 +0000767 makeArrayRef((Value *const*)
768 Ops.data() + 1,
Jay Foadbf904772011-07-19 14:01:37 +0000769 Ops.size() - 1)));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000770 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000771
772 // If this is a GEP of a GEP, fold it all into a single GEP.
773 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000774 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000775
776 // Do not try the incorporate the sub-GEP if some index is not a number.
777 bool AllConstantInt = true;
778 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
779 if (!isa<ConstantInt>(NestedOps[i])) {
780 AllConstantInt = false;
781 break;
782 }
783 if (!AllConstantInt)
784 break;
785
Dan Gohman474e488c2010-03-10 19:31:51 +0000786 Ptr = cast<Constant>(GEP->getOperand(0));
787 Offset += APInt(BitWidth,
Jay Foadbf904772011-07-19 14:01:37 +0000788 TD->getIndexedOffset(Ptr->getType(), NestedOps));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000789 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000790 }
791
Dan Gohman81ce8422009-08-19 18:18:36 +0000792 // If the base value for this address is a literal integer value, fold the
793 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000794 APInt BasePtr(BitWidth, 0);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000795 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
796 if (CE->getOpcode() == Instruction::IntToPtr) {
Jay Foad583abbc2010-12-07 08:25:19 +0000797 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
798 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000799 }
800 }
801
Dan Gohmana5ca5782010-03-18 19:34:33 +0000802 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000803 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Dan Gohman81ce8422009-08-19 18:18:36 +0000804 return ConstantExpr::getIntToPtr(C, ResultTy);
805 }
806
807 // Otherwise form a regular getelementptr. Recompute the indices so that
808 // we eliminate over-indexing of the notional static type array bounds.
809 // This makes it easy to determine if the getelementptr is "inbounds".
810 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000811 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000812 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000813 SmallVector<Constant *, 32> NewIdxs;
814
Dan Gohmanc59ba422009-08-19 22:46:59 +0000815 do {
Chris Lattner229907c2011-07-18 04:54:35 +0000816 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000817 if (ATy->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000818 // The only pointer indexing we'll do is on the first index of the GEP.
819 if (!NewIdxs.empty())
820 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000821
Chris Lattner77c36d62009-12-03 01:05:45 +0000822 // Only handle pointers to sized types, not pointers to functions.
823 if (!ATy->getElementType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000824 return nullptr;
Chris Lattner77c36d62009-12-03 01:05:45 +0000825 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000826
Dan Gohman81ce8422009-08-19 18:18:36 +0000827 // Determine which element of the array the offset points into.
Dan Gohman23e62c52009-08-21 16:52:54 +0000828 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohman81ce8422009-08-19 18:18:36 +0000829 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000830 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000831 // index for this level and proceed to the next level to see if it can
832 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000833 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
834 else {
835 // The element size is non-zero divide the offset by the element
836 // size (rounding down), to compute the index at this level.
837 APInt NewIdx = Offset.udiv(ElemSize);
838 Offset -= NewIdx * ElemSize;
839 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
840 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000841 Ty = ATy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000842 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000843 // If we end up with an offset that isn't valid for this struct type, we
844 // can't re-form this GEP in a regular form, so bail out. The pointer
845 // operand likely went through casts that are necessary to make the GEP
846 // sensible.
Dan Gohman81ce8422009-08-19 18:18:36 +0000847 const StructLayout &SL = *TD->getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000848 if (Offset.uge(SL.getSizeInBytes()))
849 break;
850
851 // Determine which field of the struct the offset points into. The
852 // getZExtValue is fine as we've already ensured that the offset is
853 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000854 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000855 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
856 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000857 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000858 Ty = STy->getTypeAtIndex(ElIdx);
859 } else {
Dan Gohmanc59ba422009-08-19 22:46:59 +0000860 // We've reached some non-indexable type.
861 break;
Dan Gohman81ce8422009-08-19 18:18:36 +0000862 }
Matt Arsenault8c789092013-08-12 23:15:58 +0000863 } while (Ty != ResultElementTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000864
865 // If we haven't used up the entire offset by descending the static
866 // type, then the offset is pointing into the middle of an indivisible
867 // member, so we can't simplify it.
868 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000869 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000870
Dan Gohman21c62162009-09-11 00:04:14 +0000871 // Create a GEP.
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000872 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000873 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000874 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000875
Dan Gohmanc59ba422009-08-19 22:46:59 +0000876 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000877 // the type of what the original indices indexed, add a cast.
Matt Arsenault8c789092013-08-12 23:15:58 +0000878 if (Ty != ResultElementTy)
Chris Lattner9d051242009-10-25 06:08:26 +0000879 C = FoldBitCast(C, ResultTy, *TD);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000880
881 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000882}
883
Chris Lattner6a6b3fb2007-12-11 07:29:44 +0000884
Chris Lattner44d68b92007-01-31 00:51:48 +0000885
886//===----------------------------------------------------------------------===//
887// Constant Folding public APIs
888//===----------------------------------------------------------------------===//
889
Duncan Sands763dec02010-11-23 10:16:18 +0000890/// ConstantFoldInstruction - Try to constant fold the specified instruction.
891/// If successful, the constant result is returned, if not, null is returned.
892/// Note that this fails if not all of the operands are constant. Otherwise,
893/// this function can only fail when attempting to fold instructions like loads
894/// and stores, which have no constant expression form.
Chad Rosierc24b86f2011-12-01 03:08:23 +0000895Constant *llvm::ConstantFoldInstruction(Instruction *I,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000896 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000897 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +0000898 // Handle PHI nodes quickly here...
Chris Lattner2ae054a2007-01-30 23:45:45 +0000899 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +0000900 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +0000901
Duncan Sands1d27f0122010-11-14 12:53:18 +0000902 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
903 Value *Incoming = PN->getIncomingValue(i);
Duncan Sands763dec02010-11-23 10:16:18 +0000904 // If the incoming value is undef then skip it. Note that while we could
905 // skip the value if it is equal to the phi node itself we choose not to
906 // because that would break the rule that constant folding only applies if
907 // all operands are constants.
908 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000909 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000910 // If the incoming value is not a constant, then give up.
Duncan Sands1d27f0122010-11-14 12:53:18 +0000911 Constant *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000912 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +0000913 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000914 // Fold the PHI's operands.
915 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
916 C = ConstantFoldConstantExpression(NewC, TD, TLI);
917 // If the incoming value is a different constant to
918 // the one we saw previously, then give up.
919 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +0000920 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +0000921 CommonValue = C;
922 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000923
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000924
Duncan Sands1d27f0122010-11-14 12:53:18 +0000925 // If we reach here, all incoming values are the same constant or undef.
926 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000927 }
928
929 // Scan the operand list, checking to see if they are all constants, if so,
930 // hand off to ConstantFoldInstOperands.
931 SmallVector<Constant*, 8> Ops;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000932 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
933 Constant *Op = dyn_cast<Constant>(*i);
934 if (!Op)
Craig Topper9f008862014-04-15 04:59:12 +0000935 return nullptr; // All operands not constant!
Chris Lattner2ae054a2007-01-30 23:45:45 +0000936
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000937 // Fold the Instruction's operands.
938 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
939 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
940
941 Ops.push_back(Op);
942 }
943
Chris Lattnerd2265b42007-12-10 22:53:04 +0000944 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000945 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000946 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000947
Chris Lattner1664a4f2009-10-22 06:25:11 +0000948 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
949 return ConstantFoldLoadInst(LI, TD);
Frits van Bommela98214d2010-11-29 20:36:52 +0000950
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000951 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000952 return ConstantExpr::getInsertValue(
953 cast<Constant>(IVI->getAggregateOperand()),
954 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000955 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000956 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000957
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000958 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000959 return ConstantExpr::getExtractValue(
960 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000961 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000962 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000963
Chad Rosierc24b86f2011-12-01 03:08:23 +0000964 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000965}
966
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000967static Constant *
968ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
969 const TargetLibraryInfo *TLI,
970 SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
971 SmallVector<Constant *, 8> Ops;
972 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
973 ++i) {
Dan Gohman580b80d2009-11-23 16:22:21 +0000974 Constant *NewC = cast<Constant>(*i);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000975 // Recursively fold the ConstantExpr's operands. If we have already folded
976 // a ConstantExpr, we don't have to process it again.
977 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
978 if (FoldedOps.insert(NewCE))
979 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
980 }
Dan Gohman580b80d2009-11-23 16:22:21 +0000981 Ops.push_back(NewC);
982 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000983
984 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000985 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000986 TD, TLI);
987 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000988}
989
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000990/// ConstantFoldConstantExpression - Attempt to fold the constant expression
991/// using the specified DataLayout. If successful, the constant result is
992/// result is returned, if not, null is returned.
993Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
994 const DataLayout *TD,
995 const TargetLibraryInfo *TLI) {
996 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
997 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
998}
999
Chris Lattner2ae054a2007-01-30 23:45:45 +00001000/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
1001/// specified opcode and operands. If successful, the constant result is
1002/// returned, if not, null is returned. Note that this function can fail when
1003/// attempting to fold instructions like loads and stores, which have no
1004/// constant expression form.
1005///
Dan Gohman580b80d2009-11-23 16:22:21 +00001006/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1007/// information, due to only being passed an opcode and operands. Constant
1008/// folding using this function strips this information.
1009///
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001010Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
Jay Foadf4b14a22011-07-19 13:32:40 +00001011 ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001012 const DataLayout *TD,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001013 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +00001014 // Handle easy binops first.
Chris Lattnerd2265b42007-12-10 22:53:04 +00001015 if (Instruction::isBinaryOp(Opcode)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001016 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001017 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner44d68b92007-01-31 00:51:48 +00001018 return C;
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001019 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001020
Owen Anderson487375e2009-07-29 18:55:55 +00001021 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner44d68b92007-01-31 00:51:48 +00001022 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001023
Chris Lattnerd2265b42007-12-10 22:53:04 +00001024 switch (Opcode) {
Craig Topper9f008862014-04-15 04:59:12 +00001025 default: return nullptr;
Chris Lattner8fb74c62010-01-02 01:22:23 +00001026 case Instruction::ICmp:
Craig Toppera2886c22012-02-07 05:05:23 +00001027 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
Chris Lattner2ae054a2007-01-30 23:45:45 +00001028 case Instruction::Call:
Jay Foadf4b14a22011-07-19 13:32:40 +00001029 if (Function *F = dyn_cast<Function>(Ops.back()))
Chris Lattner2ae054a2007-01-30 23:45:45 +00001030 if (canConstantFoldCallTo(F))
Chad Rosierc24b86f2011-12-01 03:08:23 +00001031 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
Craig Topper9f008862014-04-15 04:59:12 +00001032 return nullptr;
Chris Lattner460e34a2007-08-11 23:49:01 +00001033 case Instruction::PtrToInt:
1034 // If the input is a inttoptr, eliminate the pair. This requires knowing
1035 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1036 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1037 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
1038 Constant *Input = CE->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001039 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001040 unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
1041 if (PtrWidth < InWidth) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001042 Constant *Mask =
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001043 ConstantInt::get(CE->getContext(),
1044 APInt::getLowBitsSet(InWidth, PtrWidth));
Owen Anderson487375e2009-07-29 18:55:55 +00001045 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky730d5da2008-10-24 06:14:27 +00001046 }
Chris Lattner460e34a2007-08-11 23:49:01 +00001047 // Do a zext or trunc to get to the dest size.
Owen Anderson487375e2009-07-29 18:55:55 +00001048 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner460e34a2007-08-11 23:49:01 +00001049 }
1050 }
Owen Anderson487375e2009-07-29 18:55:55 +00001051 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner460e34a2007-08-11 23:49:01 +00001052 case Instruction::IntToPtr:
Duncan Sandsea68a6c2008-08-13 20:20:35 +00001053 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001054 // the int size is >= the ptr size and the address spaces are the same.
1055 // This requires knowing the width of a pointer, so it can't be done in
1056 // ConstantExpr::getCast.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001057 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1058 if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1059 Constant *SrcPtr = CE->getOperand(0);
1060 unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1061 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1062
1063 if (MidIntSize >= SrcPtrSize) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001064 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1065 if (SrcAS == DestTy->getPointerAddressSpace())
Matt Arsenault7a960a82013-08-20 21:20:04 +00001066 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1067 }
1068 }
1069 }
Dan Gohman8a0eb362010-02-23 16:35:41 +00001070
Owen Anderson487375e2009-07-29 18:55:55 +00001071 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001072 case Instruction::Trunc:
1073 case Instruction::ZExt:
1074 case Instruction::SExt:
1075 case Instruction::FPTrunc:
1076 case Instruction::FPExt:
1077 case Instruction::UIToFP:
1078 case Instruction::SIToFP:
1079 case Instruction::FPToUI:
1080 case Instruction::FPToSI:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001081 case Instruction::AddrSpaceCast:
Owen Anderson487375e2009-07-29 18:55:55 +00001082 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001083 case Instruction::BitCast:
Chris Lattner6a6b3fb2007-12-11 07:29:44 +00001084 if (TD)
Chris Lattner9d051242009-10-25 06:08:26 +00001085 return FoldBitCast(Ops[0], DestTy, *TD);
Owen Anderson487375e2009-07-29 18:55:55 +00001086 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001087 case Instruction::Select:
Owen Anderson487375e2009-07-29 18:55:55 +00001088 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001089 case Instruction::ExtractElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001090 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001091 case Instruction::InsertElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001092 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001093 case Instruction::ShuffleVector:
Owen Anderson487375e2009-07-29 18:55:55 +00001094 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001095 case Instruction::GetElementPtr:
Chad Rosierc24b86f2011-12-01 03:08:23 +00001096 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001097 return C;
Chad Rosierc24b86f2011-12-01 03:08:23 +00001098 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
Chris Lattner44d68b92007-01-31 00:51:48 +00001099 return C;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001100
Jay Foaded8db7d2011-07-21 14:31:17 +00001101 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
Chris Lattner2ae054a2007-01-30 23:45:45 +00001102 }
1103}
1104
Chris Lattnerd2265b42007-12-10 22:53:04 +00001105/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
1106/// instruction (icmp/fcmp) with the specified operands. If it fails, it
1107/// returns a constant expression of the specified operands.
1108///
1109Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001110 Constant *Ops0, Constant *Ops1,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001111 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001112 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001113 // fold: icmp (inttoptr x), null -> icmp x, 0
1114 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001115 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001116 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1117 //
1118 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1119 // around to know if bit truncation is happening.
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001120 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1121 if (TD && Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001122 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001123 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001124 // Convert the integer value to the right size to ensure we get the
1125 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001126 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001127 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001128 Constant *Null = Constant::getNullValue(C->getType());
Chad Rosierc24b86f2011-12-01 03:08:23 +00001129 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001130 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001131
Chris Lattnerd2265b42007-12-10 22:53:04 +00001132 // Only do this transformation if the int is intptrty in size, otherwise
1133 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001134 if (CE0->getOpcode() == Instruction::PtrToInt) {
1135 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1136 if (CE0->getType() == IntPtrTy) {
1137 Constant *C = CE0->getOperand(0);
1138 Constant *Null = Constant::getNullValue(C->getType());
1139 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1140 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001141 }
1142 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001143
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001144 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001145 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001146 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001147 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1148
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001149 // Convert the integer value to the right size to ensure we get the
1150 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001151 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001152 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001153 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001154 IntPtrTy, false);
Chad Rosierc24b86f2011-12-01 03:08:23 +00001155 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001156 }
1157
Chandler Carruth7ec50852012-11-01 08:07:29 +00001158 // Only do this transformation if the int is intptrty in size, otherwise
1159 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001160 if (CE0->getOpcode() == Instruction::PtrToInt) {
1161 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1162 if (CE0->getType() == IntPtrTy &&
1163 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1164 return ConstantFoldCompareInstOperands(Predicate,
1165 CE0->getOperand(0),
1166 CE1->getOperand(0),
1167 TD,
1168 TLI);
1169 }
1170 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001171 }
1172 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001173
Chris Lattner8fb74c62010-01-02 01:22:23 +00001174 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1175 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1176 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1177 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001178 Constant *LHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001179 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1180 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001181 Constant *RHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001182 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1183 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001184 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001185 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1186 Constant *Ops[] = { LHS, RHS };
Chad Rosierc24b86f2011-12-01 03:08:23 +00001187 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001188 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001189 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001190
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001191 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001192}
1193
1194
Chris Lattner2ae054a2007-01-30 23:45:45 +00001195/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1196/// getelementptr constantexpr, return the constant value being addressed by the
1197/// constant expression, or null if something is funny and we can't decide.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001198Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001199 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001200 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001201 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001202
1203 // Loop over all of the operands, tracking down which value we are
1204 // addressing.
1205 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1206 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001207 if (!C)
1208 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001209 }
1210 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001211}
1212
1213/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1214/// indices (with an *implied* zero pointer index that is not in the list),
1215/// return the constant value being addressed by a virtual load, or null if
1216/// something is funny and we can't decide.
1217Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1218 ArrayRef<Constant*> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001219 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001220 // addressing.
1221 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +00001222 C = C->getAggregateElement(Indices[i]);
Craig Topper9f008862014-04-15 04:59:12 +00001223 if (!C)
1224 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001225 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001226 return C;
1227}
1228
1229
1230//===----------------------------------------------------------------------===//
1231// Constant Folding for Calls
1232//
John Criswell970af112005-10-27 16:00:10 +00001233
1234/// canConstantFoldCallTo - Return true if its even possible to fold a call to
1235/// the specified function.
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001236bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001237 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001238 case Intrinsic::fabs:
1239 case Intrinsic::log:
1240 case Intrinsic::log2:
1241 case Intrinsic::log10:
1242 case Intrinsic::exp:
1243 case Intrinsic::exp2:
1244 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001245 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001246 case Intrinsic::sqrt:
Chad Rosier0155a632011-12-03 00:00:03 +00001247 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001248 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001249 case Intrinsic::bswap:
1250 case Intrinsic::ctpop:
1251 case Intrinsic::ctlz:
1252 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001253 case Intrinsic::fma:
1254 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001255 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001256 case Intrinsic::round:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001257 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001258 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001259 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001260 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001261 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001262 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001263 case Intrinsic::convert_from_fp16:
1264 case Intrinsic::convert_to_fp16:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001265 case Intrinsic::x86_sse_cvtss2si:
1266 case Intrinsic::x86_sse_cvtss2si64:
1267 case Intrinsic::x86_sse_cvttss2si:
1268 case Intrinsic::x86_sse_cvttss2si64:
1269 case Intrinsic::x86_sse2_cvtsd2si:
1270 case Intrinsic::x86_sse2_cvtsd2si64:
1271 case Intrinsic::x86_sse2_cvttsd2si:
1272 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001273 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001274 default:
1275 return false;
1276 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001277 }
1278
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001279 if (!F->hasName())
1280 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001281 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001282
Chris Lattner785f9982007-08-08 06:55:43 +00001283 // In these cases, the check of the length is required. We don't want to
1284 // return true for a name like "cos\0blah" which strcmp would return equal to
1285 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001286 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001287 default: return false;
1288 case 'a':
Chad Rosierc0955a52013-02-20 23:57:30 +00001289 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
Chris Lattner785f9982007-08-08 06:55:43 +00001290 case 'c':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001291 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattner785f9982007-08-08 06:55:43 +00001292 case 'e':
Chris Lattner713d5232011-05-22 22:22:35 +00001293 return Name == "exp" || Name == "exp2";
Chris Lattner785f9982007-08-08 06:55:43 +00001294 case 'f':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001295 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattner785f9982007-08-08 06:55:43 +00001296 case 'l':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001297 return Name == "log" || Name == "log10";
Chris Lattner785f9982007-08-08 06:55:43 +00001298 case 'p':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001299 return Name == "pow";
Chris Lattner785f9982007-08-08 06:55:43 +00001300 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001301 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1302 Name == "sinf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001303 case 't':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001304 return Name == "tan" || Name == "tanh";
John Criswell970af112005-10-27 16:00:10 +00001305 }
1306}
1307
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001308static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001309 if (Ty->isHalfTy()) {
1310 APFloat APF(V);
1311 bool unused;
1312 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1313 return ConstantFP::get(Ty->getContext(), APF);
1314 }
Chris Lattner351534f2009-10-05 05:06:24 +00001315 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001316 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001317 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001318 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001319 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001320
1321}
1322
Alp Tokerc817d6a2014-06-09 18:28:53 +00001323namespace {
1324/// llvm_fenv_clearexcept - Clear the floating-point exception state.
1325static inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001326#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001327 feclearexcept(FE_ALL_EXCEPT);
1328#endif
1329 errno = 0;
1330}
1331
1332/// llvm_fenv_testexcept - Test if a floating-point exception was raised.
1333static inline bool llvm_fenv_testexcept() {
1334 int errno_val = errno;
1335 if (errno_val == ERANGE || errno_val == EDOM)
1336 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001337#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001338 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1339 return true;
1340#endif
1341 return false;
1342}
1343} // End namespace
1344
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001345static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1346 Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001347 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001348 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001349 if (llvm_fenv_testexcept()) {
1350 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001351 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001352 }
1353
1354 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001355}
1356
Dan Gohman72efc042007-07-16 15:26:22 +00001357static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
Chris Lattner229907c2011-07-18 04:54:35 +00001358 double V, double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001359 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001360 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001361 if (llvm_fenv_testexcept()) {
1362 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001363 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001364 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001365
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001366 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001367}
1368
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001369/// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1370/// conversion of a constant floating point. If roundTowardZero is false, the
1371/// default IEEE rounding is used (toward nearest, ties to even). This matches
1372/// the behavior of the non-truncating SSE instructions in the default rounding
1373/// mode. The desired integer type Ty is used to select how many bits are
1374/// available for the result. Returns null if the conversion cannot be
1375/// performed, otherwise returns the Constant value resulting from the
1376/// conversion.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001377static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1378 bool roundTowardZero, Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001379 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001380 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001381 assert(ResultWidth <= 64 &&
1382 "Can only constant fold conversions to 64 and 32 bit ints");
1383
1384 uint64_t UIntVal;
1385 bool isExact = false;
1386 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1387 : APFloat::rmNearestTiesToEven;
1388 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1389 /*isSigned=*/true, mode,
1390 &isExact);
1391 if (status != APFloat::opOK && status != APFloat::opInexact)
Craig Topper9f008862014-04-15 04:59:12 +00001392 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001393 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1394}
1395
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001396static double getValueAsDouble(ConstantFP *Op) {
1397 Type *Ty = Op->getType();
1398
1399 if (Ty->isFloatTy())
1400 return Op->getValueAPF().convertToFloat();
1401
1402 if (Ty->isDoubleTy())
1403 return Op->getValueAPF().convertToDouble();
1404
1405 bool unused;
1406 APFloat APF = Op->getValueAPF();
1407 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1408 return APF.convertToDouble();
1409}
1410
Benjamin Kramer061d1472014-03-05 19:41:48 +00001411static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1412 Type *Ty, ArrayRef<Constant *> Operands,
1413 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001414 if (Operands.size() == 1) {
John Criswell970af112005-10-27 16:00:10 +00001415 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001416 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001417 APFloat Val(Op->getValueAPF());
1418
1419 bool lost = false;
1420 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1421
Benjamin Kramer061d1472014-03-05 19:41:48 +00001422 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001423 }
1424
Owen Andersond4ebfd82013-02-06 22:43:31 +00001425 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001426 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001427
Karthik Bhatb67688a2014-03-07 04:36:21 +00001428 if (IntrinsicID == Intrinsic::round) {
1429 APFloat V = Op->getValueAPF();
1430 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1431 return ConstantFP::get(Ty->getContext(), V);
1432 }
1433
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001434 /// We only fold functions with finite arguments. Folding NaN and inf is
1435 /// likely to be aborted with an exception anyway, and some host libms
1436 /// have known errors raising exceptions.
1437 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001438 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001439
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001440 /// Currently APFloat versions of these functions do not exist, so we use
1441 /// the host native double versions. Float versions are not called
1442 /// directly but for all these it is true (float)(f((double)arg)) ==
1443 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001444 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001445
Benjamin Kramer061d1472014-03-05 19:41:48 +00001446 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001447 default: break;
1448 case Intrinsic::fabs:
1449 return ConstantFoldFP(fabs, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001450#if HAVE_LOG2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001451 case Intrinsic::log2:
1452 return ConstantFoldFP(log2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001453#endif
1454#if HAVE_LOG
Owen Andersond4ebfd82013-02-06 22:43:31 +00001455 case Intrinsic::log:
1456 return ConstantFoldFP(log, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001457#endif
1458#if HAVE_LOG10
Owen Andersond4ebfd82013-02-06 22:43:31 +00001459 case Intrinsic::log10:
1460 return ConstantFoldFP(log10, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001461#endif
1462#if HAVE_EXP
Owen Andersond4ebfd82013-02-06 22:43:31 +00001463 case Intrinsic::exp:
1464 return ConstantFoldFP(exp, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001465#endif
1466#if HAVE_EXP2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001467 case Intrinsic::exp2:
1468 return ConstantFoldFP(exp2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001469#endif
Owen Andersond4ebfd82013-02-06 22:43:31 +00001470 case Intrinsic::floor:
1471 return ConstantFoldFP(floor, V, Ty);
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001472 case Intrinsic::ceil:
1473 return ConstantFoldFP(ceil, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001474 }
1475
Benjamin Kramer061d1472014-03-05 19:41:48 +00001476 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001477 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001478
Daniel Dunbarca414c72009-07-26 08:34:35 +00001479 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001480 case 'a':
Chad Rosier576c0f82011-12-01 23:16:03 +00001481 if (Name == "acos" && TLI->has(LibFunc::acos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001482 return ConstantFoldFP(acos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001483 else if (Name == "asin" && TLI->has(LibFunc::asin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001484 return ConstantFoldFP(asin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001485 else if (Name == "atan" && TLI->has(LibFunc::atan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001486 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001487 break;
1488 case 'c':
Chad Rosier576c0f82011-12-01 23:16:03 +00001489 if (Name == "ceil" && TLI->has(LibFunc::ceil))
Chris Lattner46b5c642009-11-06 04:27:31 +00001490 return ConstantFoldFP(ceil, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001491 else if (Name == "cos" && TLI->has(LibFunc::cos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001492 return ConstantFoldFP(cos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001493 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001494 return ConstantFoldFP(cosh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001495 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001496 return ConstantFoldFP(cos, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001497 break;
1498 case 'e':
Chad Rosier576c0f82011-12-01 23:16:03 +00001499 if (Name == "exp" && TLI->has(LibFunc::exp))
Chris Lattner46b5c642009-11-06 04:27:31 +00001500 return ConstantFoldFP(exp, V, Ty);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001501
Chad Rosier576c0f82011-12-01 23:16:03 +00001502 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
Chris Lattner713d5232011-05-22 22:22:35 +00001503 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1504 // C99 library.
1505 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1506 }
Chris Lattner785f9982007-08-08 06:55:43 +00001507 break;
1508 case 'f':
Chad Rosier576c0f82011-12-01 23:16:03 +00001509 if (Name == "fabs" && TLI->has(LibFunc::fabs))
Chris Lattner46b5c642009-11-06 04:27:31 +00001510 return ConstantFoldFP(fabs, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001511 else if (Name == "floor" && TLI->has(LibFunc::floor))
Chris Lattner46b5c642009-11-06 04:27:31 +00001512 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001513 break;
1514 case 'l':
Chad Rosier576c0f82011-12-01 23:16:03 +00001515 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
Chris Lattner46b5c642009-11-06 04:27:31 +00001516 return ConstantFoldFP(log, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001517 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
Chris Lattner46b5c642009-11-06 04:27:31 +00001518 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001519 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001520 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001521 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001522 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001523 else // Undefined
Owen Anderson5a1acd92009-07-31 20:28:14 +00001524 return Constant::getNullValue(Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001525 }
1526 break;
1527 case 's':
Chad Rosier576c0f82011-12-01 23:16:03 +00001528 if (Name == "sin" && TLI->has(LibFunc::sin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001529 return ConstantFoldFP(sin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001530 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001531 return ConstantFoldFP(sinh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001532 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
Chris Lattner46b5c642009-11-06 04:27:31 +00001533 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001534 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001535 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001536 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001537 return ConstantFoldFP(sin, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001538 break;
1539 case 't':
Chad Rosier576c0f82011-12-01 23:16:03 +00001540 if (Name == "tan" && TLI->has(LibFunc::tan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001541 return ConstantFoldFP(tan, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001542 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001543 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001544 break;
1545 default:
1546 break;
John Criswell970af112005-10-27 16:00:10 +00001547 }
Craig Topper9f008862014-04-15 04:59:12 +00001548 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001549 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001550
Chris Lattner9ca7c092009-10-05 05:00:35 +00001551 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001552 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001553 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001554 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001555 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001556 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001557 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001558 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001559
1560 bool lost = false;
1561 APFloat::opStatus status =
1562 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1563
1564 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001565 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001566 assert(status == APFloat::opOK && !lost &&
1567 "Precision lost during fp16 constfolding");
1568
Benjamin Kramer061d1472014-03-05 19:41:48 +00001569 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001570 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001571 default:
Craig Topper9f008862014-04-15 04:59:12 +00001572 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001573 }
John Criswell970af112005-10-27 16:00:10 +00001574 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001575
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001576 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001577 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001578 isa<ConstantDataVector>(Operands[0])) {
1579 Constant *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001580 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001581 default: break;
1582 case Intrinsic::x86_sse_cvtss2si:
1583 case Intrinsic::x86_sse_cvtss2si64:
1584 case Intrinsic::x86_sse2_cvtsd2si:
1585 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001586 if (ConstantFP *FPOp =
1587 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1588 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1589 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001590 case Intrinsic::x86_sse_cvttss2si:
1591 case Intrinsic::x86_sse_cvttss2si64:
1592 case Intrinsic::x86_sse2_cvttsd2si:
1593 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001594 if (ConstantFP *FPOp =
1595 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001596 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001597 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001598 }
1599 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001600
Dan Gohmancf39be32010-02-17 00:54:58 +00001601 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001602 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001603 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001604 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001605 }
1606
Craig Topper9f008862014-04-15 04:59:12 +00001607 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001608 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001609
Jay Foadf4b14a22011-07-19 13:32:40 +00001610 if (Operands.size() == 2) {
John Criswell970af112005-10-27 16:00:10 +00001611 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001612 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001613 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001614 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001615
John Criswell970af112005-10-27 16:00:10 +00001616 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001617 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001618 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001619
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001620 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001621 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001622 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1623 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001624 if (IntrinsicID == Intrinsic::copysign) {
1625 APFloat V1 = Op1->getValueAPF();
1626 APFloat V2 = Op2->getValueAPF();
1627 V1.copySign(V2);
1628 return ConstantFP::get(Ty->getContext(), V1);
1629 }
Chad Rosier0155a632011-12-03 00:00:03 +00001630 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001631 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001632 if (Name == "pow" && TLI->has(LibFunc::pow))
Chris Lattner46b5c642009-11-06 04:27:31 +00001633 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001634 if (Name == "fmod" && TLI->has(LibFunc::fmod))
Chris Lattner46b5c642009-11-06 04:27:31 +00001635 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001636 if (Name == "atan2" && TLI->has(LibFunc::atan2))
Chris Lattner46b5c642009-11-06 04:27:31 +00001637 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattner26933dd2007-01-15 06:27:37 +00001638 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001639 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1640 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001641 APFloat((float)std::pow((float)Op1V,
1642 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001643 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1644 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001645 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001646 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001647 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1648 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001649 APFloat((double)std::pow((double)Op1V,
1650 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001651 }
Craig Topper9f008862014-04-15 04:59:12 +00001652 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001653 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001654
Chris Lattner59d93982009-10-05 05:26:04 +00001655 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1656 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001657 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001658 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001659 case Intrinsic::sadd_with_overflow:
1660 case Intrinsic::uadd_with_overflow:
1661 case Intrinsic::ssub_with_overflow:
1662 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001663 case Intrinsic::smul_with_overflow:
1664 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001665 APInt Res;
1666 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001667 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001668 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001669 case Intrinsic::sadd_with_overflow:
1670 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1671 break;
1672 case Intrinsic::uadd_with_overflow:
1673 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1674 break;
1675 case Intrinsic::ssub_with_overflow:
1676 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1677 break;
1678 case Intrinsic::usub_with_overflow:
1679 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1680 break;
1681 case Intrinsic::smul_with_overflow:
1682 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1683 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001684 case Intrinsic::umul_with_overflow:
1685 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1686 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001687 }
Chris Lattner59d93982009-10-05 05:26:04 +00001688 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001689 ConstantInt::get(Ty->getContext(), Res),
1690 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001691 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001692 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001693 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001694 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001695 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1696 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001697 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1698 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001699 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1700 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001701 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001702 }
1703 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001704
Craig Topper9f008862014-04-15 04:59:12 +00001705 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001706 }
Craig Topper9f008862014-04-15 04:59:12 +00001707 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001708 }
Matt Arsenault83778582014-03-05 00:02:00 +00001709
1710 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001711 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001712
1713 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1714 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1715 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001716 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001717 default: break;
1718 case Intrinsic::fma:
1719 case Intrinsic::fmuladd: {
1720 APFloat V = Op1->getValueAPF();
1721 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1722 Op3->getValueAPF(),
1723 APFloat::rmNearestTiesToEven);
1724 if (s != APFloat::opInvalidOp)
1725 return ConstantFP::get(Ty->getContext(), V);
1726
Craig Topper9f008862014-04-15 04:59:12 +00001727 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001728 }
1729 }
1730 }
1731 }
1732 }
1733
Craig Topper9f008862014-04-15 04:59:12 +00001734 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001735}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001736
1737static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1738 VectorType *VTy,
1739 ArrayRef<Constant *> Operands,
1740 const TargetLibraryInfo *TLI) {
1741 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1742 SmallVector<Constant *, 4> Lane(Operands.size());
1743 Type *Ty = VTy->getElementType();
1744
1745 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1746 // Gather a column of constants.
1747 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1748 Constant *Agg = Operands[J]->getAggregateElement(I);
1749 if (!Agg)
1750 return nullptr;
1751
1752 Lane[J] = Agg;
1753 }
1754
1755 // Use the regular scalar folding to simplify this column.
1756 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1757 if (!Folded)
1758 return nullptr;
1759 Result[I] = Folded;
1760 }
1761
1762 return ConstantVector::get(Result);
1763}
1764
1765/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1766/// with the specified arguments, returning null if unsuccessful.
1767Constant *
1768llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1769 const TargetLibraryInfo *TLI) {
1770 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001771 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001772 StringRef Name = F->getName();
1773
1774 Type *Ty = F->getReturnType();
1775
1776 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1777 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1778
1779 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1780}