blob: 70c929b53a3f91881bd70e92b971019a0c76a9f4 [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000025#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000035#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000036#include "llvm/Support/MathExtras.h"
37#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
Sanjay Patel0d7dee62014-10-02 15:13:22 +000050/// Constant fold bitcast, symbolically evaluating it with DataLayout.
51/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000052/// ConstantExpr if unfoldable.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000053static Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000054 // Catch the obvious splat cases.
55 if (C->isNullValue() && !DestTy->isX86_MMXTy())
56 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000057 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
58 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +000059 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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000086 unsigned BitShift = DL.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;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000090 if (DL.isLittleEndian())
Chris Lattner8213c8a2012-02-06 21:56:39 +000091 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!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000108 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 C = FoldBitCast(C, DestIVTy, DL);
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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000164 bool isLittleEndian = DL.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;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000200 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
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
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000216 // Truncate the element to an integer with the same pointer size and
217 // convert the element back to a pointer using a inttoptr.
218 if (DstEltTy->isPointerTy()) {
219 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
220 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
221 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
222 continue;
223 }
224
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000225 // Truncate and remember this piece.
226 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000227 }
228 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000229
Chris Lattner69229312011-02-15 00:14:00 +0000230 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000231}
232
233
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000234/// If this constant is a constant offset from a global, return the global and
235/// the constant. Because of constantexprs, this function is recursive.
Chris Lattner44d68b92007-01-31 00:51:48 +0000236static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000238 // Trivial case, constant is the global.
239 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000240 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000241 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000242 return true;
243 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000244
Chris Lattner44d68b92007-01-31 00:51:48 +0000245 // Otherwise, if this isn't a constant expr, bail out.
246 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
247 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000248
Chris Lattner44d68b92007-01-31 00:51:48 +0000249 // Look through ptr->int and ptr->ptr casts.
250 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenaultcaa9c712014-07-14 22:39:26 +0000251 CE->getOpcode() == Instruction::BitCast ||
252 CE->getOpcode() == Instruction::AddrSpaceCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000253 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000254
255 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000256 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
257 if (!GEP)
258 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000259
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000260 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000261 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000262
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000263 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000265 return false;
266
267 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000268 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000269 return false;
270
271 Offset = TmpOffset;
272 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000273}
274
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000275/// Recursive helper to read bits out of global. C is the constant being copied
276/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
277/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278/// the CurPtr buffer. DL is the DataLayout.
Chris Lattnered00b802009-10-23 06:23:49 +0000279static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
280 unsigned char *CurPtr, unsigned BytesLeft,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000281 const DataLayout &DL) {
282 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000283 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000284
Chris Lattner3db7bd22009-10-24 05:27:19 +0000285 // If this element is zero or undefined, we can just return since *CurPtr is
286 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000287 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
288 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000289
Chris Lattnered00b802009-10-23 06:23:49 +0000290 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
291 if (CI->getBitWidth() > 64 ||
292 (CI->getBitWidth() & 7) != 0)
293 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000294
Chris Lattnered00b802009-10-23 06:23:49 +0000295 uint64_t Val = CI->getZExtValue();
296 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000297
Chris Lattnered00b802009-10-23 06:23:49 +0000298 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000299 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000301 n = IntBytes - n - 1;
302 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000303 ++ByteOffset;
304 }
305 return true;
306 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000307
Chris Lattnered00b802009-10-23 06:23:49 +0000308 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
309 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
311 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000312 }
313 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
315 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000316 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000317 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000318 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
319 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000320 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000321 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000322 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000323
Chris Lattnered00b802009-10-23 06:23:49 +0000324 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000326 unsigned Index = SL->getElementContainingOffset(ByteOffset);
327 uint64_t CurEltOffset = SL->getElementOffset(Index);
328 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000329
Chris Lattnered00b802009-10-23 06:23:49 +0000330 while (1) {
331 // If the element access is to the element itself and not to tail padding,
332 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000334
335 if (ByteOffset < EltSize &&
336 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000337 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000338 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000339
Chris Lattnered00b802009-10-23 06:23:49 +0000340 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000341
Chris Lattnered00b802009-10-23 06:23:49 +0000342 // Check to see if we read from the last struct element, if so we're done.
343 if (Index == CS->getType()->getNumElements())
344 return true;
345
346 // If we read all of the bytes we needed from this element we're done.
347 uint64_t NextEltOffset = SL->getElementOffset(Index);
348
Matt Arsenault8c789092013-08-12 23:15:58 +0000349 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000350 return true;
351
352 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000353 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
354 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000355 ByteOffset = 0;
356 CurEltOffset = NextEltOffset;
357 }
358 // not reached.
359 }
360
Chris Lattner67058832012-01-25 06:48:06 +0000361 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
362 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000363 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000364 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000365 uint64_t Index = ByteOffset / EltSize;
366 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000367 uint64_t NumElts;
368 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
369 NumElts = AT->getNumElements();
370 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000371 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000372
Chris Lattner67058832012-01-25 06:48:06 +0000373 for (; Index != NumElts; ++Index) {
374 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000375 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000376 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000377
378 uint64_t BytesWritten = EltSize - Offset;
379 assert(BytesWritten <= EltSize && "Not indexing into this element?");
380 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000381 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000382
Chris Lattner67058832012-01-25 06:48:06 +0000383 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000384 BytesLeft -= BytesWritten;
385 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000386 }
387 return true;
388 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000389
Anders Carlssond21b06a2011-02-06 20:11:56 +0000390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000391 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000393 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000394 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000395 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000396 }
397
Chris Lattnered00b802009-10-23 06:23:49 +0000398 // Otherwise, unknown initializer type.
399 return false;
400}
401
402static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000403 const DataLayout &DL) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000404 PointerType *PTy = cast<PointerType>(C->getType());
405 Type *LoadTy = PTy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000406 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000407
Chris Lattnered00b802009-10-23 06:23:49 +0000408 // If this isn't an integer load we can't fold it directly.
409 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000410 unsigned AS = PTy->getAddressSpace();
411
Chris Lattnered00b802009-10-23 06:23:49 +0000412 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000413 // and then bitcast the result. This can be useful for union cases. Note
414 // that address spaces don't matter here since we're not going to result in
415 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000416 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000417 if (LoadTy->isHalfTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000418 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000419 else if (LoadTy->isFloatTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000420 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000421 else if (LoadTy->isDoubleTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000422 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
Duncan Sands19d0b472010-02-16 11:11:14 +0000423 else if (LoadTy->isVectorTy()) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000424 MapTy = PointerType::getIntNPtrTy(C->getContext(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000425 DL.getTypeAllocSizeInBits(LoadTy), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000426 } else
Craig Topper9f008862014-04-15 04:59:12 +0000427 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000428
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 C = FoldBitCast(C, MapTy, DL);
430 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, DL))
431 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000432 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000433 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000434
Chris Lattnered00b802009-10-23 06:23:49 +0000435 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000436 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000437 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000438
Chris Lattnered00b802009-10-23 06:23:49 +0000439 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000440 APInt Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000442 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000443
Chris Lattnered00b802009-10-23 06:23:49 +0000444 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000445 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000446 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000447 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000448
449 // If we're loading off the beginning of the global, some bytes may be valid,
450 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000451 if (Offset.isNegative())
Craig Topper9f008862014-04-15 04:59:12 +0000452 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000453
Chris Lattnered00b802009-10-23 06:23:49 +0000454 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000455 if (Offset.getZExtValue() >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000456 DL.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000457 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000458
Chris Lattner59f94c02009-10-23 06:50:36 +0000459 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000460 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 BytesLoaded, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000462 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000463
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000464 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000466 ResultVal = RawBytes[BytesLoaded - 1];
467 for (unsigned i = 1; i != BytesLoaded; ++i) {
468 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000469 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000470 }
471 } else {
472 ResultVal = RawBytes[0];
473 for (unsigned i = 1; i != BytesLoaded; ++i) {
474 ResultVal <<= 8;
475 ResultVal |= RawBytes[i];
476 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000477 }
Chris Lattnered00b802009-10-23 06:23:49 +0000478
Chris Lattner59f94c02009-10-23 06:50:36 +0000479 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000480}
481
Chandler Carrutha0e56952014-05-15 09:56:28 +0000482static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 const DataLayout &DL) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000484 auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
485 if (!DestPtrTy)
486 return nullptr;
487 Type *DestTy = DestPtrTy->getElementType();
488
489 Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
490 if (!C)
491 return nullptr;
492
493 do {
494 Type *SrcTy = C->getType();
495
496 // If the type sizes are the same and a cast is legal, just directly
497 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000498 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000499 Instruction::CastOps Cast = Instruction::BitCast;
500 // If we are going from a pointer to int or vice versa, we spell the cast
501 // differently.
502 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
503 Cast = Instruction::IntToPtr;
504 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
505 Cast = Instruction::PtrToInt;
506
507 if (CastInst::castIsValid(Cast, C, DestTy))
508 return ConstantExpr::getCast(Cast, C, DestTy);
509 }
510
511 // If this isn't an aggregate type, there is nothing we can do to drill down
512 // and find a bitcastable constant.
513 if (!SrcTy->isAggregateType())
514 return nullptr;
515
516 // We're simulating a load through a pointer that was bitcast to point to
517 // a different type, so we can try to walk down through the initial
518 // elements of an aggregate to see if some part of th e aggregate is
519 // castable to implement the "load" semantic model.
520 C = C->getAggregateElement(0u);
521 } while (C);
522
523 return nullptr;
524}
525
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000526/// Return the value that a load from C would produce if it is constant and
527/// determinable. If this is not determinable, return null.
Chris Lattner1664a4f2009-10-22 06:25:11 +0000528Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000529 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000530 // First, try the easy cases:
531 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
532 if (GV->isConstant() && GV->hasDefinitiveInitializer())
533 return GV->getInitializer();
534
David Majnemered9abe12015-07-22 22:29:30 +0000535 if (auto *GA = dyn_cast<GlobalAlias>(C))
536 if (GA->getAliasee() && !GA->mayBeOverridden())
537 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), DL);
538
Chris Lattnercf7e8942009-10-22 06:44:07 +0000539 // If the loaded value isn't a constant expr, we can't handle it.
540 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000541 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000542 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000543
Chris Lattnercf7e8942009-10-22 06:44:07 +0000544 if (CE->getOpcode() == Instruction::GetElementPtr) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000545 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
546 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000547 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000548 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
549 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000550 }
551 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000552 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000553
Chandler Carrutha0e56952014-05-15 09:56:28 +0000554 if (CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000555 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000556 return LoadedC;
557
Chris Lattnercf7e8942009-10-22 06:44:07 +0000558 // Instead of loading constant c string, use corresponding integer value
559 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000560 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000561 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000562 unsigned StrLen = Str.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000563 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnered00b802009-10-23 06:23:49 +0000564 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000565 // Replace load with immediate integer if the result is an integer or fp
566 // value.
567 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000568 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000569 APInt StrVal(NumBits, 0);
570 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000571 if (DL.isLittleEndian()) {
Chris Lattnered00b802009-10-23 06:23:49 +0000572 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000573 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner51d2f702009-10-22 06:38:35 +0000574 StrVal = (StrVal << 8) | SingleChar;
575 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000576 } else {
Chris Lattnered00b802009-10-23 06:23:49 +0000577 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000578 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
579 StrVal = (StrVal << 8) | SingleChar;
580 }
581 // Append NULL at the end.
582 SingleChar = 0;
583 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000584 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000585
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000586 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
587 if (Ty->isFloatingPointTy())
588 Res = ConstantExpr::getBitCast(Res, Ty);
589 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000590 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000591 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000592
Chris Lattnercf7e8942009-10-22 06:44:07 +0000593 // If this load comes from anywhere in a constant global, and if the global
594 // is all undef or zero, we know what it loads.
Dan Gohman0f124e12011-01-24 18:53:32 +0000595 if (GlobalVariable *GV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000596 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000597 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000598 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
Chris Lattnercf7e8942009-10-22 06:44:07 +0000599 if (GV->getInitializer()->isNullValue())
600 return Constant::getNullValue(ResTy);
601 if (isa<UndefValue>(GV->getInitializer()))
602 return UndefValue::get(ResTy);
603 }
604 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000605
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000606 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 return FoldReinterpretLoadFromConstPtr(CE, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000608}
609
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000610static Constant *ConstantFoldLoadInst(const LoadInst *LI,
611 const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000612 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000613
Chris Lattner1664a4f2009-10-22 06:25:11 +0000614 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 return ConstantFoldLoadFromConstPtr(C, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000616
Craig Topper9f008862014-04-15 04:59:12 +0000617 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000618}
Chris Lattner44d68b92007-01-31 00:51:48 +0000619
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000620/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000621/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000622/// these together. If target data info is available, it is provided as DL,
623/// otherwise DL is null.
Chris Lattner44d68b92007-01-31 00:51:48 +0000624static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 Constant *Op1,
626 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000627 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000628
Chris Lattner44d68b92007-01-31 00:51:48 +0000629 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
630 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
631 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000632
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000633 if (Opc == Instruction::And) {
634 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000635 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
636 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000637 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
638 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000639 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
640 // All the bits of Op0 that the 'and' could be masking are already zero.
641 return Op0;
642 }
643 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
644 // All the bits of Op1 that the 'and' could be masking are already zero.
645 return Op1;
646 }
647
648 APInt KnownZero = KnownZero0 | KnownZero1;
649 APInt KnownOne = KnownOne0 & KnownOne1;
650 if ((KnownZero | KnownOne).isAllOnesValue()) {
651 return ConstantInt::get(Op0->getType(), KnownOne);
652 }
653 }
654
Chris Lattner44d68b92007-01-31 00:51:48 +0000655 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
656 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000657 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000658 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000659 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000660
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000661 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
662 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
663 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000664
Chris Lattner44d68b92007-01-31 00:51:48 +0000665 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000666 // PtrToInt may change the bitwidth so we have convert to the right size
667 // first.
668 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
669 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000670 }
671 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000672
Craig Topper9f008862014-04-15 04:59:12 +0000673 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000674}
675
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000676/// If array indices are not pointer-sized integers, explicitly cast them so
677/// that they aren't implicitly casted by the getelementptr.
David Blaikie4a2e73b2015-04-02 18:55:32 +0000678static Constant *CastGEPIndices(Type *SrcTy, ArrayRef<Constant *> Ops,
679 Type *ResultTy, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000680 const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000682
683 bool Any = false;
684 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000685 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000686 if ((i == 1 ||
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000687 !isa<StructType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000688 cast<PointerType>(Ops[0]->getType()->getScalarType())
689 ->getElementType(),
690 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000691 Ops[i]->getType() != IntPtrTy) {
692 Any = true;
693 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
694 true,
695 IntPtrTy,
696 true),
697 Ops[i], IntPtrTy));
698 } else
699 NewIdxs.push_back(Ops[i]);
700 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000701
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000702 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000703 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000704
David Blaikie4a2e73b2015-04-02 18:55:32 +0000705 Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ops[0], NewIdxs);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000706 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000707 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000708 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000709 }
710
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000711 return C;
712}
713
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000714/// Strip the pointer casts, but preserve the address space information.
715static Constant* StripPtrCastKeepAS(Constant* Ptr) {
716 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
717 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000718 Ptr = Ptr->stripPointerCasts();
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000719 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
720
721 // Preserve the address space number of the pointer.
722 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
723 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
724 OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000725 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000726 }
727 return Ptr;
728}
729
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000730/// If we can symbolically evaluate the GEP constant expression, do so.
David Blaikie4a2e73b2015-04-02 18:55:32 +0000731static Constant *SymbolicallyEvaluateGEP(Type *SrcTy, ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000732 Type *ResultTy, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000733 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000734 Constant *Ptr = Ops[0];
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000735 if (!Ptr->getType()->getPointerElementType()->isSized() ||
Nadav Rotem3924cb02011-12-05 06:29:09 +0000736 !Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000737 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000738
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000739 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Matt Arsenault8c789092013-08-12 23:15:58 +0000740 Type *ResultElementTy = ResultTy->getPointerElementType();
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000741
742 // If this is a constant expr gep that is effectively computing an
743 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000744 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000745 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000746
Chris Lattner5858e092011-01-06 06:19:46 +0000747 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
748 // "inttoptr (sub (ptrtoint Ptr), V)"
Matt Arsenault8c789092013-08-12 23:15:58 +0000749 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
Chris Lattner5858e092011-01-06 06:19:46 +0000750 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000751 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000752 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000753 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000754 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000755 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
756 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
757 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
758 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000759 Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000760 return Res;
761 }
762 }
Craig Topper9f008862014-04-15 04:59:12 +0000763 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000764 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000765
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000766 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000767 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000768 APInt(BitWidth,
769 DL.getIndexedOffset(
770 Ptr->getType(),
771 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000772 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000773
774 // If this is a GEP of a GEP, fold it all into a single GEP.
775 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000776 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000777
778 // Do not try the incorporate the sub-GEP if some index is not a number.
779 bool AllConstantInt = true;
780 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
781 if (!isa<ConstantInt>(NestedOps[i])) {
782 AllConstantInt = false;
783 break;
784 }
785 if (!AllConstantInt)
786 break;
787
Dan Gohman474e488c2010-03-10 19:31:51 +0000788 Ptr = cast<Constant>(GEP->getOperand(0));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000789 Offset += APInt(BitWidth, DL.getIndexedOffset(Ptr->getType(), NestedOps));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000790 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000791 }
792
Dan Gohman81ce8422009-08-19 18:18:36 +0000793 // If the base value for this address is a literal integer value, fold the
794 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000795 APInt BasePtr(BitWidth, 0);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000796 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
797 if (CE->getOpcode() == Instruction::IntToPtr) {
Jay Foad583abbc2010-12-07 08:25:19 +0000798 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
799 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000800 }
801 }
802
Dan Gohmana5ca5782010-03-18 19:34:33 +0000803 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000804 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Dan Gohman81ce8422009-08-19 18:18:36 +0000805 return ConstantExpr::getIntToPtr(C, ResultTy);
806 }
807
808 // Otherwise form a regular getelementptr. Recompute the indices so that
809 // we eliminate over-indexing of the notional static type array bounds.
810 // This makes it easy to determine if the getelementptr is "inbounds".
811 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000812 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000813 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000814 SmallVector<Constant *, 32> NewIdxs;
815
Dan Gohmanc59ba422009-08-19 22:46:59 +0000816 do {
Chris Lattner229907c2011-07-18 04:54:35 +0000817 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000818 if (ATy->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000819 // The only pointer indexing we'll do is on the first index of the GEP.
820 if (!NewIdxs.empty())
821 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000822
Chris Lattner77c36d62009-12-03 01:05:45 +0000823 // Only handle pointers to sized types, not pointers to functions.
824 if (!ATy->getElementType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000825 return nullptr;
Chris Lattner77c36d62009-12-03 01:05:45 +0000826 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000827
Dan Gohman81ce8422009-08-19 18:18:36 +0000828 // Determine which element of the array the offset points into.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 APInt ElemSize(BitWidth, DL.getTypeAllocSize(ATy->getElementType()));
Dan Gohman81ce8422009-08-19 18:18:36 +0000830 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000831 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000832 // index for this level and proceed to the next level to see if it can
833 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000834 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
835 else {
836 // The element size is non-zero divide the offset by the element
837 // size (rounding down), to compute the index at this level.
838 APInt NewIdx = Offset.udiv(ElemSize);
839 Offset -= NewIdx * ElemSize;
840 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
841 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000842 Ty = ATy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000843 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000844 // If we end up with an offset that isn't valid for this struct type, we
845 // can't re-form this GEP in a regular form, so bail out. The pointer
846 // operand likely went through casts that are necessary to make the GEP
847 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000848 const StructLayout &SL = *DL.getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000849 if (Offset.uge(SL.getSizeInBytes()))
850 break;
851
852 // Determine which field of the struct the offset points into. The
853 // getZExtValue is fine as we've already ensured that the offset is
854 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000855 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000856 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
857 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000858 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000859 Ty = STy->getTypeAtIndex(ElIdx);
860 } else {
Dan Gohmanc59ba422009-08-19 22:46:59 +0000861 // We've reached some non-indexable type.
862 break;
Dan Gohman81ce8422009-08-19 18:18:36 +0000863 }
Matt Arsenault8c789092013-08-12 23:15:58 +0000864 } while (Ty != ResultElementTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000865
866 // If we haven't used up the entire offset by descending the static
867 // type, then the offset is pointing into the middle of an indivisible
868 // member, so we can't simplify it.
869 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000870 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000871
Dan Gohman21c62162009-09-11 00:04:14 +0000872 // Create a GEP.
David Blaikie4a2e73b2015-04-02 18:55:32 +0000873 Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000874 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000875 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000876
Dan Gohmanc59ba422009-08-19 22:46:59 +0000877 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000878 // the type of what the original indices indexed, add a cast.
Matt Arsenault8c789092013-08-12 23:15:58 +0000879 if (Ty != ResultElementTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000880 C = FoldBitCast(C, ResultTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000881
882 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000883}
884
Chris Lattner6a6b3fb2007-12-11 07:29:44 +0000885
Chris Lattner44d68b92007-01-31 00:51:48 +0000886
887//===----------------------------------------------------------------------===//
888// Constant Folding public APIs
889//===----------------------------------------------------------------------===//
890
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000891/// Try to constant fold the specified instruction.
Duncan Sands763dec02010-11-23 10:16:18 +0000892/// If successful, the constant result is returned, if not, null is returned.
893/// Note that this fails if not all of the operands are constant. Otherwise,
894/// this function can only fail when attempting to fold instructions like loads
895/// and stores, which have no constant expression form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000896Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
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
Pete Cooper833f34d2015-05-12 20:05:31 +0000902 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +0000903 // If the incoming value is undef then skip it. Note that while we could
904 // skip the value if it is equal to the phi node itself we choose not to
905 // because that would break the rule that constant folding only applies if
906 // all operands are constants.
907 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000908 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000909 // If the incoming value is not a constant, then give up.
Duncan Sands1d27f0122010-11-14 12:53:18 +0000910 Constant *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000911 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +0000912 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000913 // Fold the PHI's operands.
914 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000915 C = ConstantFoldConstantExpression(NewC, DL, TLI);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000916 // If the incoming value is a different constant to
917 // the one we saw previously, then give up.
918 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +0000919 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +0000920 CommonValue = C;
921 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000922
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000923
Duncan Sands1d27f0122010-11-14 12:53:18 +0000924 // If we reach here, all incoming values are the same constant or undef.
925 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000926 }
927
928 // Scan the operand list, checking to see if they are all constants, if so,
929 // hand off to ConstantFoldInstOperands.
930 SmallVector<Constant*, 8> Ops;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000931 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
932 Constant *Op = dyn_cast<Constant>(*i);
933 if (!Op)
Craig Topper9f008862014-04-15 04:59:12 +0000934 return nullptr; // All operands not constant!
Chris Lattner2ae054a2007-01-30 23:45:45 +0000935
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000936 // Fold the Instruction's operands.
937 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000938 Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000939
940 Ops.push_back(Op);
941 }
942
Chris Lattnerd2265b42007-12-10 22:53:04 +0000943 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000944 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000945 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000946
Chris Lattner1664a4f2009-10-22 06:25:11 +0000947 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000948 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +0000949
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000950 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000951 return ConstantExpr::getInsertValue(
952 cast<Constant>(IVI->getAggregateOperand()),
953 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000954 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000955 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000956
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000957 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000958 return ConstantExpr::getExtractValue(
959 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000960 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000961 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000962
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000964}
965
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000966static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL,
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000968 const TargetLibraryInfo *TLI,
Craig Topper71b7b682014-08-21 05:55:13 +0000969 SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000970 SmallVector<Constant *, 8> Ops;
971 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
972 ++i) {
Dan Gohman580b80d2009-11-23 16:22:21 +0000973 Constant *NewC = cast<Constant>(*i);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000974 // Recursively fold the ConstantExpr's operands. If we have already folded
975 // a ConstantExpr, we don't have to process it again.
976 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000977 if (FoldedOps.insert(NewCE).second)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000978 NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000979 }
Dan Gohman580b80d2009-11-23 16:22:21 +0000980 Ops.push_back(NewC);
981 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000982
983 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000984 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000985 DL, TLI);
986 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000987}
988
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000989/// Attempt to fold the constant expression
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000990/// using the specified DataLayout. If successful, the constant result is
991/// result is returned, if not, null is returned.
992Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000993 const DataLayout &DL,
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000994 const TargetLibraryInfo *TLI) {
995 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000997}
998
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000999/// Attempt to constant fold an instruction with the
Chris Lattner2ae054a2007-01-30 23:45:45 +00001000/// specified opcode and operands. If successful, the constant result is
1001/// returned, if not, null is returned. Note that this function can fail when
1002/// attempting to fold instructions like loads and stores, which have no
1003/// constant expression form.
1004///
Dan Gohman580b80d2009-11-23 16:22:21 +00001005/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1006/// information, due to only being passed an opcode and operands. Constant
1007/// folding using this function strips this information.
1008///
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001009Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
Jay Foadf4b14a22011-07-19 13:32:40 +00001010 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001011 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001012 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +00001013 // Handle easy binops first.
Chris Lattnerd2265b42007-12-10 22:53:04 +00001014 if (Instruction::isBinaryOp(Opcode)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001015 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], DL))
Chris Lattner44d68b92007-01-31 00:51:48 +00001017 return C;
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001018 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001019
Owen Anderson487375e2009-07-29 18:55:55 +00001020 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner44d68b92007-01-31 00:51:48 +00001021 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001022
Chris Lattnerd2265b42007-12-10 22:53:04 +00001023 switch (Opcode) {
Craig Topper9f008862014-04-15 04:59:12 +00001024 default: return nullptr;
Chris Lattner8fb74c62010-01-02 01:22:23 +00001025 case Instruction::ICmp:
Craig Toppera2886c22012-02-07 05:05:23 +00001026 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
Chris Lattner2ae054a2007-01-30 23:45:45 +00001027 case Instruction::Call:
Jay Foadf4b14a22011-07-19 13:32:40 +00001028 if (Function *F = dyn_cast<Function>(Ops.back()))
Chris Lattner2ae054a2007-01-30 23:45:45 +00001029 if (canConstantFoldCallTo(F))
Chad Rosierc24b86f2011-12-01 03:08:23 +00001030 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
Craig Topper9f008862014-04-15 04:59:12 +00001031 return nullptr;
Chris Lattner460e34a2007-08-11 23:49:01 +00001032 case Instruction::PtrToInt:
1033 // If the input is a inttoptr, eliminate the pair. This requires knowing
1034 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1035 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (CE->getOpcode() == Instruction::IntToPtr) {
Chris Lattner460e34a2007-08-11 23:49:01 +00001037 Constant *Input = CE->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001038 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001040 if (PtrWidth < InWidth) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001041 Constant *Mask =
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001042 ConstantInt::get(CE->getContext(),
1043 APInt::getLowBitsSet(InWidth, PtrWidth));
Owen Anderson487375e2009-07-29 18:55:55 +00001044 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky730d5da2008-10-24 06:14:27 +00001045 }
Chris Lattner460e34a2007-08-11 23:49:01 +00001046 // Do a zext or trunc to get to the dest size.
Owen Anderson487375e2009-07-29 18:55:55 +00001047 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner460e34a2007-08-11 23:49:01 +00001048 }
1049 }
Owen Anderson487375e2009-07-29 18:55:55 +00001050 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner460e34a2007-08-11 23:49:01 +00001051 case Instruction::IntToPtr:
Duncan Sandsea68a6c2008-08-13 20:20:35 +00001052 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001053 // the int size is >= the ptr size and the address spaces are the same.
1054 // This requires knowing the width of a pointer, so it can't be done in
1055 // ConstantExpr::getCast.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001056 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001057 if (CE->getOpcode() == Instruction::PtrToInt) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001058 Constant *SrcPtr = CE->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001059 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001060 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1061
1062 if (MidIntSize >= SrcPtrSize) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001063 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1064 if (SrcAS == DestTy->getPointerAddressSpace())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001065 return FoldBitCast(CE->getOperand(0), DestTy, DL);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001066 }
1067 }
1068 }
Dan Gohman8a0eb362010-02-23 16:35:41 +00001069
Owen Anderson487375e2009-07-29 18:55:55 +00001070 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001071 case Instruction::Trunc:
1072 case Instruction::ZExt:
1073 case Instruction::SExt:
1074 case Instruction::FPTrunc:
1075 case Instruction::FPExt:
1076 case Instruction::UIToFP:
1077 case Instruction::SIToFP:
1078 case Instruction::FPToUI:
1079 case Instruction::FPToSI:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001080 case Instruction::AddrSpaceCast:
Owen Anderson487375e2009-07-29 18:55:55 +00001081 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001082 case Instruction::BitCast:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001083 return FoldBitCast(Ops[0], DestTy, DL);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001084 case Instruction::Select:
Owen Anderson487375e2009-07-29 18:55:55 +00001085 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001086 case Instruction::ExtractElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001087 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001088 case Instruction::InsertElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001089 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001090 case Instruction::ShuffleVector:
Owen Anderson487375e2009-07-29 18:55:55 +00001091 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
David Blaikie4a2e73b2015-04-02 18:55:32 +00001092 case Instruction::GetElementPtr: {
1093 Type *SrcTy = nullptr;
1094 if (Constant *C = CastGEPIndices(SrcTy, Ops, DestTy, DL, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001095 return C;
David Blaikie4a2e73b2015-04-02 18:55:32 +00001096 if (Constant *C = SymbolicallyEvaluateGEP(SrcTy, Ops, DestTy, DL, TLI))
Chris Lattner44d68b92007-01-31 00:51:48 +00001097 return C;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001098
David Blaikie4a2e73b2015-04-02 18:55:32 +00001099 return ConstantExpr::getGetElementPtr(SrcTy, Ops[0], Ops.slice(1));
1100 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001101 }
1102}
1103
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001104/// Attempt to constant fold a compare
Chris Lattnerd2265b42007-12-10 22:53:04 +00001105/// instruction (icmp/fcmp) with the specified operands. If it fails, it
1106/// returns a constant expression of the specified operands.
Chris Lattnerd2265b42007-12-10 22:53:04 +00001107Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001108 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001109 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001110 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001111 // fold: icmp (inttoptr x), null -> icmp x, 0
1112 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001113 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001114 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1115 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001116 // FIXME: The following comment is out of data and the DataLayout is here now.
1117 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001118 // around to know if bit truncation is happening.
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001119 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001120 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001121 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001122 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001123 // Convert the integer value to the right size to ensure we get the
1124 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001125 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001126 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001127 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001128 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001129 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001130
Chris Lattnerd2265b42007-12-10 22:53:04 +00001131 // Only do this transformation if the int is intptrty in size, otherwise
1132 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001133 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001134 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001135 if (CE0->getType() == IntPtrTy) {
1136 Constant *C = CE0->getOperand(0);
1137 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001138 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001139 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001140 }
1141 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001142
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001143 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001145 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001146 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001147
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001148 // Convert the integer value to the right size to ensure we get the
1149 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001150 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001151 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001152 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001153 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001154 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001155 }
1156
Chandler Carruth7ec50852012-11-01 08:07:29 +00001157 // Only do this transformation if the int is intptrty in size, otherwise
1158 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001159 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001160 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001161 if (CE0->getType() == IntPtrTy &&
1162 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001163 return ConstantFoldCompareInstOperands(
1164 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001165 }
1166 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001167 }
1168 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001169
Chris Lattner8fb74c62010-01-02 01:22:23 +00001170 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1171 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1172 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1173 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174 Constant *LHS = ConstantFoldCompareInstOperands(
1175 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1176 Constant *RHS = ConstantFoldCompareInstOperands(
1177 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001178 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001179 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1180 Constant *Ops[] = { LHS, RHS };
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001181 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, DL, TLI);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001182 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001183 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001184
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001185 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001186}
1187
1188
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001189/// Given a constant and a getelementptr constantexpr, return the constant value
1190/// being addressed by the constant expression, or null if something is funny
1191/// and we can't decide.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001192Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001193 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001194 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001195 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001196
1197 // Loop over all of the operands, tracking down which value we are
1198 // addressing.
1199 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1200 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001201 if (!C)
1202 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001203 }
1204 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001205}
1206
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001207/// Given a constant and getelementptr indices (with an *implied* zero pointer
1208/// index that is not in the list), return the constant value being addressed by
1209/// a virtual load, or null if something is funny and we can't decide.
Chris Lattnerf488b352012-01-24 05:43:50 +00001210Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1211 ArrayRef<Constant*> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001212 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001213 // addressing.
1214 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +00001215 C = C->getAggregateElement(Indices[i]);
Craig Topper9f008862014-04-15 04:59:12 +00001216 if (!C)
1217 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001218 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001219 return C;
1220}
1221
1222
1223//===----------------------------------------------------------------------===//
1224// Constant Folding for Calls
1225//
John Criswell970af112005-10-27 16:00:10 +00001226
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001227/// Return true if it's even possible to fold a call to the specified function.
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001228bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001229 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001230 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001231 case Intrinsic::minnum:
1232 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001233 case Intrinsic::log:
1234 case Intrinsic::log2:
1235 case Intrinsic::log10:
1236 case Intrinsic::exp:
1237 case Intrinsic::exp2:
1238 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001239 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001240 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001241 case Intrinsic::sin:
1242 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001243 case Intrinsic::trunc:
1244 case Intrinsic::rint:
1245 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001246 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001247 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001248 case Intrinsic::bswap:
1249 case Intrinsic::ctpop:
1250 case Intrinsic::ctlz:
1251 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001252 case Intrinsic::fma:
1253 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001254 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001255 case Intrinsic::round:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001256 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001257 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001258 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001259 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001260 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001261 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001262 case Intrinsic::convert_from_fp16:
1263 case Intrinsic::convert_to_fp16:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001264 case Intrinsic::x86_sse_cvtss2si:
1265 case Intrinsic::x86_sse_cvtss2si64:
1266 case Intrinsic::x86_sse_cvttss2si:
1267 case Intrinsic::x86_sse_cvttss2si64:
1268 case Intrinsic::x86_sse2_cvtsd2si:
1269 case Intrinsic::x86_sse2_cvtsd2si64:
1270 case Intrinsic::x86_sse2_cvttsd2si:
1271 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001272 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001273 default:
1274 return false;
1275 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001276 }
1277
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001278 if (!F->hasName())
1279 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001280 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001281
Chris Lattner785f9982007-08-08 06:55:43 +00001282 // In these cases, the check of the length is required. We don't want to
1283 // return true for a name like "cos\0blah" which strcmp would return equal to
1284 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001285 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001286 default: return false;
1287 case 'a':
Chad Rosierc0955a52013-02-20 23:57:30 +00001288 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
Chris Lattner785f9982007-08-08 06:55:43 +00001289 case 'c':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001290 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattner785f9982007-08-08 06:55:43 +00001291 case 'e':
Chris Lattner713d5232011-05-22 22:22:35 +00001292 return Name == "exp" || Name == "exp2";
Chris Lattner785f9982007-08-08 06:55:43 +00001293 case 'f':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001294 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattner785f9982007-08-08 06:55:43 +00001295 case 'l':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001296 return Name == "log" || Name == "log10";
Chris Lattner785f9982007-08-08 06:55:43 +00001297 case 'p':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001298 return Name == "pow";
Chris Lattner785f9982007-08-08 06:55:43 +00001299 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001300 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1301 Name == "sinf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001302 case 't':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001303 return Name == "tan" || Name == "tanh";
John Criswell970af112005-10-27 16:00:10 +00001304 }
1305}
1306
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001307static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001308 if (Ty->isHalfTy()) {
1309 APFloat APF(V);
1310 bool unused;
1311 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1312 return ConstantFP::get(Ty->getContext(), APF);
1313 }
Chris Lattner351534f2009-10-05 05:06:24 +00001314 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001315 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001316 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001317 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001318 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001319
1320}
1321
Alp Tokerc817d6a2014-06-09 18:28:53 +00001322namespace {
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001323/// Clear the floating-point exception state.
Alp Tokerc817d6a2014-06-09 18:28:53 +00001324static inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001325#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001326 feclearexcept(FE_ALL_EXCEPT);
1327#endif
1328 errno = 0;
1329}
1330
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001331/// Test if a floating-point exception was raised.
Alp Tokerc817d6a2014-06-09 18:28:53 +00001332static inline bool llvm_fenv_testexcept() {
1333 int errno_val = errno;
1334 if (errno_val == ERANGE || errno_val == EDOM)
1335 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001336#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001337 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1338 return true;
1339#endif
1340 return false;
1341}
1342} // End namespace
1343
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001344static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1345 Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001346 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001347 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001348 if (llvm_fenv_testexcept()) {
1349 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001350 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001351 }
1352
1353 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001354}
1355
Dan Gohman72efc042007-07-16 15:26:22 +00001356static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
Chris Lattner229907c2011-07-18 04:54:35 +00001357 double V, double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001358 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001359 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001360 if (llvm_fenv_testexcept()) {
1361 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001362 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001363 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001364
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001365 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001366}
1367
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001368/// Attempt to fold an SSE floating point to integer conversion of a constant
1369/// floating point. If roundTowardZero is false, the default IEEE rounding is
1370/// used (toward nearest, ties to even). This matches the behavior of the
1371/// non-truncating SSE instructions in the default rounding mode. The desired
1372/// integer type Ty is used to select how many bits are available for the
1373/// result. Returns null if the conversion cannot be performed, otherwise
1374/// returns the Constant value resulting from the conversion.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001375static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1376 bool roundTowardZero, Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001377 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001378 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001379 assert(ResultWidth <= 64 &&
1380 "Can only constant fold conversions to 64 and 32 bit ints");
1381
1382 uint64_t UIntVal;
1383 bool isExact = false;
1384 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1385 : APFloat::rmNearestTiesToEven;
1386 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1387 /*isSigned=*/true, mode,
1388 &isExact);
1389 if (status != APFloat::opOK && status != APFloat::opInexact)
Craig Topper9f008862014-04-15 04:59:12 +00001390 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001391 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1392}
1393
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001394static double getValueAsDouble(ConstantFP *Op) {
1395 Type *Ty = Op->getType();
1396
1397 if (Ty->isFloatTy())
1398 return Op->getValueAPF().convertToFloat();
1399
1400 if (Ty->isDoubleTy())
1401 return Op->getValueAPF().convertToDouble();
1402
1403 bool unused;
1404 APFloat APF = Op->getValueAPF();
1405 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1406 return APF.convertToDouble();
1407}
1408
Benjamin Kramer061d1472014-03-05 19:41:48 +00001409static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1410 Type *Ty, ArrayRef<Constant *> Operands,
1411 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001412 if (Operands.size() == 1) {
John Criswell970af112005-10-27 16:00:10 +00001413 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001414 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001415 APFloat Val(Op->getValueAPF());
1416
1417 bool lost = false;
1418 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1419
Benjamin Kramer061d1472014-03-05 19:41:48 +00001420 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001421 }
1422
Owen Andersond4ebfd82013-02-06 22:43:31 +00001423 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001424 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001425
Karthik Bhatb67688a2014-03-07 04:36:21 +00001426 if (IntrinsicID == Intrinsic::round) {
1427 APFloat V = Op->getValueAPF();
1428 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1429 return ConstantFP::get(Ty->getContext(), V);
1430 }
1431
Karthik Bhatd818e382015-07-21 08:52:23 +00001432 if (IntrinsicID == Intrinsic::floor) {
1433 APFloat V = Op->getValueAPF();
1434 V.roundToIntegral(APFloat::rmTowardNegative);
1435 return ConstantFP::get(Ty->getContext(), V);
1436 }
1437
1438 if (IntrinsicID == Intrinsic::ceil) {
1439 APFloat V = Op->getValueAPF();
1440 V.roundToIntegral(APFloat::rmTowardPositive);
1441 return ConstantFP::get(Ty->getContext(), V);
1442 }
1443
1444 if (IntrinsicID == Intrinsic::trunc) {
1445 APFloat V = Op->getValueAPF();
1446 V.roundToIntegral(APFloat::rmTowardZero);
1447 return ConstantFP::get(Ty->getContext(), V);
1448 }
1449
1450 if (IntrinsicID == Intrinsic::rint) {
1451 APFloat V = Op->getValueAPF();
1452 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1453 return ConstantFP::get(Ty->getContext(), V);
1454 }
1455
1456 if (IntrinsicID == Intrinsic::nearbyint) {
1457 APFloat V = Op->getValueAPF();
1458 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1459 return ConstantFP::get(Ty->getContext(), V);
1460 }
1461
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001462 /// We only fold functions with finite arguments. Folding NaN and inf is
1463 /// likely to be aborted with an exception anyway, and some host libms
1464 /// have known errors raising exceptions.
1465 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001466 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001467
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001468 /// Currently APFloat versions of these functions do not exist, so we use
1469 /// the host native double versions. Float versions are not called
1470 /// directly but for all these it is true (float)(f((double)arg)) ==
1471 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001472 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001473
Benjamin Kramer061d1472014-03-05 19:41:48 +00001474 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001475 default: break;
1476 case Intrinsic::fabs:
1477 return ConstantFoldFP(fabs, V, Ty);
1478 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001479 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001480 case Intrinsic::log:
1481 return ConstantFoldFP(log, V, Ty);
1482 case Intrinsic::log10:
1483 return ConstantFoldFP(log10, V, Ty);
1484 case Intrinsic::exp:
1485 return ConstantFoldFP(exp, V, Ty);
1486 case Intrinsic::exp2:
1487 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001488 case Intrinsic::sin:
1489 return ConstantFoldFP(sin, V, Ty);
1490 case Intrinsic::cos:
1491 return ConstantFoldFP(cos, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001492 }
1493
Benjamin Kramer061d1472014-03-05 19:41:48 +00001494 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001495 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001496
Daniel Dunbarca414c72009-07-26 08:34:35 +00001497 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001498 case 'a':
Chad Rosier576c0f82011-12-01 23:16:03 +00001499 if (Name == "acos" && TLI->has(LibFunc::acos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001500 return ConstantFoldFP(acos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001501 else if (Name == "asin" && TLI->has(LibFunc::asin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001502 return ConstantFoldFP(asin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001503 else if (Name == "atan" && TLI->has(LibFunc::atan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001504 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001505 break;
1506 case 'c':
Chad Rosier576c0f82011-12-01 23:16:03 +00001507 if (Name == "ceil" && TLI->has(LibFunc::ceil))
Chris Lattner46b5c642009-11-06 04:27:31 +00001508 return ConstantFoldFP(ceil, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001509 else if (Name == "cos" && TLI->has(LibFunc::cos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001510 return ConstantFoldFP(cos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001511 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001512 return ConstantFoldFP(cosh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001513 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001514 return ConstantFoldFP(cos, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001515 break;
1516 case 'e':
Chad Rosier576c0f82011-12-01 23:16:03 +00001517 if (Name == "exp" && TLI->has(LibFunc::exp))
Chris Lattner46b5c642009-11-06 04:27:31 +00001518 return ConstantFoldFP(exp, V, Ty);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001519
Chad Rosier576c0f82011-12-01 23:16:03 +00001520 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
Chris Lattner713d5232011-05-22 22:22:35 +00001521 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1522 // C99 library.
1523 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1524 }
Chris Lattner785f9982007-08-08 06:55:43 +00001525 break;
1526 case 'f':
Chad Rosier576c0f82011-12-01 23:16:03 +00001527 if (Name == "fabs" && TLI->has(LibFunc::fabs))
Chris Lattner46b5c642009-11-06 04:27:31 +00001528 return ConstantFoldFP(fabs, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001529 else if (Name == "floor" && TLI->has(LibFunc::floor))
Chris Lattner46b5c642009-11-06 04:27:31 +00001530 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001531 break;
1532 case 'l':
Chad Rosier576c0f82011-12-01 23:16:03 +00001533 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
Chris Lattner46b5c642009-11-06 04:27:31 +00001534 return ConstantFoldFP(log, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001535 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
Chris Lattner46b5c642009-11-06 04:27:31 +00001536 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001537 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001538 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001539 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001540 return ConstantFoldFP(sqrt, V, Ty);
Sanjay Patel7b2cd9a2014-10-01 20:36:33 +00001541 else {
1542 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1543 // all guarantee or favor returning NaN - the square root of a
1544 // negative number is not defined for the LLVM sqrt intrinsic.
1545 // This is because the intrinsic should only be emitted in place of
1546 // libm's sqrt function when using "no-nans-fp-math".
1547 return UndefValue::get(Ty);
1548 }
Chris Lattner785f9982007-08-08 06:55:43 +00001549 }
1550 break;
1551 case 's':
Chad Rosier576c0f82011-12-01 23:16:03 +00001552 if (Name == "sin" && TLI->has(LibFunc::sin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001553 return ConstantFoldFP(sin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001554 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001555 return ConstantFoldFP(sinh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001556 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
Chris Lattner46b5c642009-11-06 04:27:31 +00001557 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001558 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001559 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001560 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001561 return ConstantFoldFP(sin, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001562 break;
1563 case 't':
Chad Rosier576c0f82011-12-01 23:16:03 +00001564 if (Name == "tan" && TLI->has(LibFunc::tan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001565 return ConstantFoldFP(tan, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001566 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001567 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001568 break;
1569 default:
1570 break;
John Criswell970af112005-10-27 16:00:10 +00001571 }
Craig Topper9f008862014-04-15 04:59:12 +00001572 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001573 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001574
Chris Lattner9ca7c092009-10-05 05:00:35 +00001575 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001576 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001577 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001578 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001579 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001580 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001581 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001582 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001583
1584 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001585 APFloat::opStatus status = Val.convert(
1586 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001587
1588 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001589 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001590 assert(status == APFloat::opOK && !lost &&
1591 "Precision lost during fp16 constfolding");
1592
Benjamin Kramer061d1472014-03-05 19:41:48 +00001593 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001594 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001595 default:
Craig Topper9f008862014-04-15 04:59:12 +00001596 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001597 }
John Criswell970af112005-10-27 16:00:10 +00001598 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001599
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001600 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001601 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001602 isa<ConstantDataVector>(Operands[0])) {
1603 Constant *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001604 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001605 default: break;
1606 case Intrinsic::x86_sse_cvtss2si:
1607 case Intrinsic::x86_sse_cvtss2si64:
1608 case Intrinsic::x86_sse2_cvtsd2si:
1609 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001610 if (ConstantFP *FPOp =
1611 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1612 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1613 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001614 case Intrinsic::x86_sse_cvttss2si:
1615 case Intrinsic::x86_sse_cvttss2si64:
1616 case Intrinsic::x86_sse2_cvttsd2si:
1617 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001618 if (ConstantFP *FPOp =
1619 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001620 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001621 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001622 }
1623 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001624
Dan Gohmancf39be32010-02-17 00:54:58 +00001625 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001626 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001627 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001628 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001629 }
1630
Craig Topper9f008862014-04-15 04:59:12 +00001631 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001632 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001633
Jay Foadf4b14a22011-07-19 13:32:40 +00001634 if (Operands.size() == 2) {
John Criswell970af112005-10-27 16:00:10 +00001635 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001636 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001637 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001638 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001639
John Criswell970af112005-10-27 16:00:10 +00001640 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001641 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001642 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001643
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001644 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001645 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001646 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1647 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001648 if (IntrinsicID == Intrinsic::copysign) {
1649 APFloat V1 = Op1->getValueAPF();
1650 APFloat V2 = Op2->getValueAPF();
1651 V1.copySign(V2);
1652 return ConstantFP::get(Ty->getContext(), V1);
1653 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001654
1655 if (IntrinsicID == Intrinsic::minnum) {
1656 const APFloat &C1 = Op1->getValueAPF();
1657 const APFloat &C2 = Op2->getValueAPF();
1658 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1659 }
1660
1661 if (IntrinsicID == Intrinsic::maxnum) {
1662 const APFloat &C1 = Op1->getValueAPF();
1663 const APFloat &C2 = Op2->getValueAPF();
1664 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1665 }
1666
Chad Rosier0155a632011-12-03 00:00:03 +00001667 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001668 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001669 if (Name == "pow" && TLI->has(LibFunc::pow))
Chris Lattner46b5c642009-11-06 04:27:31 +00001670 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001671 if (Name == "fmod" && TLI->has(LibFunc::fmod))
Chris Lattner46b5c642009-11-06 04:27:31 +00001672 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001673 if (Name == "atan2" && TLI->has(LibFunc::atan2))
Chris Lattner46b5c642009-11-06 04:27:31 +00001674 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattner26933dd2007-01-15 06:27:37 +00001675 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001676 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1677 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001678 APFloat((float)std::pow((float)Op1V,
1679 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001680 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1681 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001682 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001683 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001684 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1685 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001686 APFloat((double)std::pow((double)Op1V,
1687 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001688 }
Craig Topper9f008862014-04-15 04:59:12 +00001689 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001690 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001691
Chris Lattner59d93982009-10-05 05:26:04 +00001692 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1693 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001694 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001695 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001696 case Intrinsic::sadd_with_overflow:
1697 case Intrinsic::uadd_with_overflow:
1698 case Intrinsic::ssub_with_overflow:
1699 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001700 case Intrinsic::smul_with_overflow:
1701 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001702 APInt Res;
1703 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001704 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001705 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001706 case Intrinsic::sadd_with_overflow:
1707 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1708 break;
1709 case Intrinsic::uadd_with_overflow:
1710 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1711 break;
1712 case Intrinsic::ssub_with_overflow:
1713 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1714 break;
1715 case Intrinsic::usub_with_overflow:
1716 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1717 break;
1718 case Intrinsic::smul_with_overflow:
1719 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1720 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001721 case Intrinsic::umul_with_overflow:
1722 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1723 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001724 }
Chris Lattner59d93982009-10-05 05:26:04 +00001725 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001726 ConstantInt::get(Ty->getContext(), Res),
1727 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001728 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001729 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001730 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001731 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001732 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1733 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001734 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1735 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001736 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1737 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001738 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001739 }
1740 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001741
Craig Topper9f008862014-04-15 04:59:12 +00001742 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001743 }
Craig Topper9f008862014-04-15 04:59:12 +00001744 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001745 }
Matt Arsenault83778582014-03-05 00:02:00 +00001746
1747 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001748 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001749
1750 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1751 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1752 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001753 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001754 default: break;
1755 case Intrinsic::fma:
1756 case Intrinsic::fmuladd: {
1757 APFloat V = Op1->getValueAPF();
1758 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1759 Op3->getValueAPF(),
1760 APFloat::rmNearestTiesToEven);
1761 if (s != APFloat::opInvalidOp)
1762 return ConstantFP::get(Ty->getContext(), V);
1763
Craig Topper9f008862014-04-15 04:59:12 +00001764 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001765 }
1766 }
1767 }
1768 }
1769 }
1770
Craig Topper9f008862014-04-15 04:59:12 +00001771 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001772}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001773
1774static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1775 VectorType *VTy,
1776 ArrayRef<Constant *> Operands,
1777 const TargetLibraryInfo *TLI) {
1778 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1779 SmallVector<Constant *, 4> Lane(Operands.size());
1780 Type *Ty = VTy->getElementType();
1781
1782 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1783 // Gather a column of constants.
1784 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1785 Constant *Agg = Operands[J]->getAggregateElement(I);
1786 if (!Agg)
1787 return nullptr;
1788
1789 Lane[J] = Agg;
1790 }
1791
1792 // Use the regular scalar folding to simplify this column.
1793 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1794 if (!Folded)
1795 return nullptr;
1796 Result[I] = Folded;
1797 }
1798
1799 return ConstantVector::get(Result);
1800}
1801
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001802/// Attempt to constant fold a call to the specified function
Benjamin Kramer061d1472014-03-05 19:41:48 +00001803/// with the specified arguments, returning null if unsuccessful.
1804Constant *
1805llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1806 const TargetLibraryInfo *TLI) {
1807 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001808 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001809 StringRef Name = F->getName();
1810
1811 Type *Ty = F->getReturnType();
1812
1813 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1814 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1815
1816 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1817}